org.el 942 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891
  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. (defsubst org-uniquify (list)
  170. "Non-destructively remove duplicate elements from LIST."
  171. (let ((res (copy-sequence list))) (delete-dups res)))
  172. (defsubst org-get-at-bol (property)
  173. "Get text property PROPERTY at the beginning of line."
  174. (get-text-property (point-at-bol) property))
  175. (defsubst org-trim (s &optional keep-lead)
  176. "Remove whitespace at the beginning and the end of string S.
  177. When optional argument KEEP-LEAD is non-nil, removing blank lines
  178. at the beginning of the string does not affect leading indentation."
  179. (replace-regexp-in-string
  180. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  181. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  182. ;; load languages based on value of `org-babel-load-languages'
  183. (defvar org-babel-load-languages)
  184. ;;;###autoload
  185. (defun org-babel-do-load-languages (sym value)
  186. "Load the languages defined in `org-babel-load-languages'."
  187. (set-default sym value)
  188. (dolist (pair org-babel-load-languages)
  189. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  190. (if active
  191. (require (intern (concat "ob-" lang)))
  192. (funcall 'fmakunbound
  193. (intern (concat "org-babel-execute:" lang)))
  194. (funcall 'fmakunbound
  195. (intern (concat "org-babel-expand-body:" lang)))))))
  196. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  197. ;;;###autoload
  198. (defun org-babel-load-file (file &optional compile)
  199. "Load Emacs Lisp source code blocks in the Org FILE.
  200. This function exports the source code using `org-babel-tangle'
  201. and then loads the resulting file using `load-file'. With prefix
  202. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  203. file to byte-code before it is loaded."
  204. (interactive "fFile to load: \nP")
  205. (let* ((age (lambda (file)
  206. (float-time
  207. (time-subtract (current-time)
  208. (nth 5 (or (file-attributes (file-truename file))
  209. (file-attributes file)))))))
  210. (base-name (file-name-sans-extension file))
  211. (exported-file (concat base-name ".el")))
  212. ;; tangle if the Org file is newer than the elisp file
  213. (unless (and (file-exists-p exported-file)
  214. (> (funcall age file) (funcall age exported-file)))
  215. ;; Tangle-file traversal returns reversed list of tangled files
  216. ;; and we want to evaluate the first target.
  217. (setq exported-file
  218. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  219. (message "%s %s"
  220. (if compile
  221. (progn (byte-compile-file exported-file 'load)
  222. "Compiled and loaded")
  223. (progn (load-file exported-file) "Loaded"))
  224. exported-file)))
  225. (defcustom org-babel-load-languages '((emacs-lisp . t))
  226. "Languages which can be evaluated in Org buffers.
  227. This list can be used to load support for any of the languages
  228. below, note that each language will depend on a different set of
  229. system executables and/or Emacs modes. When a language is
  230. \"loaded\", then code blocks in that language can be evaluated
  231. with `org-babel-execute-src-block' bound by default to C-c
  232. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  233. be set to remove code block evaluation from the C-c C-c
  234. keybinding. By default only Emacs Lisp (which has no
  235. requirements) is loaded."
  236. :group 'org-babel
  237. :set 'org-babel-do-load-languages
  238. :version "24.1"
  239. :type '(alist :tag "Babel Languages"
  240. :key-type
  241. (choice
  242. (const :tag "Awk" awk)
  243. (const :tag "C" C)
  244. (const :tag "R" R)
  245. (const :tag "Asymptote" asymptote)
  246. (const :tag "Calc" calc)
  247. (const :tag "Clojure" clojure)
  248. (const :tag "CSS" css)
  249. (const :tag "Ditaa" ditaa)
  250. (const :tag "Dot" dot)
  251. (const :tag "Emacs Lisp" emacs-lisp)
  252. (const :tag "Forth" forth)
  253. (const :tag "Fortran" fortran)
  254. (const :tag "Gnuplot" gnuplot)
  255. (const :tag "Haskell" haskell)
  256. (const :tag "hledger" hledger)
  257. (const :tag "IO" io)
  258. (const :tag "J" J)
  259. (const :tag "Java" java)
  260. (const :tag "Javascript" js)
  261. (const :tag "LaTeX" latex)
  262. (const :tag "Ledger" ledger)
  263. (const :tag "Lilypond" lilypond)
  264. (const :tag "Lisp" lisp)
  265. (const :tag "Makefile" makefile)
  266. (const :tag "Maxima" maxima)
  267. (const :tag "Matlab" matlab)
  268. (const :tag "Mscgen" mscgen)
  269. (const :tag "Ocaml" ocaml)
  270. (const :tag "Octave" octave)
  271. (const :tag "Org" org)
  272. (const :tag "Perl" perl)
  273. (const :tag "Pico Lisp" picolisp)
  274. (const :tag "PlantUML" plantuml)
  275. (const :tag "Python" python)
  276. (const :tag "Ruby" ruby)
  277. (const :tag "Sass" sass)
  278. (const :tag "Scala" scala)
  279. (const :tag "Scheme" scheme)
  280. (const :tag "Screen" screen)
  281. (const :tag "Shell Script" shell)
  282. (const :tag "Shen" shen)
  283. (const :tag "Sql" sql)
  284. (const :tag "Sqlite" sqlite)
  285. (const :tag "Stan" stan)
  286. (const :tag "ebnf2ps" ebnf2ps))
  287. :value-type (boolean :tag "Activate" :value t)))
  288. ;;;; Customization variables
  289. (defcustom org-clone-delete-id nil
  290. "Remove ID property of clones of a subtree.
  291. When non-nil, clones of a subtree don't inherit the ID property.
  292. Otherwise they inherit the ID property with a new unique
  293. identifier."
  294. :type 'boolean
  295. :version "24.1"
  296. :group 'org-id)
  297. ;;; Version
  298. (org-check-version)
  299. ;;;###autoload
  300. (defun org-version (&optional here full message)
  301. "Show the Org version.
  302. Interactively, or when MESSAGE is non-nil, show it in echo area.
  303. With prefix argument, or when HERE is non-nil, insert it at point.
  304. In non-interactive uses, a reduced version string is output unless
  305. FULL is given."
  306. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  307. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  308. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  309. (load-suffixes (list ".el"))
  310. (org-install-dir
  311. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  312. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  313. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  314. (let* ((load-suffixes save-load-suffixes)
  315. (release (org-release))
  316. (git-version (org-git-version))
  317. (version (format "Org mode version %s (%s @ %s)"
  318. release
  319. git-version
  320. (if org-install-dir
  321. (if (string= org-dir org-install-dir)
  322. org-install-dir
  323. (concat "mixed installation! "
  324. org-install-dir
  325. " and "
  326. org-dir))
  327. "org-loaddefs.el can not be found!")))
  328. (version1 (if full version release)))
  329. (when here (insert version1))
  330. (when message (message "%s" version1))
  331. version1)))
  332. (defconst org-version (org-version))
  333. ;;; Syntax Constants
  334. ;;;; Block
  335. (defconst org-block-regexp
  336. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  337. "Regular expression for hiding blocks.")
  338. (defconst org-dblock-start-re
  339. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  340. "Matches the start line of a dynamic block, with parameters.")
  341. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  342. "Matches the end of a dynamic block.")
  343. ;;;; Clock and Planning
  344. (defconst org-clock-string "CLOCK:"
  345. "String used as prefix for timestamps clocking work hours on an item.")
  346. (defvar org-closed-string "CLOSED:"
  347. "String used as the prefix for timestamps logging closing a TODO entry.")
  348. (defvar org-deadline-string "DEADLINE:"
  349. "String to mark deadline entries.
  350. \\<org-mode-map>
  351. A deadline is this string, followed by a time stamp. It must be
  352. a word, terminated by a colon. You can insert a schedule keyword
  353. and a timestamp with `\\[org-deadline]'.")
  354. (defvar org-scheduled-string "SCHEDULED:"
  355. "String to mark scheduled TODO entries.
  356. \\<org-mode-map>
  357. A schedule is this string, followed by a time stamp. It must be
  358. a word, terminated by a colon. You can insert a schedule keyword
  359. and a timestamp with `\\[org-schedule]'.")
  360. (defconst org-ds-keyword-length
  361. (+ 2
  362. (apply #'max
  363. (mapcar #'length
  364. (list org-deadline-string org-scheduled-string
  365. org-clock-string org-closed-string))))
  366. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  367. (defconst org-planning-line-re
  368. (concat "^[ \t]*"
  369. (regexp-opt
  370. (list org-closed-string org-deadline-string org-scheduled-string)
  371. t))
  372. "Matches a line with planning info.
  373. Matched keyword is in group 1.")
  374. (defconst org-clock-line-re
  375. (concat "^[ \t]*" org-clock-string)
  376. "Matches a line with clock info.")
  377. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  378. "Matches the DEADLINE keyword.")
  379. (defconst org-deadline-time-regexp
  380. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  381. "Matches the DEADLINE keyword together with a time stamp.")
  382. (defconst org-deadline-time-hour-regexp
  383. (concat "\\<" org-deadline-string
  384. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  385. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  386. (defconst org-deadline-line-regexp
  387. (concat "\\<\\(" org-deadline-string "\\).*")
  388. "Matches the DEADLINE keyword and the rest of the line.")
  389. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  390. "Matches the SCHEDULED keyword.")
  391. (defconst org-scheduled-time-regexp
  392. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  393. "Matches the SCHEDULED keyword together with a time stamp.")
  394. (defconst org-scheduled-time-hour-regexp
  395. (concat "\\<" org-scheduled-string
  396. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  397. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  398. (defconst org-closed-time-regexp
  399. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  400. "Matches the CLOSED keyword together with a time stamp.")
  401. (defconst org-keyword-time-regexp
  402. (concat "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string
  405. org-clock-string)
  406. t)
  407. " *[[<]\\([^]>]+\\)[]>]")
  408. "Matches any of the 4 keywords, together with the time stamp.")
  409. (defconst org-keyword-time-not-clock-regexp
  410. (concat
  411. "\\<"
  412. (regexp-opt
  413. (list org-scheduled-string org-deadline-string org-closed-string) t)
  414. " *[[<]\\([^]>]+\\)[]>]")
  415. "Matches any of the 3 keywords, together with the time stamp.")
  416. (defconst org-maybe-keyword-time-regexp
  417. (concat "\\(\\<"
  418. (regexp-opt
  419. (list org-scheduled-string org-deadline-string org-closed-string
  420. org-clock-string)
  421. t)
  422. "\\)?"
  423. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  424. "\\|"
  425. "<%%([^\r\n>]*>\\)")
  426. "Matches a timestamp, possibly preceded by a keyword.")
  427. (defconst org-all-time-keywords
  428. (mapcar (lambda (w) (substring w 0 -1))
  429. (list org-scheduled-string org-deadline-string
  430. org-clock-string org-closed-string))
  431. "List of time keywords.")
  432. ;;;; Drawer
  433. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  434. "Matches first or last line of a hidden block.
  435. Group 1 contains drawer's name or \"END\".")
  436. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  437. "Regular expression matching the first line of a property drawer.")
  438. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  439. "Regular expression matching the last line of a property drawer.")
  440. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  441. "Regular expression matching the first line of a clock drawer.")
  442. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  443. "Regular expression matching the last line of a clock drawer.")
  444. (defconst org-property-drawer-re
  445. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  446. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  447. "[ \t]*:END:[ \t]*$")
  448. "Matches an entire property drawer.")
  449. (defconst org-clock-drawer-re
  450. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  451. org-clock-drawer-end-re "\\)\n?")
  452. "Matches an entire clock drawer.")
  453. ;;;; Headline
  454. (defconst org-heading-keyword-regexp-format
  455. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  456. "Printf format for a regexp matching a headline with some keyword.
  457. This regexp will match the headline of any node which has the
  458. exact keyword that is put into the format. The keyword isn't in
  459. any group by default, but the stars and the body are.")
  460. (defconst org-heading-keyword-maybe-regexp-format
  461. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  462. "Printf format for a regexp matching a headline, possibly with some keyword.
  463. This regexp can match any headline with the specified keyword, or
  464. without a keyword. The keyword isn't in any group by default,
  465. but the stars and the body are.")
  466. (defconst org-archive-tag "ARCHIVE"
  467. "The tag that marks a subtree as archived.
  468. An archived subtree does not open during visibility cycling, and does
  469. not contribute to the agenda listings.")
  470. (eval-and-compile
  471. (defconst org-comment-string "COMMENT"
  472. "Entries starting with this keyword will never be exported.
  473. \\<org-mode-map>
  474. An entry can be toggled between COMMENT and normal with
  475. `\\[org-toggle-comment]'."))
  476. ;;;; LaTeX Environments and Fragments
  477. (defconst org-latex-regexps
  478. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  479. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  480. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  481. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  482. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  483. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  484. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  485. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  486. "Regular expressions for matching embedded LaTeX.")
  487. ;;;; Node Property
  488. (defconst org-effort-property "Effort"
  489. "The property that is being used to keep track of effort estimates.
  490. Effort estimates given in this property need to have the format H:MM.")
  491. ;;;; Table
  492. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  493. "Detect an org-type or table-type table.")
  494. (defconst org-table-line-regexp "^[ \t]*|"
  495. "Detect an org-type table line.")
  496. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  497. "Detect an org-type table line.")
  498. (defconst org-table-hline-regexp "^[ \t]*|-"
  499. "Detect an org-type table hline.")
  500. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  501. "Detect a table-type table hline.")
  502. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  503. "Detect the first line outside a table when searching from within it.
  504. This works for both table types.")
  505. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  506. "Detect a #+TBLFM line.")
  507. ;;;; Timestamp
  508. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  509. "Regular expression for fast time stamp matching.")
  510. (defconst org-ts-regexp-inactive
  511. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  512. "Regular expression for fast inactive time stamp matching.")
  513. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  514. "Regular expression for fast time stamp matching.")
  515. (defconst org-ts-regexp0
  516. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  517. "Regular expression matching time strings for analysis.
  518. This one does not require the space after the date, so it can be used
  519. on a string that terminates immediately after the date.")
  520. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  521. "Regular expression matching time strings for analysis.")
  522. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  523. "Regular expression matching time stamps, with groups.")
  524. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  525. "Regular expression matching time stamps (also [..]), with groups.")
  526. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  527. "Regular expression matching a time stamp range.")
  528. (defconst org-tr-regexp-both
  529. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  530. "Regular expression matching a time stamp range.")
  531. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  532. org-ts-regexp "\\)?")
  533. "Regular expression matching a time stamp or time stamp range.")
  534. (defconst org-tsr-regexp-both
  535. (concat org-ts-regexp-both "\\(--?-?"
  536. org-ts-regexp-both "\\)?")
  537. "Regular expression matching a time stamp or time stamp range.
  538. The time stamps may be either active or inactive.")
  539. (defconst org-repeat-re
  540. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  541. "Regular expression for specifying repeated events.
  542. After a match, group 1 contains the repeat expression.")
  543. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  544. "Formats for `format-time-string' which are used for time stamps.")
  545. ;;; The custom variables
  546. (defgroup org nil
  547. "Outline-based notes management and organizer."
  548. :tag "Org"
  549. :group 'outlines
  550. :group 'calendar)
  551. (defcustom org-mode-hook nil
  552. "Mode hook for Org mode, run after the mode was turned on."
  553. :group 'org
  554. :type 'hook)
  555. (defcustom org-load-hook nil
  556. "Hook that is run after org.el has been loaded."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-log-buffer-setup-hook nil
  560. "Hook that is run after an Org log buffer is created."
  561. :group 'org
  562. :version "24.1"
  563. :type 'hook)
  564. (defvar org-modules) ; defined below
  565. (defvar org-modules-loaded nil
  566. "Have the modules been loaded already?")
  567. (defun org-load-modules-maybe (&optional force)
  568. "Load all extensions listed in `org-modules'."
  569. (when (or force (not org-modules-loaded))
  570. (dolist (ext org-modules)
  571. (condition-case nil (require ext)
  572. (error (message "Problems while trying to load feature `%s'" ext))))
  573. (setq org-modules-loaded t)))
  574. (defun org-set-modules (var value)
  575. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  576. (set var value)
  577. (when (featurep 'org)
  578. (org-load-modules-maybe 'force)
  579. (org-element-cache-reset 'all)))
  580. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  581. "Modules that should always be loaded together with org.el.
  582. If a description starts with <C>, the file is not part of Emacs
  583. and loading it will require that you have downloaded and properly
  584. installed the Org mode distribution.
  585. You can also use this system to load external packages (i.e. neither Org
  586. core modules, nor modules from the CONTRIB directory). Just add symbols
  587. to the end of the list. If the package is called org-xyz.el, then you need
  588. to add the symbol `xyz', and the package must have a call to:
  589. (provide \\='org-xyz)
  590. For export specific modules, see also `org-export-backends'."
  591. :group 'org
  592. :set 'org-set-modules
  593. :version "24.4"
  594. :package-version '(Org . "8.0")
  595. :type
  596. '(set :greedy t
  597. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  598. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  599. (const :tag " crypt: Encryption of subtrees" org-crypt)
  600. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  601. (const :tag " docview: Links to doc-view buffers" org-docview)
  602. (const :tag " eww: Store link to url of eww" org-eww)
  603. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  604. (const :tag " habit: Track your consistency with habits" org-habit)
  605. (const :tag " id: Global IDs for identifying entries" org-id)
  606. (const :tag " info: Links to Info nodes" org-info)
  607. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  608. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  609. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  610. (const :tag " mouse: Additional mouse support" org-mouse)
  611. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  612. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  613. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  614. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  615. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  616. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  617. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  618. (const :tag "C collector: Collect properties into tables" org-collector)
  619. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  620. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  621. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  622. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  623. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  624. (const :tag "C eval: Include command output as text" org-eval)
  625. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  626. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  627. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  628. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  629. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  630. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  631. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  632. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  633. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  634. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  635. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  636. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  637. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  638. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  639. (const :tag "C registry: A registry for Org links" org-registry)
  640. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  641. (const :tag "C secretary: Team management with org-mode" org-secretary)
  642. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  643. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  644. (const :tag "C track: Keep up with Org mode development" org-track)
  645. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  646. (const :tag "C vm: Links to VM folders/messages" org-vm)
  647. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  648. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  649. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  650. (defvar org-export-registered-backends) ; From ox.el.
  651. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  652. (declare-function org-export-backend-name "ox" (backend) t)
  653. (defcustom org-export-backends '(ascii html icalendar latex odt)
  654. "List of export back-ends that should be always available.
  655. If a description starts with <C>, the file is not part of Emacs
  656. and loading it will require that you have downloaded and properly
  657. installed the Org mode distribution.
  658. Unlike to `org-modules', libraries in this list will not be
  659. loaded along with Org, but only once the export framework is
  660. needed.
  661. This variable needs to be set before org.el is loaded. If you
  662. need to make a change while Emacs is running, use the customize
  663. interface or run the following code, where VAL stands for the new
  664. value of the variable, after updating it:
  665. (progn
  666. (setq org-export-registered-backends
  667. (cl-remove-if-not
  668. (lambda (backend)
  669. (let ((name (org-export-backend-name backend)))
  670. (or (memq name val)
  671. (catch \\='parentp
  672. (dolist (b val)
  673. (and (org-export-derived-backend-p b name)
  674. (throw \\='parentp t)))))))
  675. org-export-registered-backends))
  676. (let ((new-list (mapcar #\\='org-export-backend-name
  677. org-export-registered-backends)))
  678. (dolist (backend val)
  679. (cond
  680. ((not (load (format \"ox-%s\" backend) t t))
  681. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  682. backend))
  683. ((not (memq backend new-list)) (push backend new-list))))
  684. (set-default \\='org-export-backends new-list)))
  685. Adding a back-end to this list will also pull the back-end it
  686. depends on, if any."
  687. :group 'org
  688. :group 'org-export
  689. :version "26.1"
  690. :package-version '(Org . "9.0")
  691. :initialize 'custom-initialize-set
  692. :set (lambda (var val)
  693. (if (not (featurep 'ox)) (set-default var val)
  694. ;; Any back-end not required anymore (not present in VAL and not
  695. ;; a parent of any back-end in the new value) is removed from the
  696. ;; list of registered back-ends.
  697. (setq org-export-registered-backends
  698. (cl-remove-if-not
  699. (lambda (backend)
  700. (let ((name (org-export-backend-name backend)))
  701. (or (memq name val)
  702. (catch 'parentp
  703. (dolist (b val)
  704. (and (org-export-derived-backend-p b name)
  705. (throw 'parentp t)))))))
  706. org-export-registered-backends))
  707. ;; Now build NEW-LIST of both new back-ends and required
  708. ;; parents.
  709. (let ((new-list (mapcar #'org-export-backend-name
  710. org-export-registered-backends)))
  711. (dolist (backend val)
  712. (cond
  713. ((not (load (format "ox-%s" backend) t t))
  714. (message "Problems while trying to load export back-end `%s'"
  715. backend))
  716. ((not (memq backend new-list)) (push backend new-list))))
  717. ;; Set VAR to that list with fixed dependencies.
  718. (set-default var new-list))))
  719. :type '(set :greedy t
  720. (const :tag " ascii Export buffer to ASCII format" ascii)
  721. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  722. (const :tag " html Export buffer to HTML format" html)
  723. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  724. (const :tag " latex Export buffer to LaTeX format" latex)
  725. (const :tag " man Export buffer to MAN format" man)
  726. (const :tag " md Export buffer to Markdown format" md)
  727. (const :tag " odt Export buffer to ODT format" odt)
  728. (const :tag " org Export buffer to Org format" org)
  729. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  730. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  731. (const :tag "C deck Export buffer to deck.js presentations" deck)
  732. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  733. (const :tag "C groff Export buffer to Groff format" groff)
  734. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  735. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  736. (const :tag "C s5 Export buffer to s5 presentations" s5)
  737. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  738. (eval-after-load 'ox
  739. '(dolist (backend org-export-backends)
  740. (condition-case nil (require (intern (format "ox-%s" backend)))
  741. (error (message "Problems while trying to load export back-end `%s'"
  742. backend)))))
  743. (defcustom org-support-shift-select nil
  744. "Non-nil means make shift-cursor commands select text when possible.
  745. \\<org-mode-map>\
  746. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  747. start selecting a region, or enlarge regions started in this way.
  748. In Org mode, in special contexts, these same keys are used for
  749. other purposes, important enough to compete with shift selection.
  750. Org tries to balance these needs by supporting `shift-select-mode'
  751. outside these special contexts, under control of this variable.
  752. The default of this variable is nil, to avoid confusing behavior. Shifted
  753. cursor keys will then execute Org commands in the following contexts:
  754. - on a headline, changing TODO state (left/right) and priority (up/down)
  755. - on a time stamp, changing the time
  756. - in a plain list item, changing the bullet type
  757. - in a property definition line, switching between allowed values
  758. - in the BEGIN line of a clock table (changing the time block).
  759. Outside these contexts, the commands will throw an error.
  760. When this variable is t and the cursor is not in a special
  761. context, Org mode will support shift-selection for making and
  762. enlarging regions. To make this more effective, the bullet
  763. cycling will no longer happen anywhere in an item line, but only
  764. if the cursor is exactly on the bullet.
  765. If you set this variable to the symbol `always', then the keys
  766. will not be special in headlines, property lines, and item lines,
  767. to make shift selection work there as well. If this is what you
  768. want, you can use the following alternative commands:
  769. `\\[org-todo]' and `\\[org-priority]' \
  770. to change TODO state and priority,
  771. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  772. can be used to switch TODO sets,
  773. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  774. and properties can be edited by hand or in column view.
  775. However, when the cursor is on a timestamp, shift-cursor commands
  776. will still edit the time stamp - this is just too good to give up."
  777. :group 'org
  778. :type '(choice
  779. (const :tag "Never" nil)
  780. (const :tag "When outside special context" t)
  781. (const :tag "Everywhere except timestamps" always)))
  782. (defcustom org-loop-over-headlines-in-active-region nil
  783. "Shall some commands act upon headlines in the active region?
  784. When set to t, some commands will be performed in all headlines
  785. within the active region.
  786. When set to `start-level', some commands will be performed in all
  787. headlines within the active region, provided that these headlines
  788. are of the same level than the first one.
  789. When set to a string, those commands will be performed on the
  790. matching headlines within the active region. Such string must be
  791. a tags/property/todo match as it is used in the agenda tags view.
  792. The list of commands is: `org-schedule', `org-deadline',
  793. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  794. `org-archive-to-archive-sibling'. The archiving commands skip
  795. already archived entries."
  796. :type '(choice (const :tag "Don't loop" nil)
  797. (const :tag "All headlines in active region" t)
  798. (const :tag "In active region, headlines at the same level than the first one" start-level)
  799. (string :tag "Tags/Property/Todo matcher"))
  800. :version "24.1"
  801. :group 'org-todo
  802. :group 'org-archive)
  803. (defgroup org-startup nil
  804. "Options concerning startup of Org mode."
  805. :tag "Org Startup"
  806. :group 'org)
  807. (defcustom org-startup-folded t
  808. "Non-nil means entering Org mode will switch to OVERVIEW.
  809. This can also be configured on a per-file basis by adding one of
  810. the following lines anywhere in the buffer:
  811. #+STARTUP: fold (or `overview', this is equivalent)
  812. #+STARTUP: nofold (or `showall', this is equivalent)
  813. #+STARTUP: content
  814. #+STARTUP: showeverything
  815. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  816. to ignore this option when Org opens agenda files for the first
  817. time."
  818. :group 'org-startup
  819. :type '(choice
  820. (const :tag "nofold: show all" nil)
  821. (const :tag "fold: overview" t)
  822. (const :tag "content: all headlines" content)
  823. (const :tag "show everything, even drawers" showeverything)))
  824. (defcustom org-startup-truncated t
  825. "Non-nil means entering Org mode will set `truncate-lines'.
  826. This is useful since some lines containing links can be very long and
  827. uninteresting. Also tables look terrible when wrapped.
  828. The variable `org-startup-truncated' allows to configure
  829. truncation for Org mode different to the other modes that use the
  830. variable `truncate-lines' and as a shortcut instead of putting
  831. the variable `truncate-lines' into the `org-mode-hook'. If one
  832. wants to configure truncation for Org mode not statically but
  833. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  834. the variable `truncate-lines' has to be used because in such a
  835. case it is too late to set the variable `org-startup-truncated'."
  836. :group 'org-startup
  837. :type 'boolean)
  838. (defcustom org-startup-indented nil
  839. "Non-nil means turn on `org-indent-mode' on startup.
  840. This can also be configured on a per-file basis by adding one of
  841. the following lines anywhere in the buffer:
  842. #+STARTUP: indent
  843. #+STARTUP: noindent"
  844. :group 'org-structure
  845. :type '(choice
  846. (const :tag "Not" nil)
  847. (const :tag "Globally (slow on startup in large files)" t)))
  848. (defcustom org-use-sub-superscripts t
  849. "Non-nil means interpret \"_\" and \"^\" for display.
  850. If you want to control how Org exports those characters, see
  851. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  852. used to be an alias for `org-export-with-sub-superscripts' in
  853. Org <8.0, it is not anymore.
  854. When this option is turned on, you can use TeX-like syntax for
  855. sub- and superscripts within the buffer. Several characters after
  856. \"_\" or \"^\" will be considered as a single item - so grouping
  857. with {} is normally not needed. For example, the following things
  858. will be parsed as single sub- or superscripts:
  859. 10^24 or 10^tau several digits will be considered 1 item.
  860. 10^-12 or 10^-tau a leading sign with digits or a word
  861. x^2-y^3 will be read as x^2 - y^3, because items are
  862. terminated by almost any nonword/nondigit char.
  863. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  864. Still, ambiguity is possible. So when in doubt, use {} to enclose
  865. the sub/superscript. If you set this variable to the symbol `{}',
  866. the braces are *required* in order to trigger interpretations as
  867. sub/superscript. This can be helpful in documents that need \"_\"
  868. frequently in plain text."
  869. :group 'org-startup
  870. :version "24.4"
  871. :package-version '(Org . "8.0")
  872. :type '(choice
  873. (const :tag "Always interpret" t)
  874. (const :tag "Only with braces" {})
  875. (const :tag "Never interpret" nil)))
  876. (defcustom org-startup-with-beamer-mode nil
  877. "Non-nil means turn on `org-beamer-mode' on startup.
  878. This can also be configured on a per-file basis by adding one of
  879. the following lines anywhere in the buffer:
  880. #+STARTUP: beamer"
  881. :group 'org-startup
  882. :version "24.1"
  883. :type 'boolean)
  884. (defcustom org-startup-align-all-tables nil
  885. "Non-nil means align all tables when visiting a file.
  886. This is useful when the column width in tables is forced with <N> cookies
  887. in table fields. Such tables will look correct only after the first re-align.
  888. This can also be configured on a per-file basis by adding one of
  889. the following lines anywhere in the buffer:
  890. #+STARTUP: align
  891. #+STARTUP: noalign"
  892. :group 'org-startup
  893. :type 'boolean)
  894. (defcustom org-startup-with-inline-images nil
  895. "Non-nil means show inline images when loading a new Org file.
  896. This can also be configured on a per-file basis by adding one of
  897. the following lines anywhere in the buffer:
  898. #+STARTUP: inlineimages
  899. #+STARTUP: noinlineimages"
  900. :group 'org-startup
  901. :version "24.1"
  902. :type 'boolean)
  903. (defcustom org-startup-with-latex-preview nil
  904. "Non-nil means preview LaTeX fragments when loading a new Org file.
  905. This can also be configured on a per-file basis by adding one of
  906. the following lines anywhere in the buffer:
  907. #+STARTUP: latexpreview
  908. #+STARTUP: nolatexpreview"
  909. :group 'org-startup
  910. :version "24.4"
  911. :package-version '(Org . "8.0")
  912. :type 'boolean)
  913. (defcustom org-insert-mode-line-in-empty-file nil
  914. "Non-nil means insert the first line setting Org mode in empty files.
  915. When the function `org-mode' is called interactively in an empty file, this
  916. normally means that the file name does not automatically trigger Org mode.
  917. To ensure that the file will always be in Org mode in the future, a
  918. line enforcing Org mode will be inserted into the buffer, if this option
  919. has been set."
  920. :group 'org-startup
  921. :type 'boolean)
  922. (defcustom org-replace-disputed-keys nil
  923. "Non-nil means use alternative key bindings for some keys.
  924. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  925. These keys are also used by other packages like shift-selection-mode'
  926. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  927. If you want to use Org mode together with one of these other modes,
  928. or more generally if you would like to move some Org mode commands to
  929. other keys, set this variable and configure the keys with the variable
  930. `org-disputed-keys'.
  931. This option is only relevant at load-time of Org mode, and must be set
  932. *before* org.el is loaded. Changing it requires a restart of Emacs to
  933. become effective."
  934. :group 'org-startup
  935. :type 'boolean)
  936. (defcustom org-use-extra-keys nil
  937. "Non-nil means use extra key sequence definitions for certain commands.
  938. This happens automatically if `window-system' is nil. This
  939. variable lets you do the same manually. You must set it before
  940. loading Org."
  941. :group 'org-startup
  942. :type 'boolean)
  943. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  944. (defcustom org-disputed-keys
  945. '(([(shift up)] . [(meta p)])
  946. ([(shift down)] . [(meta n)])
  947. ([(shift left)] . [(meta -)])
  948. ([(shift right)] . [(meta +)])
  949. ([(control shift right)] . [(meta shift +)])
  950. ([(control shift left)] . [(meta shift -)]))
  951. "Keys for which Org mode and other modes compete.
  952. This is an alist, cars are the default keys, second element specifies
  953. the alternative to use when `org-replace-disputed-keys' is t.
  954. Keys can be specified in any syntax supported by `define-key'.
  955. The value of this option takes effect only at Org mode startup,
  956. therefore you'll have to restart Emacs to apply it after changing."
  957. :group 'org-startup
  958. :type 'alist)
  959. (defun org-key (key)
  960. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  961. Or return the original if not disputed."
  962. (when org-replace-disputed-keys
  963. (let* ((nkey (key-description key))
  964. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  965. org-disputed-keys)))
  966. (setq key (if x (cdr x) key))))
  967. key)
  968. (defun org-defkey (keymap key def)
  969. "Define a key, possibly translated, as returned by `org-key'."
  970. (define-key keymap (org-key key) def))
  971. (defcustom org-ellipsis nil
  972. "The ellipsis to use in the Org mode outline.
  973. When nil, just use the standard three dots.
  974. When a string, use that string instead.
  975. The change affects only Org mode (which will then use its own display table).
  976. Changing this requires executing `\\[org-mode]' in a buffer to become
  977. effective."
  978. :group 'org-startup
  979. :type '(choice (const :tag "Default" nil)
  980. (string :tag "String" :value "...#"))
  981. :safe #'string-or-null-p)
  982. (defvar org-display-table nil
  983. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  984. (defgroup org-keywords nil
  985. "Keywords in Org mode."
  986. :tag "Org Keywords"
  987. :group 'org)
  988. (defcustom org-closed-keep-when-no-todo nil
  989. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  990. :group 'org-todo
  991. :group 'org-keywords
  992. :version "24.4"
  993. :package-version '(Org . "8.0")
  994. :type 'boolean)
  995. (defgroup org-structure nil
  996. "Options concerning the general structure of Org files."
  997. :tag "Org Structure"
  998. :group 'org)
  999. (defgroup org-reveal-location nil
  1000. "Options about how to make context of a location visible."
  1001. :tag "Org Reveal Location"
  1002. :group 'org-structure)
  1003. (defcustom org-show-context-detail '((agenda . local)
  1004. (bookmark-jump . lineage)
  1005. (isearch . lineage)
  1006. (default . ancestors))
  1007. "Alist between context and visibility span when revealing a location.
  1008. \\<org-mode-map>Some actions may move point into invisible
  1009. locations. As a consequence, Org always expose a neighborhood
  1010. around point. How much is shown depends on the initial action,
  1011. or context. Valid contexts are
  1012. agenda when exposing an entry from the agenda
  1013. org-goto when using the command `org-goto' (`\\[org-goto]')
  1014. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1015. tags-tree when constructing a sparse tree based on tags matches
  1016. link-search when exposing search matches associated with a link
  1017. mark-goto when exposing the jump goal of a mark
  1018. bookmark-jump when exposing a bookmark location
  1019. isearch when exiting from an incremental search
  1020. default default for all contexts not set explicitly
  1021. Allowed visibility spans are
  1022. minimal show current headline; if point is not on headline,
  1023. also show entry
  1024. local show current headline, entry and next headline
  1025. ancestors show current headline and its direct ancestors; if
  1026. point is not on headline, also show entry
  1027. lineage show current headline, its direct ancestors and all
  1028. their children; if point is not on headline, also show
  1029. entry and first child
  1030. tree show current headline, its direct ancestors and all
  1031. their children; if point is not on headline, also show
  1032. entry and all children
  1033. canonical show current headline, its direct ancestors along with
  1034. their entries and children; if point is not located on
  1035. the headline, also show current entry and all children
  1036. As special cases, a nil or t value means show all contexts in
  1037. `minimal' or `canonical' view, respectively.
  1038. Some views can make displayed information very compact, but also
  1039. make it harder to edit the location of the match. In such
  1040. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1041. more context."
  1042. :group 'org-reveal-location
  1043. :version "26.1"
  1044. :package-version '(Org . "9.0")
  1045. :type '(choice
  1046. (const :tag "Canonical" t)
  1047. (const :tag "Minimal" nil)
  1048. (repeat :greedy t :tag "Individual contexts"
  1049. (cons
  1050. (choice :tag "Context"
  1051. (const agenda)
  1052. (const org-goto)
  1053. (const occur-tree)
  1054. (const tags-tree)
  1055. (const link-search)
  1056. (const mark-goto)
  1057. (const bookmark-jump)
  1058. (const isearch)
  1059. (const default))
  1060. (choice :tag "Detail level"
  1061. (const minimal)
  1062. (const local)
  1063. (const ancestors)
  1064. (const lineage)
  1065. (const tree)
  1066. (const canonical))))))
  1067. (defcustom org-indirect-buffer-display 'other-window
  1068. "How should indirect tree buffers be displayed?
  1069. This applies to indirect buffers created with the commands
  1070. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1071. Valid values are:
  1072. current-window Display in the current window
  1073. other-window Just display in another window.
  1074. dedicated-frame Create one new frame, and re-use it each time.
  1075. new-frame Make a new frame each time. Note that in this case
  1076. previously-made indirect buffers are kept, and you need to
  1077. kill these buffers yourself."
  1078. :group 'org-structure
  1079. :group 'org-agenda-windows
  1080. :type '(choice
  1081. (const :tag "In current window" current-window)
  1082. (const :tag "In current frame, other window" other-window)
  1083. (const :tag "Each time a new frame" new-frame)
  1084. (const :tag "One dedicated frame" dedicated-frame)))
  1085. (defcustom org-use-speed-commands nil
  1086. "Non-nil means activate single letter commands at beginning of a headline.
  1087. This may also be a function to test for appropriate locations where speed
  1088. commands should be active.
  1089. For example, to activate speed commands when the point is on any
  1090. star at the beginning of the headline, you can do this:
  1091. (setq org-use-speed-commands
  1092. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1093. :group 'org-structure
  1094. :type '(choice
  1095. (const :tag "Never" nil)
  1096. (const :tag "At beginning of headline stars" t)
  1097. (function)))
  1098. (defcustom org-speed-commands-user nil
  1099. "Alist of additional speed commands.
  1100. This list will be checked before `org-speed-commands-default'
  1101. when the variable `org-use-speed-commands' is non-nil
  1102. and when the cursor is at the beginning of a headline.
  1103. The car if each entry is a string with a single letter, which must
  1104. be assigned to `self-insert-command' in the global map.
  1105. The cdr is either a command to be called interactively, a function
  1106. to be called, or a form to be evaluated.
  1107. An entry that is just a list with a single string will be interpreted
  1108. as a descriptive headline that will be added when listing the speed
  1109. commands in the Help buffer using the `?' speed command."
  1110. :group 'org-structure
  1111. :type '(repeat :value ("k" . ignore)
  1112. (choice :value ("k" . ignore)
  1113. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1114. (cons :tag "Letter and Command"
  1115. (string :tag "Command letter")
  1116. (choice
  1117. (function)
  1118. (sexp))))))
  1119. (defcustom org-bookmark-names-plist
  1120. '(:last-capture "org-capture-last-stored"
  1121. :last-refile "org-refile-last-stored"
  1122. :last-capture-marker "org-capture-last-stored-marker")
  1123. "Names for bookmarks automatically set by some Org commands.
  1124. This can provide strings as names for a number of bookmarks Org sets
  1125. automatically. The following keys are currently implemented:
  1126. :last-capture
  1127. :last-capture-marker
  1128. :last-refile
  1129. When a key does not show up in the property list, the corresponding bookmark
  1130. is not set."
  1131. :group 'org-structure
  1132. :type 'plist)
  1133. (defgroup org-cycle nil
  1134. "Options concerning visibility cycling in Org mode."
  1135. :tag "Org Cycle"
  1136. :group 'org-structure)
  1137. (defcustom org-cycle-skip-children-state-if-no-children t
  1138. "Non-nil means skip CHILDREN state in entries that don't have any."
  1139. :group 'org-cycle
  1140. :type 'boolean)
  1141. (defcustom org-cycle-max-level nil
  1142. "Maximum level which should still be subject to visibility cycling.
  1143. Levels higher than this will, for cycling, be treated as text, not a headline.
  1144. When `org-odd-levels-only' is set, a value of N in this variable actually
  1145. means 2N-1 stars as the limiting headline.
  1146. When nil, cycle all levels.
  1147. Note that the limiting level of cycling is also influenced by
  1148. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1149. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1150. than its value."
  1151. :group 'org-cycle
  1152. :type '(choice
  1153. (const :tag "No limit" nil)
  1154. (integer :tag "Maximum level")))
  1155. (defcustom org-hide-block-startup nil
  1156. "Non-nil means entering Org mode will fold all blocks.
  1157. This can also be set in on a per-file basis with
  1158. #+STARTUP: hideblocks
  1159. #+STARTUP: showblocks"
  1160. :group 'org-startup
  1161. :group 'org-cycle
  1162. :type 'boolean)
  1163. (defcustom org-cycle-global-at-bob nil
  1164. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1165. This makes it possible to do global cycling without having to use `S-TAB'
  1166. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1167. line of the buffer
  1168. must not be a headline -- it may be empty or some other text.
  1169. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1170. sure the cursor stays at the beginning of the buffer.
  1171. When this option is nil, don't do anything special at the beginning of
  1172. the buffer."
  1173. :group 'org-cycle
  1174. :type 'boolean)
  1175. (defcustom org-cycle-level-after-item/entry-creation t
  1176. "Non-nil means cycle entry level or item indentation in new empty entries.
  1177. When the cursor is at the end of an empty headline, i.e., with only stars
  1178. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1179. and then all possible ancestor states, before returning to the original state.
  1180. This makes data entry extremely fast: M-RET to create a new headline,
  1181. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1182. When the cursor is at the end of an empty plain list item, one TAB will
  1183. make it a subitem, two or more tabs will back up to make this an item
  1184. higher up in the item hierarchy."
  1185. :group 'org-cycle
  1186. :type 'boolean)
  1187. (defcustom org-cycle-emulate-tab t
  1188. "Where should `org-cycle' emulate TAB.
  1189. nil Never
  1190. white Only in completely white lines
  1191. whitestart Only at the beginning of lines, before the first non-white char
  1192. t Everywhere except in headlines
  1193. exc-hl-bol Everywhere except at the start of a headline
  1194. If TAB is used in a place where it does not emulate TAB, the current subtree
  1195. visibility is cycled."
  1196. :group 'org-cycle
  1197. :type '(choice (const :tag "Never" nil)
  1198. (const :tag "Only in completely white lines" white)
  1199. (const :tag "Before first char in a line" whitestart)
  1200. (const :tag "Everywhere except in headlines" t)
  1201. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1202. (defcustom org-cycle-separator-lines 2
  1203. "Number of empty lines needed to keep an empty line between collapsed trees.
  1204. If you leave an empty line between the end of a subtree and the following
  1205. headline, this empty line is hidden when the subtree is folded.
  1206. Org mode will leave (exactly) one empty line visible if the number of
  1207. empty lines is equal or larger to the number given in this variable.
  1208. So the default 2 means at least 2 empty lines after the end of a subtree
  1209. are needed to produce free space between a collapsed subtree and the
  1210. following headline.
  1211. If the number is negative, and the number of empty lines is at least -N,
  1212. all empty lines are shown.
  1213. Special case: when 0, never leave empty lines in collapsed view."
  1214. :group 'org-cycle
  1215. :type 'integer)
  1216. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1217. (defcustom org-pre-cycle-hook nil
  1218. "Hook that is run before visibility cycling is happening.
  1219. The function(s) in this hook must accept a single argument which indicates
  1220. the new state that will be set right after running this hook. The
  1221. argument is a symbol. Before a global state change, it can have the values
  1222. `overview', `content', or `all'. Before a local state change, it can have
  1223. the values `folded', `children', or `subtree'."
  1224. :group 'org-cycle
  1225. :type 'hook)
  1226. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1227. org-cycle-hide-drawers
  1228. org-cycle-show-empty-lines
  1229. org-optimize-window-after-visibility-change)
  1230. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1231. The function(s) in this hook must accept a single argument which indicates
  1232. the new state that was set by the most recent `org-cycle' command. The
  1233. argument is a symbol. After a global state change, it can have the values
  1234. `overview', `contents', or `all'. After a local state change, it can have
  1235. the values `folded', `children', or `subtree'."
  1236. :group 'org-cycle
  1237. :type 'hook
  1238. :version "26.1"
  1239. :package-version '(Org . "8.3"))
  1240. (defgroup org-edit-structure nil
  1241. "Options concerning structure editing in Org mode."
  1242. :tag "Org Edit Structure"
  1243. :group 'org-structure)
  1244. (defcustom org-odd-levels-only nil
  1245. "Non-nil means skip even levels and only use odd levels for the outline.
  1246. This has the effect that two stars are being added/taken away in
  1247. promotion/demotion commands. It also influences how levels are
  1248. handled by the exporters.
  1249. Changing it requires restart of `font-lock-mode' to become effective
  1250. for fontification also in regions already fontified.
  1251. You may also set this on a per-file basis by adding one of the following
  1252. lines to the buffer:
  1253. #+STARTUP: odd
  1254. #+STARTUP: oddeven"
  1255. :group 'org-edit-structure
  1256. :group 'org-appearance
  1257. :type 'boolean)
  1258. (defcustom org-adapt-indentation t
  1259. "Non-nil means adapt indentation to outline node level.
  1260. When this variable is set, Org assumes that you write outlines by
  1261. indenting text in each node to align with the headline (after the
  1262. stars). The following issues are influenced by this variable:
  1263. - The indentation is increased by one space in a demotion
  1264. command, and decreased by one in a promotion command. However,
  1265. in the latter case, if shifting some line in the entry body
  1266. would alter document structure (e.g., insert a new headline),
  1267. indentation is not changed at all.
  1268. - Property drawers and planning information is inserted indented
  1269. when this variable is set. When nil, they will not be indented.
  1270. - TAB indents a line relative to current level. The lines below
  1271. a headline will be indented when this variable is set.
  1272. Note that this is all about true indentation, by adding and
  1273. removing space characters. See also `org-indent.el' which does
  1274. level-dependent indentation in a virtual way, i.e. at display
  1275. time in Emacs."
  1276. :group 'org-edit-structure
  1277. :type 'boolean)
  1278. (defcustom org-special-ctrl-a/e nil
  1279. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1280. When t, `C-a' will bring back the cursor to the beginning of the
  1281. headline text, i.e. after the stars and after a possible TODO
  1282. keyword. In an item, this will be the position after bullet and
  1283. check-box, if any. When the cursor is already at that position,
  1284. another `C-a' will bring it to the beginning of the line.
  1285. `C-e' will jump to the end of the headline, ignoring the presence
  1286. of tags in the headline. A second `C-e' will then jump to the
  1287. true end of the line, after any tags. This also means that, when
  1288. this variable is non-nil, `C-e' also will never jump beyond the
  1289. end of the heading of a folded section, i.e. not after the
  1290. ellipses.
  1291. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1292. normally, going to the true line boundary first. Only a directly
  1293. following, identical keypress will bring the cursor to the
  1294. special positions.
  1295. This may also be a cons cell where the behavior for `C-a' and
  1296. `C-e' is set separately."
  1297. :group 'org-edit-structure
  1298. :type '(choice
  1299. (const :tag "off" nil)
  1300. (const :tag "on: after stars/bullet and before tags first" t)
  1301. (const :tag "reversed: true line boundary first" reversed)
  1302. (cons :tag "Set C-a and C-e separately"
  1303. (choice :tag "Special C-a"
  1304. (const :tag "off" nil)
  1305. (const :tag "on: after stars/bullet first" t)
  1306. (const :tag "reversed: before stars/bullet first" reversed))
  1307. (choice :tag "Special C-e"
  1308. (const :tag "off" nil)
  1309. (const :tag "on: before tags first" t)
  1310. (const :tag "reversed: after tags first" reversed)))))
  1311. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1312. (defcustom org-special-ctrl-k nil
  1313. "Non-nil means `C-k' will behave specially in headlines.
  1314. When nil, `C-k' will call the default `kill-line' command.
  1315. When t, the following will happen while the cursor is in the headline:
  1316. - When the cursor is at the beginning of a headline, kill the entire
  1317. line and possible the folded subtree below the line.
  1318. - When in the middle of the headline text, kill the headline up to the tags.
  1319. - When after the headline text, kill the tags."
  1320. :group 'org-edit-structure
  1321. :type 'boolean)
  1322. (defcustom org-ctrl-k-protect-subtree nil
  1323. "Non-nil means, do not delete a hidden subtree with C-k.
  1324. When set to the symbol `error', simply throw an error when C-k is
  1325. used to kill (part-of) a headline that has hidden text behind it.
  1326. Any other non-nil value will result in a query to the user, if it is
  1327. OK to kill that hidden subtree. When nil, kill without remorse."
  1328. :group 'org-edit-structure
  1329. :version "24.1"
  1330. :type '(choice
  1331. (const :tag "Do not protect hidden subtrees" nil)
  1332. (const :tag "Protect hidden subtrees with a security query" t)
  1333. (const :tag "Never kill a hidden subtree with C-k" error)))
  1334. (defcustom org-special-ctrl-o t
  1335. "Non-nil means, make `C-o' insert a row in tables."
  1336. :group 'org-edit-structure
  1337. :type 'boolean)
  1338. (defcustom org-catch-invisible-edits nil
  1339. "Check if in invisible region before inserting or deleting a character.
  1340. Valid values are:
  1341. nil Do not check, so just do invisible edits.
  1342. error Throw an error and do nothing.
  1343. show Make point visible, and do the requested edit.
  1344. show-and-error Make point visible, then throw an error and abort the edit.
  1345. smart Make point visible, and do insertion/deletion if it is
  1346. adjacent to visible text and the change feels predictable.
  1347. Never delete a previously invisible character or add in the
  1348. middle or right after an invisible region. Basically, this
  1349. allows insertion and backward-delete right before ellipses.
  1350. FIXME: maybe in this case we should not even show?"
  1351. :group 'org-edit-structure
  1352. :version "24.1"
  1353. :type '(choice
  1354. (const :tag "Do not check" nil)
  1355. (const :tag "Throw error when trying to edit" error)
  1356. (const :tag "Unhide, but do not do the edit" show-and-error)
  1357. (const :tag "Show invisible part and do the edit" show)
  1358. (const :tag "Be smart and do the right thing" smart)))
  1359. (defcustom org-yank-folded-subtrees t
  1360. "Non-nil means when yanking subtrees, fold them.
  1361. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1362. it starts with a heading and all other headings in it are either children
  1363. or siblings, then fold all the subtrees. However, do this only if no
  1364. text after the yank would be swallowed into a folded tree by this action."
  1365. :group 'org-edit-structure
  1366. :type 'boolean)
  1367. (defcustom org-yank-adjusted-subtrees nil
  1368. "Non-nil means when yanking subtrees, adjust the level.
  1369. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1370. this function for details."
  1371. :group 'org-edit-structure
  1372. :type 'boolean)
  1373. (defcustom org-M-RET-may-split-line '((default . t))
  1374. "Non-nil means M-RET will split the line at the cursor position.
  1375. When nil, it will go to the end of the line before making a
  1376. new line.
  1377. You may also set this option in a different way for different
  1378. contexts. Valid contexts are:
  1379. headline when creating a new headline
  1380. item when creating a new item
  1381. table in a table field
  1382. default the value to be used for all contexts not explicitly
  1383. customized"
  1384. :group 'org-structure
  1385. :group 'org-table
  1386. :type '(choice
  1387. (const :tag "Always" t)
  1388. (const :tag "Never" nil)
  1389. (repeat :greedy t :tag "Individual contexts"
  1390. (cons
  1391. (choice :tag "Context"
  1392. (const headline)
  1393. (const item)
  1394. (const table)
  1395. (const default))
  1396. (boolean)))))
  1397. (defcustom org-insert-heading-respect-content nil
  1398. "Non-nil means insert new headings after the current subtree.
  1399. \\<org-mode-map>
  1400. When nil, the new heading is created directly after the current line.
  1401. The commands `\\[org-insert-heading-respect-content]' and \
  1402. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1403. for the duration of the command."
  1404. :group 'org-structure
  1405. :type 'boolean)
  1406. (defcustom org-blank-before-new-entry '((heading . auto)
  1407. (plain-list-item . auto))
  1408. "Should `org-insert-heading' leave a blank line before new heading/item?
  1409. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1410. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1411. which case Org will look at the surrounding headings/items and try to
  1412. make an intelligent decision whether to insert a blank line or not."
  1413. :group 'org-edit-structure
  1414. :type '(list
  1415. (cons (const heading)
  1416. (choice (const :tag "Never" nil)
  1417. (const :tag "Always" t)
  1418. (const :tag "Auto" auto)))
  1419. (cons (const plain-list-item)
  1420. (choice (const :tag "Never" nil)
  1421. (const :tag "Always" t)
  1422. (const :tag "Auto" auto)))))
  1423. (defcustom org-insert-heading-hook nil
  1424. "Hook being run after inserting a new heading."
  1425. :group 'org-edit-structure
  1426. :type 'hook)
  1427. (defcustom org-enable-fixed-width-editor t
  1428. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1429. This currently only means they are never auto-wrapped.
  1430. When nil, such lines will be treated like ordinary lines."
  1431. :group 'org-edit-structure
  1432. :type 'boolean)
  1433. (defcustom org-goto-auto-isearch t
  1434. "Non-nil means typing characters in `org-goto' starts incremental search.
  1435. When nil, you can use these keybindings to navigate the buffer:
  1436. q Quit the org-goto interface
  1437. n Go to the next visible heading
  1438. p Go to the previous visible heading
  1439. f Go one heading forward on same level
  1440. b Go one heading backward on same level
  1441. u Go one heading up"
  1442. :group 'org-edit-structure
  1443. :type 'boolean)
  1444. (defgroup org-sparse-trees nil
  1445. "Options concerning sparse trees in Org mode."
  1446. :tag "Org Sparse Trees"
  1447. :group 'org-structure)
  1448. (defcustom org-highlight-sparse-tree-matches t
  1449. "Non-nil means highlight all matches that define a sparse tree.
  1450. The highlights will automatically disappear the next time the buffer is
  1451. changed by an edit command."
  1452. :group 'org-sparse-trees
  1453. :type 'boolean)
  1454. (defcustom org-remove-highlights-with-change t
  1455. "Non-nil means any change to the buffer will remove temporary highlights.
  1456. \\<org-mode-map>\
  1457. Such highlights are created by `org-occur' and `org-clock-display'.
  1458. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1459. to get rid of the highlights.
  1460. The highlights created by `org-toggle-latex-fragment' always need
  1461. `\\[org-toggle-latex-fragment]' to be removed."
  1462. :group 'org-sparse-trees
  1463. :group 'org-time
  1464. :type 'boolean)
  1465. (defcustom org-occur-case-fold-search t
  1466. "Non-nil means `org-occur' should be case-insensitive.
  1467. If set to `smart' the search will be case-insensitive only if it
  1468. doesn't specify any upper case character."
  1469. :group 'org-sparse-trees
  1470. :version "26.1"
  1471. :type '(choice
  1472. (const :tag "Case-sensitive" nil)
  1473. (const :tag "Case-insensitive" t)
  1474. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1475. (defcustom org-occur-hook '(org-first-headline-recenter)
  1476. "Hook that is run after `org-occur' has constructed a sparse tree.
  1477. This can be used to recenter the window to show as much of the structure
  1478. as possible."
  1479. :group 'org-sparse-trees
  1480. :type 'hook)
  1481. (defgroup org-imenu-and-speedbar nil
  1482. "Options concerning imenu and speedbar in Org mode."
  1483. :tag "Org Imenu and Speedbar"
  1484. :group 'org-structure)
  1485. (defcustom org-imenu-depth 2
  1486. "The maximum level for Imenu access to Org headlines.
  1487. This also applied for speedbar access."
  1488. :group 'org-imenu-and-speedbar
  1489. :type 'integer)
  1490. (defgroup org-table nil
  1491. "Options concerning tables in Org mode."
  1492. :tag "Org Table"
  1493. :group 'org)
  1494. (defcustom org-enable-table-editor 'optimized
  1495. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1496. When nil, such lines will be treated like ordinary lines.
  1497. When equal to the symbol `optimized', the table editor will be optimized to
  1498. do the following:
  1499. - Automatic overwrite mode in front of whitespace in table fields.
  1500. This makes the structure of the table stay in tact as long as the edited
  1501. field does not exceed the column width.
  1502. - Minimize the number of realigns. Normally, the table is aligned each time
  1503. TAB or RET are pressed to move to another field. With optimization this
  1504. happens only if changes to a field might have changed the column width.
  1505. Optimization requires replacing the functions `self-insert-command',
  1506. `delete-char', and `backward-delete-char' in Org buffers, with a
  1507. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1508. good at guessing when a re-align will be necessary, but you can always
  1509. force one with `\\[org-ctrl-c-ctrl-c]'.
  1510. If you would like to use the optimized version in Org mode, but the
  1511. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1512. This variable can be used to turn on and off the table editor during a session,
  1513. but in order to toggle optimization, a restart is required.
  1514. See also the variable `org-table-auto-blank-field'."
  1515. :group 'org-table
  1516. :type '(choice
  1517. (const :tag "off" nil)
  1518. (const :tag "on" t)
  1519. (const :tag "on, optimized" optimized)))
  1520. (defcustom org-self-insert-cluster-for-undo nil
  1521. "Non-nil means cluster self-insert commands for undo when possible.
  1522. If this is set, then, like in the Emacs command loop, 20 consecutive
  1523. characters will be undone together.
  1524. This is configurable, because there is some impact on typing performance."
  1525. :group 'org-table
  1526. :type 'boolean)
  1527. (defcustom org-table-tab-recognizes-table.el t
  1528. "Non-nil means TAB will automatically notice a table.el table.
  1529. When it sees such a table, it moves point into it and - if necessary -
  1530. calls `table-recognize-table'."
  1531. :group 'org-table-editing
  1532. :type 'boolean)
  1533. (defgroup org-link nil
  1534. "Options concerning links in Org mode."
  1535. :tag "Org Link"
  1536. :group 'org)
  1537. (defvar-local org-link-abbrev-alist-local nil
  1538. "Buffer-local version of `org-link-abbrev-alist', which see.
  1539. The value of this is taken from the #+LINK lines.")
  1540. (defcustom org-link-parameters
  1541. '(("doi" :follow org--open-doi-link)
  1542. ("elisp" :follow org--open-elisp-link)
  1543. ("file" :complete org-file-complete-link)
  1544. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1545. ("help" :follow org--open-help-link)
  1546. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1547. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1548. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1549. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1550. ("shell" :follow org--open-shell-link))
  1551. "An alist of properties that defines all the links in Org mode.
  1552. The key in each association is a string of the link type.
  1553. Subsequent optional elements make up a p-list of link properties.
  1554. :follow - A function that takes the link path as an argument.
  1555. :export - A function that takes the link path, description and
  1556. export-backend as arguments.
  1557. :store - A function responsible for storing the link. See the
  1558. function `org-store-link-functions'.
  1559. :complete - A function that inserts a link with completion. The
  1560. function takes one optional prefix arg.
  1561. :face - A face for the link, or a function that returns a face.
  1562. The function takes one argument which is the link path. The
  1563. default face is `org-link'.
  1564. :mouse-face - The mouse-face. The default is `highlight'.
  1565. :display - `full' will not fold the link in descriptive
  1566. display. Default is `org-link'.
  1567. :help-echo - A string or function that takes (window object position)
  1568. as arguments and returns a string.
  1569. :keymap - A keymap that is active on the link. The default is
  1570. `org-mouse-map'.
  1571. :htmlize-link - A function for the htmlize-link. Defaults
  1572. to (list :uri \"type:path\")
  1573. :activate-func - A function to run at the end of font-lock
  1574. activation. The function must accept (link-start link-end path bracketp)
  1575. as arguments."
  1576. :group 'org-link
  1577. :type '(alist :tag "Link display parameters"
  1578. :value-type plist)
  1579. :version "26.1"
  1580. :package-version '(Org . "9.1"))
  1581. (defun org-link-get-parameter (type key)
  1582. "Get TYPE link property for KEY.
  1583. TYPE is a string and KEY is a plist keyword."
  1584. (plist-get
  1585. (cdr (assoc type org-link-parameters))
  1586. key))
  1587. (defun org-link-set-parameters (type &rest parameters)
  1588. "Set link TYPE properties to PARAMETERS.
  1589. PARAMETERS should be :key val pairs."
  1590. (let ((data (assoc type org-link-parameters)))
  1591. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1592. (push (cons type parameters) org-link-parameters)
  1593. (org-make-link-regexps)
  1594. (org-element-update-syntax))))
  1595. (defun org-link-types ()
  1596. "Return a list of known link types."
  1597. (mapcar #'car org-link-parameters))
  1598. (defcustom org-link-abbrev-alist nil
  1599. "Alist of link abbreviations.
  1600. The car of each element is a string, to be replaced at the start of a link.
  1601. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1602. links in Org buffers can have an optional tag after a double colon, e.g.,
  1603. [[linkkey:tag][description]]
  1604. The `linkkey' must be a single word, starting with a letter, followed
  1605. by letters, numbers, `-' or `_'.
  1606. If REPLACE is a string, the tag will simply be appended to create the link.
  1607. If the string contains \"%s\", the tag will be inserted there. If the string
  1608. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1609. at that point (see the function `url-hexify-string'). If the string contains
  1610. the specifier \"%(my-function)\", then the custom function `my-function' will
  1611. be invoked: this function takes the tag as its only argument and must return
  1612. a string.
  1613. REPLACE may also be a function that will be called with the tag as the
  1614. only argument to create the link, which should be returned as a string.
  1615. See the manual for examples."
  1616. :group 'org-link
  1617. :type '(repeat
  1618. (cons
  1619. (string :tag "Protocol")
  1620. (choice
  1621. (string :tag "Format")
  1622. (function)))))
  1623. (defcustom org-descriptive-links t
  1624. "Non-nil means Org will display descriptive links.
  1625. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1626. \"Org Website\", hiding the link itself and just displaying its
  1627. description. When set to nil, Org will display the full links
  1628. literally.
  1629. You can interactively set the value of this variable by calling
  1630. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1631. :group 'org-link
  1632. :type 'boolean)
  1633. (defcustom org-link-file-path-type 'adaptive
  1634. "How the path name in file links should be stored.
  1635. Valid values are:
  1636. relative Relative to the current directory, i.e. the directory of the file
  1637. into which the link is being inserted.
  1638. absolute Absolute path, if possible with ~ for home directory.
  1639. noabbrev Absolute path, no abbreviation of home directory.
  1640. adaptive Use relative path for files in the current directory and sub-
  1641. directories of it. For other files, use an absolute path."
  1642. :group 'org-link
  1643. :type '(choice
  1644. (const relative)
  1645. (const absolute)
  1646. (const noabbrev)
  1647. (const adaptive)))
  1648. (defvaralias 'org-activate-links 'org-highlight-links)
  1649. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1650. "Types of links that should be highlighted in Org files.
  1651. This is a list of symbols, each one of them leading to the
  1652. highlighting of a certain link type.
  1653. You can still open links that are not highlighted.
  1654. In principle, it does not hurt to turn on highlighting for all
  1655. link types. There may be a small gain when turning off unused
  1656. link types. The types are:
  1657. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1658. angle Links in angular brackets that may contain whitespace like
  1659. <bbdb:Carsten Dominik>.
  1660. plain Plain links in normal text, no whitespace, like http://google.com.
  1661. radio Text that is matched by a radio target, see manual for details.
  1662. tag Tag settings in a headline (link to tag search).
  1663. date Time stamps (link to calendar).
  1664. footnote Footnote labels.
  1665. If you set this variable during an Emacs session, use `org-mode-restart'
  1666. in the Org buffer so that the change takes effect."
  1667. :group 'org-link
  1668. :group 'org-appearance
  1669. :type '(set :greedy t
  1670. (const :tag "Double bracket links" bracket)
  1671. (const :tag "Angular bracket links" angle)
  1672. (const :tag "Plain text links" plain)
  1673. (const :tag "Radio target matches" radio)
  1674. (const :tag "Tags" tag)
  1675. (const :tag "Timestamps" date)
  1676. (const :tag "Footnotes" footnote)))
  1677. (defcustom org-make-link-description-function nil
  1678. "Function to use for generating link descriptions from links.
  1679. When nil, the link location will be used. This function must take
  1680. two parameters: the first one is the link, the second one is the
  1681. description generated by `org-insert-link'. The function should
  1682. return the description to use."
  1683. :group 'org-link
  1684. :type '(choice (const nil) (function)))
  1685. (defgroup org-link-store nil
  1686. "Options concerning storing links in Org mode."
  1687. :tag "Org Store Link"
  1688. :group 'org-link)
  1689. (defcustom org-url-hexify-p t
  1690. "When non-nil, hexify URL when creating a link."
  1691. :type 'boolean
  1692. :version "24.3"
  1693. :group 'org-link-store)
  1694. (defcustom org-email-link-description-format "Email %c: %.30s"
  1695. "Format of the description part of a link to an email or usenet message.
  1696. The following %-escapes will be replaced by corresponding information:
  1697. %F full \"From\" field
  1698. %f name, taken from \"From\" field, address if no name
  1699. %T full \"To\" field
  1700. %t first name in \"To\" field, address if no name
  1701. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1702. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1703. %s subject
  1704. %d date
  1705. %m message-id.
  1706. You may use normal field width specification between the % and the letter.
  1707. This is for example useful to limit the length of the subject.
  1708. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1709. :group 'org-link-store
  1710. :type 'string)
  1711. (defcustom org-from-is-user-regexp
  1712. (let (r1 r2)
  1713. (when (and user-mail-address (not (string= user-mail-address "")))
  1714. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1715. (when (and user-full-name (not (string= user-full-name "")))
  1716. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1717. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1718. "Regexp matched against the \"From:\" header of an email or usenet message.
  1719. It should match if the message is from the user him/herself."
  1720. :group 'org-link-store
  1721. :type 'regexp)
  1722. (defcustom org-context-in-file-links t
  1723. "Non-nil means file links from `org-store-link' contain context.
  1724. \\<org-mode-map>
  1725. A search string will be added to the file name with :: as separator
  1726. and used to find the context when the link is activated by the command
  1727. `org-open-at-point'. When this option is t, the entire active region
  1728. will be placed in the search string of the file link. If set to a
  1729. positive integer, only the first n lines of context will be stored.
  1730. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1731. \\[org-store-link]')
  1732. negates this setting for the duration of the command."
  1733. :group 'org-link-store
  1734. :type '(choice boolean integer))
  1735. (defcustom org-keep-stored-link-after-insertion nil
  1736. "Non-nil means keep link in list for entire session.
  1737. \\<org-mode-map>
  1738. The command `org-store-link' adds a link pointing to the current
  1739. location to an internal list. These links accumulate during a session.
  1740. The command `org-insert-link' can be used to insert links into any
  1741. Org file (offering completion for all stored links).
  1742. When this option is nil, every link which has been inserted once using
  1743. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1744. unused
  1745. links more efficient."
  1746. :group 'org-link-store
  1747. :type 'boolean)
  1748. (defgroup org-link-follow nil
  1749. "Options concerning following links in Org mode."
  1750. :tag "Org Follow Link"
  1751. :group 'org-link)
  1752. (defcustom org-link-translation-function nil
  1753. "Function to translate links with different syntax to Org syntax.
  1754. This can be used to translate links created for example by the Planner
  1755. or emacs-wiki packages to Org syntax.
  1756. The function must accept two parameters, a TYPE containing the link
  1757. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1758. which is everything after the link protocol. It should return a cons
  1759. with possibly modified values of type and path.
  1760. Org contains a function for this, so if you set this variable to
  1761. `org-translate-link-from-planner', you should be able follow many
  1762. links created by planner."
  1763. :group 'org-link-follow
  1764. :type '(choice (const nil) (function)))
  1765. (defcustom org-follow-link-hook nil
  1766. "Hook that is run after a link has been followed."
  1767. :group 'org-link-follow
  1768. :type 'hook)
  1769. (defcustom org-tab-follows-link nil
  1770. "Non-nil means on links TAB will follow the link.
  1771. Needs to be set before org.el is loaded.
  1772. This really should not be used, it does not make sense, and the
  1773. implementation is bad."
  1774. :group 'org-link-follow
  1775. :type 'boolean)
  1776. (defcustom org-return-follows-link nil
  1777. "Non-nil means on links RET will follow the link.
  1778. In tables, the special behavior of RET has precedence."
  1779. :group 'org-link-follow
  1780. :type 'boolean)
  1781. (defcustom org-mouse-1-follows-link
  1782. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1783. "Non-nil means mouse-1 on a link will follow the link.
  1784. A longer mouse click will still set point. Needs to be set
  1785. before org.el is loaded."
  1786. :group 'org-link-follow
  1787. :version "24.4"
  1788. :package-version '(Org . "8.3")
  1789. :type '(choice
  1790. (const :tag "A double click follows the link" double)
  1791. (const :tag "Unconditionally follow the link with mouse-1" t)
  1792. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1793. (defcustom org-mark-ring-length 4
  1794. "Number of different positions to be recorded in the ring.
  1795. Changing this requires a restart of Emacs to work correctly."
  1796. :group 'org-link-follow
  1797. :type 'integer)
  1798. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1799. "Non-nil means internal fuzzy links can only match headlines.
  1800. When nil, the a fuzzy link may point to a target or a named
  1801. construct in the document. When set to the special value
  1802. `query-to-create', offer to create a new headline when none
  1803. matched.
  1804. Spaces and statistics cookies are ignored during heading searches."
  1805. :group 'org-link-follow
  1806. :version "24.1"
  1807. :type '(choice
  1808. (const :tag "Use fuzzy text search" nil)
  1809. (const :tag "Match only exact headline" t)
  1810. (const :tag "Match exact headline or query to create it"
  1811. query-to-create))
  1812. :safe #'symbolp)
  1813. (defcustom org-link-frame-setup
  1814. '((vm . vm-visit-folder-other-frame)
  1815. (vm-imap . vm-visit-imap-folder-other-frame)
  1816. (gnus . org-gnus-no-new-news)
  1817. (file . find-file-other-window)
  1818. (wl . wl-other-frame))
  1819. "Setup the frame configuration for following links.
  1820. When following a link with Emacs, it may often be useful to display
  1821. this link in another window or frame. This variable can be used to
  1822. set this up for the different types of links.
  1823. For VM, use any of
  1824. `vm-visit-folder'
  1825. `vm-visit-folder-other-window'
  1826. `vm-visit-folder-other-frame'
  1827. For Gnus, use any of
  1828. `gnus'
  1829. `gnus-other-frame'
  1830. `org-gnus-no-new-news'
  1831. For FILE, use any of
  1832. `find-file'
  1833. `find-file-other-window'
  1834. `find-file-other-frame'
  1835. For Wanderlust use any of
  1836. `wl'
  1837. `wl-other-frame'
  1838. For the calendar, use the variable `calendar-setup'.
  1839. For BBDB, it is currently only possible to display the matches in
  1840. another window."
  1841. :group 'org-link-follow
  1842. :type '(list
  1843. (cons (const vm)
  1844. (choice
  1845. (const vm-visit-folder)
  1846. (const vm-visit-folder-other-window)
  1847. (const vm-visit-folder-other-frame)))
  1848. (cons (const vm-imap)
  1849. (choice
  1850. (const vm-visit-imap-folder)
  1851. (const vm-visit-imap-folder-other-window)
  1852. (const vm-visit-imap-folder-other-frame)))
  1853. (cons (const gnus)
  1854. (choice
  1855. (const gnus)
  1856. (const gnus-other-frame)
  1857. (const org-gnus-no-new-news)))
  1858. (cons (const file)
  1859. (choice
  1860. (const find-file)
  1861. (const find-file-other-window)
  1862. (const find-file-other-frame)))
  1863. (cons (const wl)
  1864. (choice
  1865. (const wl)
  1866. (const wl-other-frame)))))
  1867. (defcustom org-display-internal-link-with-indirect-buffer nil
  1868. "Non-nil means use indirect buffer to display infile links.
  1869. Activating internal links (from one location in a file to another location
  1870. in the same file) normally just jumps to the location. When the link is
  1871. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1872. is displayed in
  1873. another window. When this option is set, the other window actually displays
  1874. an indirect buffer clone of the current buffer, to avoid any visibility
  1875. changes to the current buffer."
  1876. :group 'org-link-follow
  1877. :type 'boolean)
  1878. (defcustom org-open-non-existing-files nil
  1879. "Non-nil means `org-open-file' will open non-existing files.
  1880. When nil, an error will be generated.
  1881. This variable applies only to external applications because they
  1882. might choke on non-existing files. If the link is to a file that
  1883. will be opened in Emacs, the variable is ignored."
  1884. :group 'org-link-follow
  1885. :type 'boolean)
  1886. (defcustom org-open-directory-means-index-dot-org nil
  1887. "Non-nil means a link to a directory really means to index.org.
  1888. When nil, following a directory link will run dired or open a finder/explorer
  1889. window on that directory."
  1890. :group 'org-link-follow
  1891. :type 'boolean)
  1892. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1893. "Non-nil means ask for confirmation before executing shell links.
  1894. Shell links can be dangerous: just think about a link
  1895. [[shell:rm -rf ~/*][Google Search]]
  1896. This link would show up in your Org document as \"Google Search\",
  1897. but really it would remove your entire home directory.
  1898. Therefore we advise against setting this variable to nil.
  1899. Just change it to `y-or-n-p' if you want to confirm with a
  1900. single keystroke rather than having to type \"yes\"."
  1901. :group 'org-link-follow
  1902. :type '(choice
  1903. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1904. (const :tag "with y-or-n (faster)" y-or-n-p)
  1905. (const :tag "no confirmation (dangerous)" nil)))
  1906. (put 'org-confirm-shell-link-function
  1907. 'safe-local-variable
  1908. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1909. (defcustom org-confirm-shell-link-not-regexp ""
  1910. "A regexp to skip confirmation for shell links."
  1911. :group 'org-link-follow
  1912. :version "24.1"
  1913. :type 'regexp)
  1914. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1915. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1916. Elisp links can be dangerous: just think about a link
  1917. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1918. This link would show up in your Org document as \"Google Search\",
  1919. but really it would remove your entire home directory.
  1920. Therefore we advise against setting this variable to nil.
  1921. Just change it to `y-or-n-p' if you want to confirm with a
  1922. single keystroke rather than having to type \"yes\"."
  1923. :group 'org-link-follow
  1924. :type '(choice
  1925. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1926. (const :tag "with y-or-n (faster)" y-or-n-p)
  1927. (const :tag "no confirmation (dangerous)" nil)))
  1928. (put 'org-confirm-shell-link-function
  1929. 'safe-local-variable
  1930. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1931. (defcustom org-confirm-elisp-link-not-regexp ""
  1932. "A regexp to skip confirmation for Elisp links."
  1933. :group 'org-link-follow
  1934. :version "24.1"
  1935. :type 'regexp)
  1936. (defconst org-file-apps-defaults-gnu
  1937. '((remote . emacs)
  1938. (system . mailcap)
  1939. (t . mailcap))
  1940. "Default file applications on a UNIX or GNU/Linux system.
  1941. See `org-file-apps'.")
  1942. (defconst org-file-apps-defaults-macosx
  1943. '((remote . emacs)
  1944. (system . "open %s")
  1945. ("ps.gz" . "gv %s")
  1946. ("eps.gz" . "gv %s")
  1947. ("dvi" . "xdvi %s")
  1948. ("fig" . "xfig %s")
  1949. (t . "open %s"))
  1950. "Default file applications on a macOS system.
  1951. The system \"open\" is known as a default, but we use X11 applications
  1952. for some files for which the OS does not have a good default.
  1953. See `org-file-apps'.")
  1954. (defconst org-file-apps-defaults-windowsnt
  1955. (list '(remote . emacs)
  1956. (cons 'system (lambda (file _path)
  1957. (with-no-warnings (w32-shell-execute "open" file))))
  1958. (cons t (lambda (file _path)
  1959. (with-no-warnings (w32-shell-execute "open" file)))))
  1960. "Default file applications on a Windows NT system.
  1961. The system \"open\" is used for most files.
  1962. See `org-file-apps'.")
  1963. (defcustom org-file-apps
  1964. '((auto-mode . emacs)
  1965. ("\\.mm\\'" . default)
  1966. ("\\.x?html?\\'" . default)
  1967. ("\\.pdf\\'" . default))
  1968. "External applications for opening `file:path' items in a document.
  1969. \\<org-mode-map>\
  1970. Org mode uses system defaults for different file types, but
  1971. you can use this variable to set the application for a given file
  1972. extension. The entries in this list are cons cells where the car identifies
  1973. files and the cdr the corresponding command.
  1974. Possible values for the file identifier are:
  1975. \"string\" A string as a file identifier can be interpreted in different
  1976. ways, depending on its contents:
  1977. - Alphanumeric characters only:
  1978. Match links with this file extension.
  1979. Example: (\"pdf\" . \"evince %s\")
  1980. to open PDFs with evince.
  1981. - Regular expression: Match links where the
  1982. filename matches the regexp. If you want to
  1983. use groups here, use shy groups.
  1984. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1985. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1986. to open *.html and *.xhtml with firefox.
  1987. - Regular expression which contains (non-shy) groups:
  1988. Match links where the whole link, including \"::\", and
  1989. anything after that, matches the regexp.
  1990. In a custom command string, %1, %2, etc. are replaced with
  1991. the parts of the link that were matched by the groups.
  1992. For backwards compatibility, if a command string is given
  1993. that does not use any of the group matches, this case is
  1994. handled identically to the second one (i.e. match against
  1995. file name only).
  1996. In a custom function, you can access the group matches with
  1997. (match-string n link).
  1998. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1999. \"evince -p %1 %s\")
  2000. to open [[file:document.pdf::5]] with evince at page 5.
  2001. `directory' Matches a directory
  2002. `remote' Matches a remote file, accessible through tramp or efs.
  2003. Remote files most likely should be visited through Emacs
  2004. because external applications cannot handle such paths.
  2005. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2006. so all files Emacs knows how to handle. Using this with
  2007. command `emacs' will open most files in Emacs. Beware that this
  2008. will also open html files inside Emacs, unless you add
  2009. (\"html\" . default) to the list as well.
  2010. `system' The system command to open files, like `open' on Windows
  2011. and macOS, and mailcap under GNU/Linux. This is the command
  2012. that will be selected if you call `org-open-at-point' with a
  2013. double prefix argument (`\\[universal-argument] \
  2014. \\[universal-argument] \\[org-open-at-point]').
  2015. t Default for files not matched by any of the other options.
  2016. Possible values for the command are:
  2017. `emacs' The file will be visited by the current Emacs process.
  2018. `default' Use the default application for this file type, which is the
  2019. association for t in the list, most likely in the system-specific
  2020. part. This can be used to overrule an unwanted setting in the
  2021. system-specific variable.
  2022. `system' Use the system command for opening files, like \"open\".
  2023. This command is specified by the entry whose car is `system'.
  2024. Most likely, the system-specific version of this variable
  2025. does define this command, but you can overrule/replace it
  2026. here.
  2027. `mailcap' Use command specified in the mailcaps.
  2028. string A command to be executed by a shell; %s will be replaced
  2029. by the path to the file.
  2030. function A Lisp function, which will be called with two arguments:
  2031. the file path and the original link string, without the
  2032. \"file:\" prefix.
  2033. For more examples, see the system specific constants
  2034. `org-file-apps-defaults-macosx'
  2035. `org-file-apps-defaults-windowsnt'
  2036. `org-file-apps-defaults-gnu'."
  2037. :group 'org-link-follow
  2038. :type '(repeat
  2039. (cons (choice :value ""
  2040. (string :tag "Extension")
  2041. (const :tag "System command to open files" system)
  2042. (const :tag "Default for unrecognized files" t)
  2043. (const :tag "Remote file" remote)
  2044. (const :tag "Links to a directory" directory)
  2045. (const :tag "Any files that have Emacs modes"
  2046. auto-mode))
  2047. (choice :value ""
  2048. (const :tag "Visit with Emacs" emacs)
  2049. (const :tag "Use default" default)
  2050. (const :tag "Use the system command" system)
  2051. (string :tag "Command")
  2052. (function :tag "Function")))))
  2053. (defcustom org-doi-server-url "http://dx.doi.org/"
  2054. "The URL of the DOI server."
  2055. :type 'string
  2056. :version "24.3"
  2057. :group 'org-link-follow)
  2058. (defgroup org-refile nil
  2059. "Options concerning refiling entries in Org mode."
  2060. :tag "Org Refile"
  2061. :group 'org)
  2062. (defcustom org-directory "~/org"
  2063. "Directory with Org files.
  2064. This is just a default location to look for Org files. There is no need
  2065. at all to put your files into this directory. It is used in the
  2066. following situations:
  2067. 1. When a capture template specifies a target file that is not an
  2068. absolute path. The path will then be interpreted relative to
  2069. `org-directory'
  2070. 2. When the value of variable `org-agenda-files' is a single file, any
  2071. relative paths in this file will be taken as relative to
  2072. `org-directory'."
  2073. :group 'org-refile
  2074. :group 'org-capture
  2075. :type 'directory)
  2076. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2077. "Default target for storing notes.
  2078. Used as a fall back file for org-capture.el, for templates that
  2079. do not specify a target file."
  2080. :group 'org-refile
  2081. :group 'org-capture
  2082. :type 'file)
  2083. (defcustom org-goto-interface 'outline
  2084. "The default interface to be used for `org-goto'.
  2085. Allowed values are:
  2086. outline The interface shows an outline of the relevant file
  2087. and the correct heading is found by moving through
  2088. the outline or by searching with incremental search.
  2089. outline-path-completion Headlines in the current buffer are offered via
  2090. completion. This is the interface also used by
  2091. the refile command."
  2092. :group 'org-refile
  2093. :type '(choice
  2094. (const :tag "Outline" outline)
  2095. (const :tag "Outline-path-completion" outline-path-completion)))
  2096. (defcustom org-goto-max-level 5
  2097. "Maximum target level when running `org-goto' with refile interface."
  2098. :group 'org-refile
  2099. :type 'integer)
  2100. (defcustom org-reverse-note-order nil
  2101. "Non-nil means store new notes at the beginning of a file or entry.
  2102. When nil, new notes will be filed to the end of a file or entry.
  2103. This can also be a list with cons cells of regular expressions that
  2104. are matched against file names, and values."
  2105. :group 'org-capture
  2106. :group 'org-refile
  2107. :type '(choice
  2108. (const :tag "Reverse always" t)
  2109. (const :tag "Reverse never" nil)
  2110. (repeat :tag "By file name regexp"
  2111. (cons regexp boolean))))
  2112. (defcustom org-log-refile nil
  2113. "Information to record when a task is refiled.
  2114. Possible values are:
  2115. nil Don't add anything
  2116. time Add a time stamp to the task
  2117. note Prompt for a note and add it with template `org-log-note-headings'
  2118. This option can also be set with on a per-file-basis with
  2119. #+STARTUP: nologrefile
  2120. #+STARTUP: logrefile
  2121. #+STARTUP: lognoterefile
  2122. You can have local logging settings for a subtree by setting the LOGGING
  2123. property to one or more of these keywords.
  2124. When bulk-refiling from the agenda, the value `note' is forbidden and
  2125. will temporarily be changed to `time'."
  2126. :group 'org-refile
  2127. :group 'org-progress
  2128. :version "24.1"
  2129. :type '(choice
  2130. (const :tag "No logging" nil)
  2131. (const :tag "Record timestamp" time)
  2132. (const :tag "Record timestamp with note." note)))
  2133. (defcustom org-refile-targets nil
  2134. "Targets for refiling entries with `\\[org-refile]'.
  2135. This is a list of cons cells. Each cell contains:
  2136. - a specification of the files to be considered, either a list of files,
  2137. or a symbol whose function or variable value will be used to retrieve
  2138. a file name or a list of file names. If you use `org-agenda-files' for
  2139. that, all agenda files will be scanned for targets. Nil means consider
  2140. headings in the current buffer.
  2141. - A specification of how to find candidate refile targets. This may be
  2142. any of:
  2143. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2144. This tag has to be present in all target headlines, inheritance will
  2145. not be considered.
  2146. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2147. todo keyword.
  2148. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2149. headlines that are refiling targets.
  2150. - a cons cell (:level . N). Any headline of level N is considered a target.
  2151. Note that, when `org-odd-levels-only' is set, level corresponds to
  2152. order in hierarchy, not to the number of stars.
  2153. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2154. Note that, when `org-odd-levels-only' is set, level corresponds to
  2155. order in hierarchy, not to the number of stars.
  2156. Each element of this list generates a set of possible targets.
  2157. The union of these sets is presented (with completion) to
  2158. the user by `org-refile'.
  2159. You can set the variable `org-refile-target-verify-function' to a function
  2160. to verify each headline found by the simple criteria above.
  2161. When this variable is nil, all top-level headlines in the current buffer
  2162. are used, equivalent to the value `((nil . (:level . 1))'."
  2163. :group 'org-refile
  2164. :type '(repeat
  2165. (cons
  2166. (choice :value org-agenda-files
  2167. (const :tag "All agenda files" org-agenda-files)
  2168. (const :tag "Current buffer" nil)
  2169. (function) (variable) (file))
  2170. (choice :tag "Identify target headline by"
  2171. (cons :tag "Specific tag" (const :value :tag) (string))
  2172. (cons :tag "TODO keyword" (const :value :todo) (string))
  2173. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2174. (cons :tag "Level number" (const :value :level) (integer))
  2175. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2176. (defcustom org-refile-target-verify-function nil
  2177. "Function to verify if the headline at point should be a refile target.
  2178. The function will be called without arguments, with point at the
  2179. beginning of the headline. It should return t and leave point
  2180. where it is if the headline is a valid target for refiling.
  2181. If the target should not be selected, the function must return nil.
  2182. In addition to this, it may move point to a place from where the search
  2183. should be continued. For example, the function may decide that the entire
  2184. subtree of the current entry should be excluded and move point to the end
  2185. of the subtree."
  2186. :group 'org-refile
  2187. :type '(choice
  2188. (const nil)
  2189. (function)))
  2190. (defcustom org-refile-use-cache nil
  2191. "Non-nil means cache refile targets to speed up the process.
  2192. \\<org-mode-map>\
  2193. The cache for a particular file will be updated automatically when
  2194. the buffer has been killed, or when any of the marker used for flagging
  2195. refile targets no longer points at a live buffer.
  2196. If you have added new entries to a buffer that might themselves be targets,
  2197. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2198. if you find that easier, \
  2199. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2200. \\[org-refile]'."
  2201. :group 'org-refile
  2202. :version "24.1"
  2203. :type 'boolean)
  2204. (defcustom org-refile-use-outline-path nil
  2205. "Non-nil means provide refile targets as paths.
  2206. So a level 3 headline will be available as level1/level2/level3.
  2207. When the value is `file', also include the file name (without directory)
  2208. into the path. In this case, you can also stop the completion after
  2209. the file name, to get entries inserted as top level in the file.
  2210. When `full-file-path', include the full file path.
  2211. When `buffer-name', use the buffer name."
  2212. :group 'org-refile
  2213. :type '(choice
  2214. (const :tag "Not" nil)
  2215. (const :tag "Yes" t)
  2216. (const :tag "Start with file name" file)
  2217. (const :tag "Start with full file path" full-file-path)
  2218. (const :tag "Start with buffer name" buffer-name)))
  2219. (defcustom org-outline-path-complete-in-steps t
  2220. "Non-nil means complete the outline path in hierarchical steps.
  2221. When Org uses the refile interface to select an outline path (see
  2222. `org-refile-use-outline-path'), the completion of the path can be
  2223. done in a single go, or it can be done in steps down the headline
  2224. hierarchy. Going in steps is probably the best if you do not use
  2225. a special completion package like `ido' or `icicles'. However,
  2226. when using these packages, going in one step can be very fast,
  2227. while still showing the whole path to the entry."
  2228. :group 'org-refile
  2229. :type 'boolean)
  2230. (defcustom org-refile-allow-creating-parent-nodes nil
  2231. "Non-nil means allow the creation of new nodes as refile targets.
  2232. New nodes are then created by adding \"/new node name\" to the completion
  2233. of an existing node. When the value of this variable is `confirm',
  2234. new node creation must be confirmed by the user (recommended).
  2235. When nil, the completion must match an existing entry.
  2236. Note that, if the new heading is not seen by the criteria
  2237. listed in `org-refile-targets', multiple instances of the same
  2238. heading would be created by trying again to file under the new
  2239. heading."
  2240. :group 'org-refile
  2241. :type '(choice
  2242. (const :tag "Never" nil)
  2243. (const :tag "Always" t)
  2244. (const :tag "Prompt for confirmation" confirm)))
  2245. (defcustom org-refile-active-region-within-subtree nil
  2246. "Non-nil means also refile active region within a subtree.
  2247. By default `org-refile' doesn't allow refiling regions if they
  2248. don't contain a set of subtrees, but it might be convenient to
  2249. do so sometimes: in that case, the first line of the region is
  2250. converted to a headline before refiling."
  2251. :group 'org-refile
  2252. :version "24.1"
  2253. :type 'boolean)
  2254. (defgroup org-todo nil
  2255. "Options concerning TODO items in Org mode."
  2256. :tag "Org TODO"
  2257. :group 'org)
  2258. (defgroup org-progress nil
  2259. "Options concerning Progress logging in Org mode."
  2260. :tag "Org Progress"
  2261. :group 'org-time)
  2262. (defvar org-todo-interpretation-widgets
  2263. '((:tag "Sequence (cycling hits every state)" sequence)
  2264. (:tag "Type (cycling directly to DONE)" type))
  2265. "The available interpretation symbols for customizing `org-todo-keywords'.
  2266. Interested libraries should add to this list.")
  2267. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2268. "List of TODO entry keyword sequences and their interpretation.
  2269. \\<org-mode-map>This is a list of sequences.
  2270. Each sequence starts with a symbol, either `sequence' or `type',
  2271. indicating if the keywords should be interpreted as a sequence of
  2272. action steps, or as different types of TODO items. The first
  2273. keywords are states requiring action - these states will select a headline
  2274. for inclusion into the global TODO list Org produces. If one of the
  2275. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2276. signify that no further action is necessary. If \"|\" is not found,
  2277. the last keyword is treated as the only DONE state of the sequence.
  2278. The command `\\[org-todo]' cycles an entry through these states, and one
  2279. additional state where no keyword is present. For details about this
  2280. cycling, see the manual.
  2281. TODO keywords and interpretation can also be set on a per-file basis with
  2282. the special #+SEQ_TODO and #+TYP_TODO lines.
  2283. Each keyword can optionally specify a character for fast state selection
  2284. \(in combination with the variable `org-use-fast-todo-selection')
  2285. and specifiers for state change logging, using the same syntax that
  2286. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2287. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2288. indicates to record a time stamp each time this state is selected.
  2289. Each keyword may also specify if a timestamp or a note should be
  2290. recorded when entering or leaving the state, by adding additional
  2291. characters in the parenthesis after the keyword. This looks like this:
  2292. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2293. record only the time of the state change. With X and Y being either
  2294. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2295. Y when leaving the state if and only if the *target* state does not
  2296. define X. You may omit any of the fast-selection key or X or /Y,
  2297. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2298. For backward compatibility, this variable may also be just a list
  2299. of keywords. In this case the interpretation (sequence or type) will be
  2300. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2301. :group 'org-todo
  2302. :group 'org-keywords
  2303. :type '(choice
  2304. (repeat :tag "Old syntax, just keywords"
  2305. (string :tag "Keyword"))
  2306. (repeat :tag "New syntax"
  2307. (cons
  2308. (choice
  2309. :tag "Interpretation"
  2310. ;;Quick and dirty way to see
  2311. ;;`org-todo-interpretations'. This takes the
  2312. ;;place of item arguments
  2313. :convert-widget
  2314. (lambda (widget)
  2315. (widget-put widget
  2316. :args (mapcar
  2317. (lambda (x)
  2318. (widget-convert
  2319. (cons 'const x)))
  2320. org-todo-interpretation-widgets))
  2321. widget))
  2322. (repeat
  2323. (string :tag "Keyword"))))))
  2324. (defvar-local org-todo-keywords-1 nil
  2325. "All TODO and DONE keywords active in a buffer.")
  2326. (defvar org-todo-keywords-for-agenda nil)
  2327. (defvar org-done-keywords-for-agenda nil)
  2328. (defvar org-todo-keyword-alist-for-agenda nil)
  2329. (defvar org-tag-alist-for-agenda nil
  2330. "Alist of all tags from all agenda files.")
  2331. (defvar org-tag-groups-alist-for-agenda nil
  2332. "Alist of all groups tags from all current agenda files.")
  2333. (defvar-local org-tag-groups-alist nil)
  2334. (defvar org-agenda-contributing-files nil)
  2335. (defvar-local org-current-tag-alist nil
  2336. "Alist of all tag groups in current buffer.
  2337. This variable takes into consideration `org-tag-alist',
  2338. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2339. (defvar-local org-not-done-keywords nil)
  2340. (defvar-local org-done-keywords nil)
  2341. (defvar-local org-todo-heads nil)
  2342. (defvar-local org-todo-sets nil)
  2343. (defvar-local org-todo-log-states nil)
  2344. (defvar-local org-todo-kwd-alist nil)
  2345. (defvar-local org-todo-key-alist nil)
  2346. (defvar-local org-todo-key-trigger nil)
  2347. (defcustom org-todo-interpretation 'sequence
  2348. "Controls how TODO keywords are interpreted.
  2349. This variable is in principle obsolete and is only used for
  2350. backward compatibility, if the interpretation of todo keywords is
  2351. not given already in `org-todo-keywords'. See that variable for
  2352. more information."
  2353. :group 'org-todo
  2354. :group 'org-keywords
  2355. :type '(choice (const sequence)
  2356. (const type)))
  2357. (defcustom org-use-fast-todo-selection t
  2358. "\\<org-mode-map>\
  2359. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2360. This variable describes if and under what circumstances the cycling
  2361. mechanism for TODO keywords will be replaced by a single-key, direct
  2362. selection scheme.
  2363. When nil, fast selection is never used.
  2364. When the symbol `prefix', it will be used when `org-todo' is called
  2365. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2366. in an Org buffer, and
  2367. `\\[universal-argument] t' in an agenda buffer.
  2368. When t, fast selection is used by default. In this case, the prefix
  2369. argument forces cycling instead.
  2370. In all cases, the special interface is only used if access keys have
  2371. actually been assigned by the user, i.e. if keywords in the configuration
  2372. are followed by a letter in parenthesis, like TODO(t)."
  2373. :group 'org-todo
  2374. :type '(choice
  2375. (const :tag "Never" nil)
  2376. (const :tag "By default" t)
  2377. (const :tag "Only with C-u C-c C-t" prefix)))
  2378. (defcustom org-provide-todo-statistics t
  2379. "Non-nil means update todo statistics after insert and toggle.
  2380. ALL-HEADLINES means update todo statistics by including headlines
  2381. with no TODO keyword as well, counting them as not done.
  2382. A list of TODO keywords means the same, but skip keywords that are
  2383. not in this list.
  2384. When set to a list of two lists, the first list contains keywords
  2385. to consider as TODO keywords, the second list contains keywords
  2386. to consider as DONE keywords.
  2387. When this is set, todo statistics is updated in the parent of the
  2388. current entry each time a todo state is changed."
  2389. :group 'org-todo
  2390. :type '(choice
  2391. (const :tag "Yes, only for TODO entries" t)
  2392. (const :tag "Yes, including all entries" all-headlines)
  2393. (repeat :tag "Yes, for TODOs in this list"
  2394. (string :tag "TODO keyword"))
  2395. (list :tag "Yes, for TODOs and DONEs in these lists"
  2396. (repeat (string :tag "TODO keyword"))
  2397. (repeat (string :tag "DONE keyword")))
  2398. (other :tag "No TODO statistics" nil)))
  2399. (defcustom org-hierarchical-todo-statistics t
  2400. "Non-nil means TODO statistics covers just direct children.
  2401. When nil, all entries in the subtree are considered.
  2402. This has only an effect if `org-provide-todo-statistics' is set.
  2403. To set this to nil for only a single subtree, use a COOKIE_DATA
  2404. property and include the word \"recursive\" into the value."
  2405. :group 'org-todo
  2406. :type 'boolean)
  2407. (defcustom org-after-todo-state-change-hook nil
  2408. "Hook which is run after the state of a TODO item was changed.
  2409. The new state (a string with a TODO keyword, or nil) is available in the
  2410. Lisp variable `org-state'."
  2411. :group 'org-todo
  2412. :type 'hook)
  2413. (defvar org-blocker-hook nil
  2414. "Hook for functions that are allowed to block a state change.
  2415. Functions in this hook should not modify the buffer.
  2416. Each function gets as its single argument a property list,
  2417. see `org-trigger-hook' for more information about this list.
  2418. If any of the functions in this hook returns nil, the state change
  2419. is blocked.")
  2420. (defvar org-trigger-hook nil
  2421. "Hook for functions that are triggered by a state change.
  2422. Each function gets as its single argument a property list with at
  2423. least the following elements:
  2424. (:type type-of-change :position pos-at-entry-start
  2425. :from old-state :to new-state)
  2426. Depending on the type, more properties may be present.
  2427. This mechanism is currently implemented for:
  2428. TODO state changes
  2429. ------------------
  2430. :type todo-state-change
  2431. :from previous state (keyword as a string), or nil, or a symbol
  2432. `todo' or `done', to indicate the general type of state.
  2433. :to new state, like in :from")
  2434. (defcustom org-enforce-todo-dependencies nil
  2435. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2436. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2437. be blocked if any prior sibling is not yet done.
  2438. Finally, if the parent is blocked because of ordered siblings of its own,
  2439. the child will also be blocked."
  2440. :set (lambda (var val)
  2441. (set var val)
  2442. (if val
  2443. (add-hook 'org-blocker-hook
  2444. 'org-block-todo-from-children-or-siblings-or-parent)
  2445. (remove-hook 'org-blocker-hook
  2446. 'org-block-todo-from-children-or-siblings-or-parent)))
  2447. :group 'org-todo
  2448. :type 'boolean)
  2449. (defcustom org-enforce-todo-checkbox-dependencies nil
  2450. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2451. When this is nil, checkboxes have no influence on switching TODO states.
  2452. When non-nil, you first need to check off all check boxes before the TODO
  2453. entry can be switched to DONE.
  2454. This variable needs to be set before org.el is loaded, and you need to
  2455. restart Emacs after a change to make the change effective. The only way
  2456. to change is while Emacs is running is through the customize interface."
  2457. :set (lambda (var val)
  2458. (set var val)
  2459. (if val
  2460. (add-hook 'org-blocker-hook
  2461. 'org-block-todo-from-checkboxes)
  2462. (remove-hook 'org-blocker-hook
  2463. 'org-block-todo-from-checkboxes)))
  2464. :group 'org-todo
  2465. :type 'boolean)
  2466. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2467. "Non-nil means inserting a TODO heading is treated as state change.
  2468. So when the command `\\[org-insert-todo-heading]' is used, state change
  2469. logging will apply if appropriate. When nil, the new TODO item will
  2470. be inserted directly, and no logging will take place."
  2471. :group 'org-todo
  2472. :type 'boolean)
  2473. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2474. "Non-nil means switching TODO states with S-cursor counts as state change.
  2475. This is the default behavior. However, setting this to nil allows a
  2476. convenient way to select a TODO state and bypass any logging associated
  2477. with that."
  2478. :group 'org-todo
  2479. :type 'boolean)
  2480. (defcustom org-todo-state-tags-triggers nil
  2481. "Tag changes that should be triggered by TODO state changes.
  2482. This is a list. Each entry is
  2483. (state-change (tag . flag) .......)
  2484. State-change can be a string with a state, and empty string to indicate the
  2485. state that has no TODO keyword, or it can be one of the symbols `todo'
  2486. or `done', meaning any not-done or done state, respectively."
  2487. :group 'org-todo
  2488. :group 'org-tags
  2489. :type '(repeat
  2490. (cons (choice :tag "When changing to"
  2491. (const :tag "Not-done state" todo)
  2492. (const :tag "Done state" done)
  2493. (string :tag "State"))
  2494. (repeat
  2495. (cons :tag "Tag action"
  2496. (string :tag "Tag")
  2497. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2498. (defcustom org-log-done nil
  2499. "Information to record when a task moves to the DONE state.
  2500. Possible values are:
  2501. nil Don't add anything, just change the keyword
  2502. time Add a time stamp to the task
  2503. note Prompt for a note and add it with template `org-log-note-headings'
  2504. This option can also be set with on a per-file-basis with
  2505. #+STARTUP: nologdone
  2506. #+STARTUP: logdone
  2507. #+STARTUP: lognotedone
  2508. You can have local logging settings for a subtree by setting the LOGGING
  2509. property to one or more of these keywords."
  2510. :group 'org-todo
  2511. :group 'org-progress
  2512. :type '(choice
  2513. (const :tag "No logging" nil)
  2514. (const :tag "Record CLOSED timestamp" time)
  2515. (const :tag "Record CLOSED timestamp with note." note)))
  2516. ;; Normalize old uses of org-log-done.
  2517. (cond
  2518. ((eq org-log-done t) (setq org-log-done 'time))
  2519. ((and (listp org-log-done) (memq 'done org-log-done))
  2520. (setq org-log-done 'note)))
  2521. (defcustom org-log-reschedule nil
  2522. "Information to record when the scheduling date of a tasks is modified.
  2523. Possible values are:
  2524. nil Don't add anything, just change the date
  2525. time Add a time stamp to the task
  2526. note Prompt for a note and add it with template `org-log-note-headings'
  2527. This option can also be set with on a per-file-basis with
  2528. #+STARTUP: nologreschedule
  2529. #+STARTUP: logreschedule
  2530. #+STARTUP: lognotereschedule"
  2531. :group 'org-todo
  2532. :group 'org-progress
  2533. :type '(choice
  2534. (const :tag "No logging" nil)
  2535. (const :tag "Record timestamp" time)
  2536. (const :tag "Record timestamp with note." note)))
  2537. (defcustom org-log-redeadline nil
  2538. "Information to record when the deadline date of a tasks is modified.
  2539. Possible values are:
  2540. nil Don't add anything, just change the date
  2541. time Add a time stamp to the task
  2542. note Prompt for a note and add it with template `org-log-note-headings'
  2543. This option can also be set with on a per-file-basis with
  2544. #+STARTUP: nologredeadline
  2545. #+STARTUP: logredeadline
  2546. #+STARTUP: lognoteredeadline
  2547. You can have local logging settings for a subtree by setting the LOGGING
  2548. property to one or more of these keywords."
  2549. :group 'org-todo
  2550. :group 'org-progress
  2551. :type '(choice
  2552. (const :tag "No logging" nil)
  2553. (const :tag "Record timestamp" time)
  2554. (const :tag "Record timestamp with note." note)))
  2555. (defcustom org-log-note-clock-out nil
  2556. "Non-nil means record a note when clocking out of an item.
  2557. This can also be configured on a per-file basis by adding one of
  2558. the following lines anywhere in the buffer:
  2559. #+STARTUP: lognoteclock-out
  2560. #+STARTUP: nolognoteclock-out"
  2561. :group 'org-todo
  2562. :group 'org-progress
  2563. :type 'boolean)
  2564. (defcustom org-log-done-with-time t
  2565. "Non-nil means the CLOSED time stamp will contain date and time.
  2566. When nil, only the date will be recorded."
  2567. :group 'org-progress
  2568. :type 'boolean)
  2569. (defcustom org-log-note-headings
  2570. '((done . "CLOSING NOTE %t")
  2571. (state . "State %-12s from %-12S %t")
  2572. (note . "Note taken on %t")
  2573. (reschedule . "Rescheduled from %S on %t")
  2574. (delschedule . "Not scheduled, was %S on %t")
  2575. (redeadline . "New deadline from %S on %t")
  2576. (deldeadline . "Removed deadline, was %S on %t")
  2577. (refile . "Refiled on %t")
  2578. (clock-out . ""))
  2579. "Headings for notes added to entries.
  2580. The value is an alist, with the car being a symbol indicating the
  2581. note context, and the cdr is the heading to be used. The heading
  2582. may also be the empty string. The following placeholders can be
  2583. used:
  2584. %t a time stamp.
  2585. %T an active time stamp instead the default inactive one
  2586. %d a short-format time stamp.
  2587. %D an active short-format time stamp.
  2588. %s the new TODO state or time stamp (inactive), in double quotes.
  2589. %S the old TODO state or time stamp (inactive), in double quotes.
  2590. %u the user name.
  2591. %U full user name.
  2592. In fact, it is not a good idea to change the `state' entry,
  2593. because Agenda Log mode depends on the format of these entries."
  2594. :group 'org-todo
  2595. :group 'org-progress
  2596. :type '(list :greedy t
  2597. (cons (const :tag "Heading when closing an item" done) string)
  2598. (cons (const :tag
  2599. "Heading when changing todo state (todo sequence only)"
  2600. state) string)
  2601. (cons (const :tag "Heading when just taking a note" note) string)
  2602. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2603. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2604. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2605. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2606. (cons (const :tag "Heading when refiling" refile) string)
  2607. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2608. (unless (assq 'note org-log-note-headings)
  2609. (push '(note . "%t") org-log-note-headings))
  2610. (defcustom org-log-into-drawer nil
  2611. "Non-nil means insert state change notes and time stamps into a drawer.
  2612. When nil, state changes notes will be inserted after the headline and
  2613. any scheduling and clock lines, but not inside a drawer.
  2614. The value of this variable should be the name of the drawer to use.
  2615. LOGBOOK is proposed as the default drawer for this purpose, you can
  2616. also set this to a string to define the drawer of your choice.
  2617. A value of t is also allowed, representing \"LOGBOOK\".
  2618. A value of t or nil can also be set with on a per-file-basis with
  2619. #+STARTUP: logdrawer
  2620. #+STARTUP: nologdrawer
  2621. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2622. will be ignored.
  2623. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2624. a subtree.
  2625. Do not check directly this variable in a Lisp program. Call
  2626. function `org-log-into-drawer' instead."
  2627. :group 'org-todo
  2628. :group 'org-progress
  2629. :type '(choice
  2630. (const :tag "Not into a drawer" nil)
  2631. (const :tag "LOGBOOK" t)
  2632. (string :tag "Other")))
  2633. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2634. (defun org-log-into-drawer ()
  2635. "Name of the log drawer, as a string, or nil.
  2636. This is the value of `org-log-into-drawer'. However, if the
  2637. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2638. be used instead of the default value."
  2639. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2640. (cond ((equal p "nil") nil)
  2641. ((equal p "t") "LOGBOOK")
  2642. ((stringp p) p)
  2643. (p "LOGBOOK")
  2644. ((stringp org-log-into-drawer) org-log-into-drawer)
  2645. (org-log-into-drawer "LOGBOOK"))))
  2646. (defcustom org-log-state-notes-insert-after-drawers nil
  2647. "Non-nil means insert state change notes after any drawers in entry.
  2648. Only the drawers that *immediately* follow the headline and the
  2649. deadline/scheduled line are skipped.
  2650. When nil, insert notes right after the heading and perhaps the line
  2651. with deadline/scheduling if present.
  2652. This variable will have no effect if `org-log-into-drawer' is
  2653. set."
  2654. :group 'org-todo
  2655. :group 'org-progress
  2656. :type 'boolean)
  2657. (defcustom org-log-states-order-reversed t
  2658. "Non-nil means the latest state note will be directly after heading.
  2659. When nil, the state change notes will be ordered according to time.
  2660. This option can also be set with on a per-file-basis with
  2661. #+STARTUP: logstatesreversed
  2662. #+STARTUP: nologstatesreversed"
  2663. :group 'org-todo
  2664. :group 'org-progress
  2665. :type 'boolean)
  2666. (defcustom org-todo-repeat-to-state nil
  2667. "The TODO state to which a repeater should return the repeating task.
  2668. By default this is the first task in a TODO sequence, or the previous state
  2669. in a TODO_TYP set. But you can specify another task here.
  2670. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2671. :group 'org-todo
  2672. :version "24.1"
  2673. :type '(choice (const :tag "Head of sequence" nil)
  2674. (string :tag "Specific state")))
  2675. (defcustom org-log-repeat 'time
  2676. "Non-nil means record moving through the DONE state when triggering repeat.
  2677. An auto-repeating task is immediately switched back to TODO when
  2678. marked DONE. If you are not logging state changes (by adding \"@\"
  2679. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2680. record a closing note, there will be no record of the task moving
  2681. through DONE. This variable forces taking a note anyway.
  2682. nil Don't force a record
  2683. time Record a time stamp
  2684. note Prompt for a note and add it with template `org-log-note-headings'
  2685. This option can also be set with on a per-file-basis with
  2686. #+STARTUP: nologrepeat
  2687. #+STARTUP: logrepeat
  2688. #+STARTUP: lognoterepeat
  2689. You can have local logging settings for a subtree by setting the LOGGING
  2690. property to one or more of these keywords."
  2691. :group 'org-todo
  2692. :group 'org-progress
  2693. :type '(choice
  2694. (const :tag "Don't force a record" nil)
  2695. (const :tag "Force recording the DONE state" time)
  2696. (const :tag "Force recording a note with the DONE state" note)))
  2697. (defgroup org-priorities nil
  2698. "Priorities in Org mode."
  2699. :tag "Org Priorities"
  2700. :group 'org-todo)
  2701. (defcustom org-enable-priority-commands t
  2702. "Non-nil means priority commands are active.
  2703. When nil, these commands will be disabled, so that you never accidentally
  2704. set a priority."
  2705. :group 'org-priorities
  2706. :type 'boolean)
  2707. (defcustom org-highest-priority ?A
  2708. "The highest priority of TODO items. A character like ?A, ?B etc.
  2709. Must have a smaller ASCII number than `org-lowest-priority'."
  2710. :group 'org-priorities
  2711. :type 'character)
  2712. (defcustom org-lowest-priority ?C
  2713. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2714. Must have a larger ASCII number than `org-highest-priority'."
  2715. :group 'org-priorities
  2716. :type 'character)
  2717. (defcustom org-default-priority ?B
  2718. "The default priority of TODO items.
  2719. This is the priority an item gets if no explicit priority is given.
  2720. When starting to cycle on an empty priority the first step in the cycle
  2721. depends on `org-priority-start-cycle-with-default'. The resulting first
  2722. step priority must not exceed the range from `org-highest-priority' to
  2723. `org-lowest-priority' which means that `org-default-priority' has to be
  2724. in this range exclusive or inclusive the range boundaries. Else the
  2725. first step refuses to set the default and the second will fall back
  2726. to (depending on the command used) the highest or lowest priority."
  2727. :group 'org-priorities
  2728. :type 'character)
  2729. (defcustom org-priority-start-cycle-with-default t
  2730. "Non-nil means start with default priority when starting to cycle.
  2731. When this is nil, the first step in the cycle will be (depending on the
  2732. command used) one higher or lower than the default priority.
  2733. See also `org-default-priority'."
  2734. :group 'org-priorities
  2735. :type 'boolean)
  2736. (defcustom org-get-priority-function nil
  2737. "Function to extract the priority from a string.
  2738. The string is normally the headline. If this is nil Org computes the
  2739. priority from the priority cookie like [#A] in the headline. It returns
  2740. an integer, increasing by 1000 for each priority level.
  2741. The user can set a different function here, which should take a string
  2742. as an argument and return the numeric priority."
  2743. :group 'org-priorities
  2744. :version "24.1"
  2745. :type '(choice
  2746. (const nil)
  2747. (function)))
  2748. (defgroup org-time nil
  2749. "Options concerning time stamps and deadlines in Org mode."
  2750. :tag "Org Time"
  2751. :group 'org)
  2752. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2753. "Number of minutes to round time stamps to.
  2754. \\<org-mode-map>\
  2755. These are two values, the first applies when first creating a time stamp.
  2756. The second applies when changing it with the commands `S-up' and `S-down'.
  2757. When changing the time stamp, this means that it will change in steps
  2758. of N minutes, as given by the second value.
  2759. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2760. numbers should be factors of 60, so for example 5, 10, 15.
  2761. When this is larger than 1, you can still force an exact time stamp by using
  2762. a double prefix argument to a time stamp command like \
  2763. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2764. and by using a prefix arg to `S-up/down' to specify the exact number
  2765. of minutes to shift."
  2766. :group 'org-time
  2767. :get (lambda (var) ; Make sure both elements are there
  2768. (if (integerp (default-value var))
  2769. (list (default-value var) 5)
  2770. (default-value var)))
  2771. :type '(list
  2772. (integer :tag "when inserting times")
  2773. (integer :tag "when modifying times")))
  2774. ;; Normalize old customizations of this variable.
  2775. (when (integerp org-time-stamp-rounding-minutes)
  2776. (setq org-time-stamp-rounding-minutes
  2777. (list org-time-stamp-rounding-minutes
  2778. org-time-stamp-rounding-minutes)))
  2779. (defcustom org-display-custom-times nil
  2780. "Non-nil means overlay custom formats over all time stamps.
  2781. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2782. To turn this on on a per-file basis, insert anywhere in the file:
  2783. #+STARTUP: customtime"
  2784. :group 'org-time
  2785. :set 'set-default
  2786. :type 'sexp)
  2787. (make-variable-buffer-local 'org-display-custom-times)
  2788. (defcustom org-time-stamp-custom-formats
  2789. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2790. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2791. These are overlaid over the default ISO format if the variable
  2792. `org-display-custom-times' is set. Time like %H:%M should be at the
  2793. end of the second format. The custom formats are also honored by export
  2794. commands, if custom time display is turned on at the time of export."
  2795. :group 'org-time
  2796. :type 'sexp)
  2797. (defun org-time-stamp-format (&optional long inactive)
  2798. "Get the right format for a time string."
  2799. (let ((f (if long (cdr org-time-stamp-formats)
  2800. (car org-time-stamp-formats))))
  2801. (if inactive
  2802. (concat "[" (substring f 1 -1) "]")
  2803. f)))
  2804. (defcustom org-deadline-warning-days 14
  2805. "Number of days before expiration during which a deadline becomes active.
  2806. This variable governs the display in sparse trees and in the agenda.
  2807. When 0 or negative, it means use this number (the absolute value of it)
  2808. even if a deadline has a different individual lead time specified.
  2809. Custom commands can set this variable in the options section."
  2810. :group 'org-time
  2811. :group 'org-agenda-daily/weekly
  2812. :type 'integer)
  2813. (defcustom org-scheduled-delay-days 0
  2814. "Number of days before a scheduled item becomes active.
  2815. This variable governs the display in sparse trees and in the agenda.
  2816. The default value (i.e. 0) means: don't delay scheduled item.
  2817. When negative, it means use this number (the absolute value of it)
  2818. even if a scheduled item has a different individual delay time
  2819. specified.
  2820. Custom commands can set this variable in the options section."
  2821. :group 'org-time
  2822. :group 'org-agenda-daily/weekly
  2823. :version "24.4"
  2824. :package-version '(Org . "8.0")
  2825. :type 'integer)
  2826. (defcustom org-read-date-prefer-future t
  2827. "Non-nil means assume future for incomplete date input from user.
  2828. This affects the following situations:
  2829. 1. The user gives a month but not a year.
  2830. For example, if it is April and you enter \"feb 2\", this will be read
  2831. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2832. 2. The user gives a day, but no month.
  2833. For example, if today is the 15th, and you enter \"3\", Org will read
  2834. this as the third of *next* month. However, if you enter \"17\",
  2835. it will be considered as *this* month.
  2836. If you set this variable to the symbol `time', then also the following
  2837. will work:
  2838. 3. If the user gives a time.
  2839. If the time is before now, it will be interpreted as tomorrow.
  2840. Currently none of this works for ISO week specifications.
  2841. When this option is nil, the current day, month and year will always be
  2842. used as defaults.
  2843. See also `org-agenda-jump-prefer-future'."
  2844. :group 'org-time
  2845. :type '(choice
  2846. (const :tag "Never" nil)
  2847. (const :tag "Check month and day" t)
  2848. (const :tag "Check month, day, and time" time)))
  2849. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2850. "Should the agenda jump command prefer the future for incomplete dates?
  2851. The default is to do the same as configured in `org-read-date-prefer-future'.
  2852. But you can also set a deviating value here.
  2853. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2854. :group 'org-agenda
  2855. :group 'org-time
  2856. :version "24.1"
  2857. :type '(choice
  2858. (const :tag "Use org-read-date-prefer-future"
  2859. org-read-date-prefer-future)
  2860. (const :tag "Never" nil)
  2861. (const :tag "Always" t)))
  2862. (defcustom org-read-date-force-compatible-dates t
  2863. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2864. Depending on the system Emacs is running on, certain dates cannot
  2865. be represented with the type used internally to represent time.
  2866. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2867. correctly. Some systems allow for earlier dates, some for later,
  2868. some for both. One way to find out it to insert any date into an
  2869. Org buffer, putting the cursor on the year and hitting S-up and
  2870. S-down to test the range.
  2871. When this variable is set to t, the date/time prompt will not let
  2872. you specify dates outside the 1970-2037 range, so it is certain that
  2873. these dates will work in whatever version of Emacs you are
  2874. running, and also that you can move a file from one Emacs implementation
  2875. to another. WHenever Org is forcing the year for you, it will display
  2876. a message and beep.
  2877. When this variable is nil, Org will check if the date is
  2878. representable in the specific Emacs implementation you are using.
  2879. If not, it will force a year, usually the current year, and beep
  2880. to remind you. Currently this setting is not recommended because
  2881. the likelihood that you will open your Org files in an Emacs that
  2882. has limited date range is not negligible.
  2883. A workaround for this problem is to use diary sexp dates for time
  2884. stamps outside of this range."
  2885. :group 'org-time
  2886. :version "24.1"
  2887. :type 'boolean)
  2888. (defcustom org-read-date-display-live t
  2889. "Non-nil means display current interpretation of date prompt live.
  2890. This display will be in an overlay, in the minibuffer."
  2891. :group 'org-time
  2892. :type 'boolean)
  2893. (defcustom org-read-date-popup-calendar t
  2894. "Non-nil means pop up a calendar when prompting for a date.
  2895. In the calendar, the date can be selected with mouse-1. However, the
  2896. minibuffer will also be active, and you can simply enter the date as well.
  2897. When nil, only the minibuffer will be available."
  2898. :group 'org-time
  2899. :type 'boolean)
  2900. (defvaralias 'org-popup-calendar-for-date-prompt
  2901. 'org-read-date-popup-calendar)
  2902. (defcustom org-extend-today-until 0
  2903. "The hour when your day really ends. Must be an integer.
  2904. This has influence for the following applications:
  2905. - When switching the agenda to \"today\". It it is still earlier than
  2906. the time given here, the day recognized as TODAY is actually yesterday.
  2907. - When a date is read from the user and it is still before the time given
  2908. here, the current date and time will be assumed to be yesterday, 23:59.
  2909. Also, timestamps inserted in capture templates follow this rule.
  2910. IMPORTANT: This is a feature whose implementation is and likely will
  2911. remain incomplete. Really, it is only here because past midnight seems to
  2912. be the favorite working time of John Wiegley :-)"
  2913. :group 'org-time
  2914. :type 'integer)
  2915. (defcustom org-use-effective-time nil
  2916. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2917. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2918. \"effective time\" of any timestamps between midnight and 8am will be
  2919. 23:59 of the previous day."
  2920. :group 'org-time
  2921. :version "24.1"
  2922. :type 'boolean)
  2923. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2924. "When non-nil, use the last clock out time for `org-todo'.
  2925. Note that this option has precedence over the combined use of
  2926. `org-use-effective-time' and `org-extend-today-until'."
  2927. :group 'org-time
  2928. :version "24.4"
  2929. :package-version '(Org . "8.0")
  2930. :type 'boolean)
  2931. (defcustom org-edit-timestamp-down-means-later nil
  2932. "Non-nil means S-down will increase the time in a time stamp.
  2933. When nil, S-up will increase."
  2934. :group 'org-time
  2935. :type 'boolean)
  2936. (defcustom org-calendar-follow-timestamp-change t
  2937. "Non-nil means make the calendar window follow timestamp changes.
  2938. When a timestamp is modified and the calendar window is visible, it will be
  2939. moved to the new date."
  2940. :group 'org-time
  2941. :type 'boolean)
  2942. (defgroup org-tags nil
  2943. "Options concerning tags in Org mode."
  2944. :tag "Org Tags"
  2945. :group 'org)
  2946. (defcustom org-tag-alist nil
  2947. "Default tags available in Org files.
  2948. The value of this variable is an alist. Associations either:
  2949. (TAG)
  2950. (TAG . SELECT)
  2951. (SPECIAL)
  2952. where TAG is a tag as a string, SELECT is character, used to
  2953. select that tag through the fast tag selection interface, and
  2954. SPECIAL is one of the following keywords: `:startgroup',
  2955. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2956. `:newline'. These keywords are used to define a hierarchy of
  2957. tags. See manual for details.
  2958. When this variable is nil, Org mode bases tag input on what is
  2959. already in the buffer. The value can be overridden locally by
  2960. using a TAGS keyword, e.g.,
  2961. #+TAGS: tag1 tag2
  2962. See also `org-tag-persistent-alist' to sidestep this behavior."
  2963. :group 'org-tags
  2964. :type '(repeat
  2965. (choice
  2966. (cons (string :tag "Tag name")
  2967. (character :tag "Access char"))
  2968. (const :tag "Start radio group" (:startgroup))
  2969. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2970. (const :tag "Group tags delimiter" (:grouptags))
  2971. (const :tag "End radio group" (:endgroup))
  2972. (const :tag "End tag group, non distinct" (:endgrouptag))
  2973. (const :tag "New line" (:newline)))))
  2974. (defcustom org-tag-persistent-alist nil
  2975. "Tags always available in Org files.
  2976. The value of this variable is an alist. Associations either:
  2977. (TAG)
  2978. (TAG . SELECT)
  2979. (SPECIAL)
  2980. where TAG is a tag as a string, SELECT is a character, used to
  2981. select that tag through the fast tag selection interface, and
  2982. SPECIAL is one of the following keywords: `:startgroup',
  2983. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2984. `:newline'. These keywords are used to define a hierarchy of
  2985. tags. See manual for details.
  2986. Unlike to `org-tag-alist', tags defined in this variable do not
  2987. depend on a local TAGS keyword. Instead, to disable these tags
  2988. on a per-file basis, insert anywhere in the file:
  2989. #+STARTUP: noptag"
  2990. :group 'org-tags
  2991. :type '(repeat
  2992. (choice
  2993. (cons (string :tag "Tag name")
  2994. (character :tag "Access char"))
  2995. (const :tag "Start radio group" (:startgroup))
  2996. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2997. (const :tag "Group tags delimiter" (:grouptags))
  2998. (const :tag "End radio group" (:endgroup))
  2999. (const :tag "End tag group, non distinct" (:endgrouptag))
  3000. (const :tag "New line" (:newline)))))
  3001. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3002. "If non-nil, always offer completion for all tags of all agenda files.
  3003. Instead of customizing this variable directly, you might want to
  3004. set it locally for capture buffers, because there no list of
  3005. tags in that file can be created dynamically (there are none).
  3006. (add-hook \\='org-capture-mode-hook
  3007. (lambda ()
  3008. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3009. :group 'org-tags
  3010. :version "24.1"
  3011. :type 'boolean)
  3012. (defvar org-file-tags nil
  3013. "List of tags that can be inherited by all entries in the file.
  3014. The tags will be inherited if the variable `org-use-tag-inheritance'
  3015. says they should be.
  3016. This variable is populated from #+FILETAGS lines.")
  3017. (defcustom org-use-fast-tag-selection 'auto
  3018. "Non-nil means use fast tag selection scheme.
  3019. This is a special interface to select and deselect tags with single keys.
  3020. When nil, fast selection is never used.
  3021. When the symbol `auto', fast selection is used if and only if selection
  3022. characters for tags have been configured, either through the variable
  3023. `org-tag-alist' or through a #+TAGS line in the buffer.
  3024. When t, fast selection is always used and selection keys are assigned
  3025. automatically if necessary."
  3026. :group 'org-tags
  3027. :type '(choice
  3028. (const :tag "Always" t)
  3029. (const :tag "Never" nil)
  3030. (const :tag "When selection characters are configured" auto)))
  3031. (defcustom org-fast-tag-selection-single-key nil
  3032. "Non-nil means fast tag selection exits after first change.
  3033. When nil, you have to press RET to exit it.
  3034. During fast tag selection, you can toggle this flag with `C-c'.
  3035. This variable can also have the value `expert'. In this case, the window
  3036. displaying the tags menu is not even shown, until you press C-c again."
  3037. :group 'org-tags
  3038. :type '(choice
  3039. (const :tag "No" nil)
  3040. (const :tag "Yes" t)
  3041. (const :tag "Expert" expert)))
  3042. (defvar org-fast-tag-selection-include-todo nil
  3043. "Non-nil means fast tags selection interface will also offer TODO states.
  3044. This is an undocumented feature, you should not rely on it.")
  3045. (defcustom org-tags-column -77
  3046. "The column to which tags should be indented in a headline.
  3047. If this number is positive, it specifies the column. If it is negative,
  3048. it means that the tags should be flushright to that column. For example,
  3049. -80 works well for a normal 80 character screen.
  3050. When 0, place tags directly after headline text, with only one space in
  3051. between."
  3052. :group 'org-tags
  3053. :type 'integer)
  3054. (defcustom org-auto-align-tags t
  3055. "Non-nil keeps tags aligned when modifying headlines.
  3056. Some operations (i.e. demoting) change the length of a headline and
  3057. therefore shift the tags around. With this option turned on, after
  3058. each such operation the tags are again aligned to `org-tags-column'."
  3059. :group 'org-tags
  3060. :type 'boolean)
  3061. (defcustom org-use-tag-inheritance t
  3062. "Non-nil means tags in levels apply also for sublevels.
  3063. When nil, only the tags directly given in a specific line apply there.
  3064. This may also be a list of tags that should be inherited, or a regexp that
  3065. matches tags that should be inherited. Additional control is possible
  3066. with the variable `org-tags-exclude-from-inheritance' which gives an
  3067. explicit list of tags to be excluded from inheritance, even if the value of
  3068. `org-use-tag-inheritance' would select it for inheritance.
  3069. If this option is t, a match early-on in a tree can lead to a large
  3070. number of matches in the subtree when constructing the agenda or creating
  3071. a sparse tree. If you only want to see the first match in a tree during
  3072. a search, check out the variable `org-tags-match-list-sublevels'."
  3073. :group 'org-tags
  3074. :type '(choice
  3075. (const :tag "Not" nil)
  3076. (const :tag "Always" t)
  3077. (repeat :tag "Specific tags" (string :tag "Tag"))
  3078. (regexp :tag "Tags matched by regexp")))
  3079. (defcustom org-tags-exclude-from-inheritance nil
  3080. "List of tags that should never be inherited.
  3081. This is a way to exclude a few tags from inheritance. For way to do
  3082. the opposite, to actively allow inheritance for selected tags,
  3083. see the variable `org-use-tag-inheritance'."
  3084. :group 'org-tags
  3085. :type '(repeat (string :tag "Tag")))
  3086. (defun org-tag-inherit-p (tag)
  3087. "Check if TAG is one that should be inherited."
  3088. (cond
  3089. ((member tag org-tags-exclude-from-inheritance) nil)
  3090. ((eq org-use-tag-inheritance t) t)
  3091. ((not org-use-tag-inheritance) nil)
  3092. ((stringp org-use-tag-inheritance)
  3093. (string-match org-use-tag-inheritance tag))
  3094. ((listp org-use-tag-inheritance)
  3095. (member tag org-use-tag-inheritance))
  3096. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3097. (defcustom org-tags-match-list-sublevels t
  3098. "Non-nil means list also sublevels of headlines matching a search.
  3099. This variable applies to tags/property searches, and also to stuck
  3100. projects because this search is based on a tags match as well.
  3101. When set to the symbol `indented', sublevels are indented with
  3102. leading dots.
  3103. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3104. the sublevels of a headline matching a tag search often also match
  3105. the same search. Listing all of them can create very long lists.
  3106. Setting this variable to nil causes subtrees of a match to be skipped.
  3107. This variable is semi-obsolete and probably should always be true. It
  3108. is better to limit inheritance to certain tags using the variables
  3109. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3110. :group 'org-tags
  3111. :type '(choice
  3112. (const :tag "No, don't list them" nil)
  3113. (const :tag "Yes, do list them" t)
  3114. (const :tag "List them, indented with leading dots" indented)))
  3115. (defcustom org-tags-sort-function nil
  3116. "When set, tags are sorted using this function as a comparator."
  3117. :group 'org-tags
  3118. :type '(choice
  3119. (const :tag "No sorting" nil)
  3120. (const :tag "Alphabetical" string<)
  3121. (const :tag "Reverse alphabetical" string>)
  3122. (function :tag "Custom function" nil)))
  3123. (defvar org-tags-history nil
  3124. "History of minibuffer reads for tags.")
  3125. (defvar org-last-tags-completion-table nil
  3126. "The last used completion table for tags.")
  3127. (defvar org-after-tags-change-hook nil
  3128. "Hook that is run after the tags in a line have changed.")
  3129. (defgroup org-properties nil
  3130. "Options concerning properties in Org mode."
  3131. :tag "Org Properties"
  3132. :group 'org)
  3133. (defcustom org-property-format "%-10s %s"
  3134. "How property key/value pairs should be formatted by `indent-line'.
  3135. When `indent-line' hits a property definition, it will format the line
  3136. according to this format, mainly to make sure that the values are
  3137. lined-up with respect to each other."
  3138. :group 'org-properties
  3139. :type 'string)
  3140. (defcustom org-properties-postprocess-alist nil
  3141. "Alist of properties and functions to adjust inserted values.
  3142. Elements of this alist must be of the form
  3143. ([string] [function])
  3144. where [string] must be a property name and [function] must be a
  3145. lambda expression: this lambda expression must take one argument,
  3146. the value to adjust, and return the new value as a string.
  3147. For example, this element will allow the property \"Remaining\"
  3148. to be updated wrt the relation between the \"Effort\" property
  3149. and the clock summary:
  3150. ((\"Remaining\" (lambda(value)
  3151. (let ((clocksum (org-clock-sum-current-item))
  3152. (effort (org-duration-to-minutes
  3153. (org-entry-get (point) \"Effort\"))))
  3154. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3155. :group 'org-properties
  3156. :version "24.1"
  3157. :type '(alist :key-type (string :tag "Property")
  3158. :value-type (function :tag "Function")))
  3159. (defcustom org-use-property-inheritance nil
  3160. "Non-nil means properties apply also for sublevels.
  3161. This setting is chiefly used during property searches. Turning it on can
  3162. cause significant overhead when doing a search, which is why it is not
  3163. on by default.
  3164. When nil, only the properties directly given in the current entry count.
  3165. When t, every property is inherited. The value may also be a list of
  3166. properties that should have inheritance, or a regular expression matching
  3167. properties that should be inherited.
  3168. However, note that some special properties use inheritance under special
  3169. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3170. and the properties ending in \"_ALL\" when they are used as descriptor
  3171. for valid values of a property.
  3172. Note for programmers:
  3173. When querying an entry with `org-entry-get', you can control if inheritance
  3174. should be used. By default, `org-entry-get' looks only at the local
  3175. properties. You can request inheritance by setting the inherit argument
  3176. to t (to force inheritance) or to `selective' (to respect the setting
  3177. in this variable)."
  3178. :group 'org-properties
  3179. :type '(choice
  3180. (const :tag "Not" nil)
  3181. (const :tag "Always" t)
  3182. (repeat :tag "Specific properties" (string :tag "Property"))
  3183. (regexp :tag "Properties matched by regexp")))
  3184. (defun org-property-inherit-p (property)
  3185. "Return a non-nil value if PROPERTY should be inherited."
  3186. (cond
  3187. ((eq org-use-property-inheritance t) t)
  3188. ((not org-use-property-inheritance) nil)
  3189. ((stringp org-use-property-inheritance)
  3190. (string-match org-use-property-inheritance property))
  3191. ((listp org-use-property-inheritance)
  3192. (member-ignore-case property org-use-property-inheritance))
  3193. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3194. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3195. "The default column format, if no other format has been defined.
  3196. This variable can be set on the per-file basis by inserting a line
  3197. #+COLUMNS: %25ITEM ....."
  3198. :group 'org-properties
  3199. :type 'string)
  3200. (defcustom org-columns-ellipses ".."
  3201. "The ellipses to be used when a field in column view is truncated.
  3202. When this is the empty string, as many characters as possible are shown,
  3203. but then there will be no visual indication that the field has been truncated.
  3204. When this is a string of length N, the last N characters of a truncated
  3205. field are replaced by this string. If the column is narrower than the
  3206. ellipses string, only part of the ellipses string will be shown."
  3207. :group 'org-properties
  3208. :type 'string)
  3209. (defconst org-global-properties-fixed
  3210. '(("VISIBILITY_ALL" . "folded children content all")
  3211. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3212. "List of property/value pairs that can be inherited by any entry.
  3213. These are fixed values, for the preset properties. The user variable
  3214. that can be used to add to this list is `org-global-properties'.
  3215. The entries in this list are cons cells where the car is a property
  3216. name and cdr is a string with the value. If the value represents
  3217. multiple items like an \"_ALL\" property, separate the items by
  3218. spaces.")
  3219. (defcustom org-global-properties nil
  3220. "List of property/value pairs that can be inherited by any entry.
  3221. This list will be combined with the constant `org-global-properties-fixed'.
  3222. The entries in this list are cons cells where the car is a property
  3223. name and cdr is a string with the value.
  3224. You can set buffer-local values for the same purpose in the variable
  3225. `org-file-properties' this by adding lines like
  3226. #+PROPERTY: NAME VALUE"
  3227. :group 'org-properties
  3228. :type '(repeat
  3229. (cons (string :tag "Property")
  3230. (string :tag "Value"))))
  3231. (defvar-local org-file-properties nil
  3232. "List of property/value pairs that can be inherited by any entry.
  3233. Valid for the current buffer.
  3234. This variable is populated from #+PROPERTY lines.")
  3235. (defgroup org-agenda nil
  3236. "Options concerning agenda views in Org mode."
  3237. :tag "Org Agenda"
  3238. :group 'org)
  3239. (defvar-local org-category nil
  3240. "Variable used by org files to set a category for agenda display.
  3241. Such files should use a file variable to set it, for example
  3242. # -*- mode: org; org-category: \"ELisp\"
  3243. or contain a special line
  3244. #+CATEGORY: ELisp
  3245. If the file does not specify a category, then file's base name
  3246. is used instead.")
  3247. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3248. (defcustom org-agenda-files nil
  3249. "The files to be used for agenda display.
  3250. If an entry is a directory, all files in that directory that are matched
  3251. by `org-agenda-file-regexp' will be part of the file list.
  3252. If the value of the variable is not a list but a single file name, then
  3253. the list of agenda files is actually stored and maintained in that file,
  3254. one agenda file per line. In this file paths can be given relative to
  3255. `org-directory'. Tilde expansion and environment variable substitution
  3256. are also made.
  3257. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3258. and removed with `\\[org-remove-file]'."
  3259. :group 'org-agenda
  3260. :type '(choice
  3261. (repeat :tag "List of files and directories" file)
  3262. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3263. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3264. "Regular expression to match files for `org-agenda-files'.
  3265. If any element in the list in that variable contains a directory instead
  3266. of a normal file, all files in that directory that are matched by this
  3267. regular expression will be included."
  3268. :group 'org-agenda
  3269. :type 'regexp)
  3270. (defcustom org-agenda-text-search-extra-files nil
  3271. "List of extra files to be searched by text search commands.
  3272. These files will be searched in addition to the agenda files by the
  3273. commands `org-search-view' (`\\[org-agenda] s') \
  3274. and `org-occur-in-agenda-files'.
  3275. Note that these files will only be searched for text search commands,
  3276. not for the other agenda views like todo lists, tag searches or the weekly
  3277. agenda. This variable is intended to list notes and possibly archive files
  3278. that should also be searched by these two commands.
  3279. In fact, if the first element in the list is the symbol `agenda-archives',
  3280. then all archive files of all agenda files will be added to the search
  3281. scope."
  3282. :group 'org-agenda
  3283. :type '(set :greedy t
  3284. (const :tag "Agenda Archives" agenda-archives)
  3285. (repeat :inline t (file))))
  3286. (defvaralias 'org-agenda-multi-occur-extra-files
  3287. 'org-agenda-text-search-extra-files)
  3288. (defcustom org-agenda-skip-unavailable-files nil
  3289. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3290. A nil value means to remove them, after a query, from the list."
  3291. :group 'org-agenda
  3292. :type 'boolean)
  3293. (defcustom org-calendar-to-agenda-key [?c]
  3294. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3295. The command `org-calendar-goto-agenda' will be bound to this key. The
  3296. default is the character `c' because then `c' can be used to switch back and
  3297. forth between agenda and calendar."
  3298. :group 'org-agenda
  3299. :type 'sexp)
  3300. (defcustom org-calendar-insert-diary-entry-key [?i]
  3301. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3302. This option is irrelevant until `org-agenda-diary-file' has been configured
  3303. to point to an Org file. When that is the case, the command
  3304. `org-agenda-diary-entry' will be bound to the key given here, by default
  3305. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3306. if you want to continue doing this, you need to change this to a different
  3307. key."
  3308. :group 'org-agenda
  3309. :type 'sexp)
  3310. (defcustom org-agenda-diary-file 'diary-file
  3311. "File to which to add new entries with the `i' key in agenda and calendar.
  3312. When this is the symbol `diary-file', the functionality in the Emacs
  3313. calendar will be used to add entries to the `diary-file'. But when this
  3314. points to a file, `org-agenda-diary-entry' will be used instead."
  3315. :group 'org-agenda
  3316. :type '(choice
  3317. (const :tag "The standard Emacs diary file" diary-file)
  3318. (file :tag "Special Org file diary entries")))
  3319. (eval-after-load "calendar"
  3320. '(progn
  3321. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3322. 'org-calendar-goto-agenda)
  3323. (add-hook 'calendar-mode-hook
  3324. (lambda ()
  3325. (unless (eq org-agenda-diary-file 'diary-file)
  3326. (define-key calendar-mode-map
  3327. org-calendar-insert-diary-entry-key
  3328. 'org-agenda-diary-entry))))))
  3329. (defgroup org-latex nil
  3330. "Options for embedding LaTeX code into Org mode."
  3331. :tag "Org LaTeX"
  3332. :group 'org)
  3333. (defcustom org-format-latex-options
  3334. '(:foreground default :background default :scale 1.0
  3335. :html-foreground "Black" :html-background "Transparent"
  3336. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3337. "Options for creating images from LaTeX fragments.
  3338. This is a property list with the following properties:
  3339. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3340. `default' means use the foreground of the default face.
  3341. `auto' means use the foreground from the text face.
  3342. :background the background color, or \"Transparent\".
  3343. `default' means use the background of the default face.
  3344. `auto' means use the background from the text face.
  3345. :scale a scaling factor for the size of the images, to get more pixels
  3346. :html-foreground, :html-background, :html-scale
  3347. the same numbers for HTML export.
  3348. :matchers a list indicating which matchers should be used to
  3349. find LaTeX fragments. Valid members of this list are:
  3350. \"begin\" find environments
  3351. \"$1\" find single characters surrounded by $.$
  3352. \"$\" find math expressions surrounded by $...$
  3353. \"$$\" find math expressions surrounded by $$....$$
  3354. \"\\(\" find math expressions surrounded by \\(...\\)
  3355. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3356. :group 'org-latex
  3357. :type 'plist)
  3358. (defcustom org-format-latex-signal-error t
  3359. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3360. When nil, just push out a message."
  3361. :group 'org-latex
  3362. :version "24.1"
  3363. :type 'boolean)
  3364. (defcustom org-latex-to-mathml-jar-file nil
  3365. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3366. Use this to specify additional executable file say a jar file.
  3367. When using MathToWeb as the converter, specify the full-path to
  3368. your mathtoweb.jar file."
  3369. :group 'org-latex
  3370. :version "24.1"
  3371. :type '(choice
  3372. (const :tag "None" nil)
  3373. (file :tag "JAR file" :must-match t)))
  3374. (defcustom org-latex-to-mathml-convert-command nil
  3375. "Command to convert LaTeX fragments to MathML.
  3376. Replace format-specifiers in the command as noted below and use
  3377. `shell-command' to convert LaTeX to MathML.
  3378. %j: Executable file in fully expanded form as specified by
  3379. `org-latex-to-mathml-jar-file'.
  3380. %I: Input LaTeX file in fully expanded form.
  3381. %i: The latex fragment to be converted.
  3382. %o: Output MathML file.
  3383. This command is used by `org-create-math-formula'.
  3384. When using MathToWeb as the converter, set this option to
  3385. \"java -jar %j -unicode -force -df %o %I\".
  3386. When using LaTeXML set this option to
  3387. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3388. :group 'org-latex
  3389. :version "24.1"
  3390. :type '(choice
  3391. (const :tag "None" nil)
  3392. (string :tag "\nShell command")))
  3393. (defcustom org-preview-latex-default-process 'dvipng
  3394. "The default process to convert LaTeX fragments to image files.
  3395. All available processes and theirs documents can be found in
  3396. `org-preview-latex-process-alist', which see."
  3397. :group 'org-latex
  3398. :version "26.1"
  3399. :package-version '(Org . "9.0")
  3400. :type 'symbol)
  3401. (defcustom org-preview-latex-process-alist
  3402. '((dvipng
  3403. :programs ("latex" "dvipng")
  3404. :description "dvi > png"
  3405. :message "you need to install the programs: latex and dvipng."
  3406. :image-input-type "dvi"
  3407. :image-output-type "png"
  3408. :image-size-adjust (1.0 . 1.0)
  3409. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3410. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3411. (dvisvgm
  3412. :programs ("latex" "dvisvgm")
  3413. :description "dvi > svg"
  3414. :message "you need to install the programs: latex and dvisvgm."
  3415. :use-xcolor t
  3416. :image-input-type "dvi"
  3417. :image-output-type "svg"
  3418. :image-size-adjust (1.7 . 1.5)
  3419. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3420. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3421. (imagemagick
  3422. :programs ("latex" "convert")
  3423. :description "pdf > png"
  3424. :message "you need to install the programs: latex and imagemagick."
  3425. :use-xcolor t
  3426. :image-input-type "pdf"
  3427. :image-output-type "png"
  3428. :image-size-adjust (1.0 . 1.0)
  3429. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3430. :image-converter
  3431. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3432. "Definitions of external processes for LaTeX previewing.
  3433. Org mode can use some external commands to generate TeX snippet's images for
  3434. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3435. `org-create-formula-image' how to call them.
  3436. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3437. PROPERTIES accepts the following attributes:
  3438. :programs list of strings, required programs.
  3439. :description string, describe the process.
  3440. :message string, message it when required programs cannot be found.
  3441. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3442. :image-output-type string, output file type of image converter (e.g., \"png\").
  3443. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3444. deal with background and foreground color of image.
  3445. Otherwise, dvipng style background and foregroud color
  3446. format are generated. You may then refer to them in
  3447. command options with \"%F\" and \"%B\".
  3448. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3449. image size showed in buffer and the cdr element is for
  3450. HTML file. This option is only useful for process
  3451. developers, users should use variable
  3452. `org-format-latex-options' instead.
  3453. :post-clean list of strings, files matched are to be cleaned up once
  3454. the image is generated. When nil, the files with \".dvi\",
  3455. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3456. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3457. be cleaned up.
  3458. :latex-header list of strings, the LaTeX header of the snippet file.
  3459. When nil, the fallback value is used instead, which is
  3460. controlled by `org-format-latex-header',
  3461. `org-latex-default-packages-alist' and
  3462. `org-latex-packages-alist', which see.
  3463. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3464. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3465. replaced with values defined below.
  3466. :image-converter list of image converter commands strings. Each of them is
  3467. given to the shell and supports any of the following
  3468. place-holders defined below.
  3469. Place-holders used by `:image-converter' and `:latex-compiler':
  3470. %f input file name
  3471. %b base name of input file
  3472. %o base directory of input file
  3473. %O absolute output file name
  3474. Place-holders only used by `:image-converter':
  3475. %F foreground of image
  3476. %B background of image
  3477. %D dpi, which is used to adjust image size by some processing commands.
  3478. %S the image size scale ratio, which is used to adjust image size by some
  3479. processing commands."
  3480. :group 'org-latex
  3481. :version "26.1"
  3482. :package-version '(Org . "9.0")
  3483. :type '(alist :tag "LaTeX to image backends"
  3484. :value-type (plist)))
  3485. (defcustom org-preview-latex-image-directory "ltximg/"
  3486. "Path to store latex preview images.
  3487. A relative path here creates many directories relative to the
  3488. processed org files paths. An absolute path puts all preview
  3489. images at the same place."
  3490. :group 'org-latex
  3491. :version "26.1"
  3492. :package-version '(Org . "9.0")
  3493. :type 'string)
  3494. (defun org-format-latex-mathml-available-p ()
  3495. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3496. (save-match-data
  3497. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3498. org-latex-to-mathml-convert-command)
  3499. (let ((executable (car (split-string
  3500. org-latex-to-mathml-convert-command))))
  3501. (when (executable-find executable)
  3502. (if (string-match
  3503. "%j" org-latex-to-mathml-convert-command)
  3504. (file-readable-p org-latex-to-mathml-jar-file)
  3505. t))))))
  3506. (defcustom org-format-latex-header "\\documentclass{article}
  3507. \\usepackage[usenames]{color}
  3508. \[PACKAGES]
  3509. \[DEFAULT-PACKAGES]
  3510. \\pagestyle{empty} % do not remove
  3511. % The settings below are copied from fullpage.sty
  3512. \\setlength{\\textwidth}{\\paperwidth}
  3513. \\addtolength{\\textwidth}{-3cm}
  3514. \\setlength{\\oddsidemargin}{1.5cm}
  3515. \\addtolength{\\oddsidemargin}{-2.54cm}
  3516. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3517. \\setlength{\\textheight}{\\paperheight}
  3518. \\addtolength{\\textheight}{-\\headheight}
  3519. \\addtolength{\\textheight}{-\\headsep}
  3520. \\addtolength{\\textheight}{-\\footskip}
  3521. \\addtolength{\\textheight}{-3cm}
  3522. \\setlength{\\topmargin}{1.5cm}
  3523. \\addtolength{\\topmargin}{-2.54cm}"
  3524. "The document header used for processing LaTeX fragments.
  3525. It is imperative that this header make sure that no page number
  3526. appears on the page. The package defined in the variables
  3527. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3528. will either replace the placeholder \"[PACKAGES]\" in this
  3529. header, or they will be appended."
  3530. :group 'org-latex
  3531. :type 'string)
  3532. (defun org-set-packages-alist (var val)
  3533. "Set the packages alist and make sure it has 3 elements per entry."
  3534. (set var (mapcar (lambda (x)
  3535. (if (and (consp x) (= (length x) 2))
  3536. (list (car x) (nth 1 x) t)
  3537. x))
  3538. val)))
  3539. (defun org-get-packages-alist (var)
  3540. "Get the packages alist and make sure it has 3 elements per entry."
  3541. (mapcar (lambda (x)
  3542. (if (and (consp x) (= (length x) 2))
  3543. (list (car x) (nth 1 x) t)
  3544. x))
  3545. (default-value var)))
  3546. (defcustom org-latex-default-packages-alist
  3547. '(("AUTO" "inputenc" t ("pdflatex"))
  3548. ("T1" "fontenc" t ("pdflatex"))
  3549. ("" "graphicx" t)
  3550. ("" "grffile" t)
  3551. ("" "longtable" nil)
  3552. ("" "wrapfig" nil)
  3553. ("" "rotating" nil)
  3554. ("normalem" "ulem" t)
  3555. ("" "amsmath" t)
  3556. ("" "textcomp" t)
  3557. ("" "amssymb" t)
  3558. ("" "capt-of" nil)
  3559. ("" "hyperref" nil))
  3560. "Alist of default packages to be inserted in the header.
  3561. Change this only if one of the packages here causes an
  3562. incompatibility with another package you are using.
  3563. The packages in this list are needed by one part or another of
  3564. Org mode to function properly:
  3565. - inputenc, fontenc: for basic font and character selection
  3566. - graphicx: for including images
  3567. - grffile: allow periods and spaces in graphics file names
  3568. - longtable: For multipage tables
  3569. - wrapfig: for figure placement
  3570. - rotating: for sideways figures and tables
  3571. - ulem: for underline and strike-through
  3572. - amsmath: for subscript and superscript and math environments
  3573. - textcomp, amssymb: for various symbols used
  3574. for interpreting the entities in `org-entities'. You can skip
  3575. some of these packages if you don't use any of their symbols.
  3576. - capt-of: for captions outside of floats
  3577. - hyperref: for cross references
  3578. Therefore you should not modify this variable unless you know
  3579. what you are doing. The one reason to change it anyway is that
  3580. you might be loading some other package that conflicts with one
  3581. of the default packages. Each element is either a cell or
  3582. a string.
  3583. A cell is of the format
  3584. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3585. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3586. when compiling LaTeX snippets into images for inclusion into
  3587. non-LaTeX output. COMPILERS is a list of compilers that should
  3588. include the package, see `org-latex-compiler'. If the document
  3589. compiler is not in the list, and the list is non-nil, the package
  3590. will not be inserted in the final document.
  3591. A string will be inserted as-is in the header of the document."
  3592. :group 'org-latex
  3593. :group 'org-export-latex
  3594. :set 'org-set-packages-alist
  3595. :get 'org-get-packages-alist
  3596. :version "26.1"
  3597. :package-version '(Org . "8.3")
  3598. :type '(repeat
  3599. (choice
  3600. (list :tag "options/package pair"
  3601. (string :tag "options")
  3602. (string :tag "package")
  3603. (boolean :tag "Snippet"))
  3604. (string :tag "A line of LaTeX"))))
  3605. (defcustom org-latex-packages-alist nil
  3606. "Alist of packages to be inserted in every LaTeX header.
  3607. These will be inserted after `org-latex-default-packages-alist'.
  3608. Each element is either a cell or a string.
  3609. A cell is of the format:
  3610. (\"options\" \"package\" SNIPPET-FLAG)
  3611. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3612. needed when turning LaTeX snippets into images for inclusion into
  3613. non-LaTeX output.
  3614. A string will be inserted as-is in the header of the document.
  3615. Make sure that you only list packages here which:
  3616. - you want in every file;
  3617. - do not conflict with the setup in `org-format-latex-header';
  3618. - do not conflict with the default packages in
  3619. `org-latex-default-packages-alist'."
  3620. :group 'org-latex
  3621. :group 'org-export-latex
  3622. :set 'org-set-packages-alist
  3623. :get 'org-get-packages-alist
  3624. :type '(repeat
  3625. (choice
  3626. (list :tag "options/package pair"
  3627. (string :tag "options")
  3628. (string :tag "package")
  3629. (boolean :tag "Snippet"))
  3630. (string :tag "A line of LaTeX"))))
  3631. (defgroup org-appearance nil
  3632. "Settings for Org mode appearance."
  3633. :tag "Org Appearance"
  3634. :group 'org)
  3635. (defcustom org-level-color-stars-only nil
  3636. "Non-nil means fontify only the stars in each headline.
  3637. When nil, the entire headline is fontified.
  3638. Changing it requires restart of `font-lock-mode' to become effective
  3639. also in regions already fontified."
  3640. :group 'org-appearance
  3641. :type 'boolean)
  3642. (defcustom org-hide-leading-stars nil
  3643. "Non-nil means hide the first N-1 stars in a headline.
  3644. This works by using the face `org-hide' for these stars. This
  3645. face is white for a light background, and black for a dark
  3646. background. You may have to customize the face `org-hide' to
  3647. make this work.
  3648. Changing it requires restart of `font-lock-mode' to become effective
  3649. also in regions already fontified.
  3650. You may also set this on a per-file basis by adding one of the following
  3651. lines to the buffer:
  3652. #+STARTUP: hidestars
  3653. #+STARTUP: showstars"
  3654. :group 'org-appearance
  3655. :type 'boolean)
  3656. (defcustom org-hidden-keywords nil
  3657. "List of symbols corresponding to keywords to be hidden the org buffer.
  3658. For example, a value \\='(title) for this list will make the document's title
  3659. appear in the buffer without the initial #+TITLE: keyword."
  3660. :group 'org-appearance
  3661. :version "24.1"
  3662. :type '(set (const :tag "#+AUTHOR" author)
  3663. (const :tag "#+DATE" date)
  3664. (const :tag "#+EMAIL" email)
  3665. (const :tag "#+TITLE" title)))
  3666. (defcustom org-custom-properties nil
  3667. "List of properties (as strings) with a special meaning.
  3668. The default use of these custom properties is to let the user
  3669. hide them with `org-toggle-custom-properties-visibility'."
  3670. :group 'org-properties
  3671. :group 'org-appearance
  3672. :version "24.3"
  3673. :type '(repeat (string :tag "Property Name")))
  3674. (defcustom org-fontify-done-headline nil
  3675. "Non-nil means change the face of a headline if it is marked DONE.
  3676. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3677. When this is non-nil, the headline after the keyword is set to the
  3678. `org-headline-done' as an additional indication."
  3679. :group 'org-appearance
  3680. :type 'boolean)
  3681. (defcustom org-fontify-emphasized-text t
  3682. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3683. Changing this variable requires a restart of Emacs to take effect."
  3684. :group 'org-appearance
  3685. :type 'boolean)
  3686. (defcustom org-fontify-whole-heading-line nil
  3687. "Non-nil means fontify the whole line for headings.
  3688. This is useful when setting a background color for the
  3689. org-level-* faces."
  3690. :group 'org-appearance
  3691. :type 'boolean)
  3692. (defcustom org-highlight-latex-and-related nil
  3693. "Non-nil means highlight LaTeX related syntax in the buffer.
  3694. When non nil, the value should be a list containing any of the
  3695. following symbols:
  3696. `latex' Highlight LaTeX snippets and environments.
  3697. `script' Highlight subscript and superscript.
  3698. `entities' Highlight entities."
  3699. :group 'org-appearance
  3700. :version "24.4"
  3701. :package-version '(Org . "8.0")
  3702. :type '(choice
  3703. (const :tag "No highlighting" nil)
  3704. (set :greedy t :tag "Highlight"
  3705. (const :tag "LaTeX snippets and environments" latex)
  3706. (const :tag "Subscript and superscript" script)
  3707. (const :tag "Entities" entities))))
  3708. (defcustom org-hide-emphasis-markers nil
  3709. "Non-nil mean font-lock should hide the emphasis marker characters."
  3710. :group 'org-appearance
  3711. :type 'boolean)
  3712. (defcustom org-hide-macro-markers nil
  3713. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3714. :group 'org-appearance
  3715. :type 'boolean)
  3716. (defcustom org-pretty-entities nil
  3717. "Non-nil means show entities as UTF8 characters.
  3718. When nil, the \\name form remains in the buffer."
  3719. :group 'org-appearance
  3720. :version "24.1"
  3721. :type 'boolean)
  3722. (defcustom org-pretty-entities-include-sub-superscripts t
  3723. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3724. :group 'org-appearance
  3725. :version "24.1"
  3726. :type 'boolean)
  3727. (defvar org-emph-re nil
  3728. "Regular expression for matching emphasis.
  3729. After a match, the match groups contain these elements:
  3730. 0 The match of the full regular expression, including the characters
  3731. before and after the proper match
  3732. 1 The character before the proper match, or empty at beginning of line
  3733. 2 The proper match, including the leading and trailing markers
  3734. 3 The leading marker like * or /, indicating the type of highlighting
  3735. 4 The text between the emphasis markers, not including the markers
  3736. 5 The character after the match, empty at the end of a line")
  3737. (defvar org-verbatim-re nil
  3738. "Regular expression for matching verbatim text.")
  3739. (defvar org-emphasis-regexp-components) ; defined just below
  3740. (defvar org-emphasis-alist) ; defined just below
  3741. (defun org-set-emph-re (var val)
  3742. "Set variable and compute the emphasis regular expression."
  3743. (set var val)
  3744. (when (and (boundp 'org-emphasis-alist)
  3745. (boundp 'org-emphasis-regexp-components)
  3746. org-emphasis-alist org-emphasis-regexp-components)
  3747. (pcase-let*
  3748. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3749. (body (if (<= nl 0) body
  3750. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3751. (template
  3752. (format (concat "\\([%s]\\|^\\)" ;before markers
  3753. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3754. "\\([%s]\\|$\\)") ;after markers
  3755. pre border border body border post)))
  3756. (setq org-emph-re (format template "*/_+"))
  3757. (setq org-verbatim-re (format template "=~")))))
  3758. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3759. ;; set this option proved cumbersome. See this message/thread:
  3760. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3761. (defvar org-emphasis-regexp-components
  3762. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3763. "Components used to build the regular expression for emphasis.
  3764. This is a list with five entries. Terminology: In an emphasis string
  3765. like \" *strong word* \", we call the initial space PREMATCH, the final
  3766. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3767. and \"trong wor\" is the body. The different components in this variable
  3768. specify what is allowed/forbidden in each part:
  3769. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3770. post Chars allowed as postmatch. End of line will be allowed too.
  3771. border The chars *forbidden* as border characters.
  3772. body-regexp A regexp like \".\" to match a body character. Don't use
  3773. non-shy groups here, and don't allow newline here.
  3774. newline The maximum number of newlines allowed in an emphasis exp.
  3775. You need to reload Org or to restart Emacs after customizing this.")
  3776. (defcustom org-emphasis-alist
  3777. '(("*" bold)
  3778. ("/" italic)
  3779. ("_" underline)
  3780. ("=" org-verbatim verbatim)
  3781. ("~" org-code verbatim)
  3782. ("+" (:strike-through t)))
  3783. "Alist of characters and faces to emphasize text.
  3784. Text starting and ending with a special character will be emphasized,
  3785. for example *bold*, _underlined_ and /italic/. This variable sets the
  3786. marker characters and the face to be used by font-lock for highlighting
  3787. in Org buffers.
  3788. You need to reload Org or to restart Emacs after customizing this."
  3789. :group 'org-appearance
  3790. :set 'org-set-emph-re
  3791. :version "24.4"
  3792. :package-version '(Org . "8.0")
  3793. :type '(repeat
  3794. (list
  3795. (string :tag "Marker character")
  3796. (choice
  3797. (face :tag "Font-lock-face")
  3798. (plist :tag "Face property list"))
  3799. (option (const verbatim)))))
  3800. (defvar org-protecting-blocks '("src" "example" "export")
  3801. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3802. This is needed for font-lock setup.")
  3803. ;;; Functions and variables from their packages
  3804. ;; Declared here to avoid compiler warnings
  3805. (defvar mark-active)
  3806. ;; Various packages
  3807. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3808. (declare-function calendar-forward-day "cal-move" (arg))
  3809. (declare-function calendar-goto-date "cal-move" (date))
  3810. (declare-function calendar-goto-today "cal-move" ())
  3811. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3812. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3813. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3814. (declare-function cdlatex-tab "ext:cdlatex" ())
  3815. (declare-function dired-get-filename
  3816. "dired"
  3817. (&optional localp no-error-if-not-filep))
  3818. (declare-function iswitchb-read-buffer
  3819. "iswitchb"
  3820. (prompt &optional
  3821. default require-match _predicate start matches-set))
  3822. (declare-function org-agenda-change-all-lines
  3823. "org-agenda"
  3824. (newhead hdmarker &optional fixface just-this))
  3825. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3826. "org-agenda"
  3827. (&optional end))
  3828. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3829. (declare-function org-agenda-format-item
  3830. "org-agenda"
  3831. (extra txt &optional level category tags dotime
  3832. remove-re habitp))
  3833. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3834. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3835. (declare-function org-agenda-save-markers-for-cut-and-paste
  3836. "org-agenda"
  3837. (beg end))
  3838. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3839. (declare-function org-agenda-skip "org-agenda" ())
  3840. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3841. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3842. (declare-function org-indent-mode "org-indent" (&optional arg))
  3843. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3844. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3845. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3846. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3847. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3848. (declare-function parse-time-string "parse-time" (string))
  3849. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3850. (defvar align-mode-rules-list)
  3851. (defvar calc-embedded-close-formula)
  3852. (defvar calc-embedded-open-formula)
  3853. (defvar calc-embedded-open-mode)
  3854. (defvar font-lock-unfontify-region-function)
  3855. (defvar iswitchb-temp-buflist)
  3856. (defvar org-agenda-tags-todo-honor-ignore-options)
  3857. (defvar remember-data-file)
  3858. (defvar texmathp-why)
  3859. ;;;###autoload
  3860. (defun turn-on-orgtbl ()
  3861. "Unconditionally turn on `orgtbl-mode'."
  3862. (require 'org-table)
  3863. (orgtbl-mode 1))
  3864. (defun org-at-table-p (&optional table-type)
  3865. "Non-nil if the cursor is inside an Org table.
  3866. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3867. If `org-enable-table-editor' is nil, return nil unconditionally."
  3868. (and
  3869. org-enable-table-editor
  3870. (save-excursion
  3871. (beginning-of-line)
  3872. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3873. (or (not (derived-mode-p 'org-mode))
  3874. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3875. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3876. (defun org-at-table.el-p ()
  3877. "Non-nil when point is at a table.el table."
  3878. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3879. (let ((element (org-element-at-point)))
  3880. (and (eq (org-element-type element) 'table)
  3881. (eq (org-element-property :type element) 'table.el)))))
  3882. (defun org-at-table-hline-p ()
  3883. "Non-nil when point is inside a hline in a table.
  3884. Assume point is already in a table. If `org-enable-table-editor'
  3885. is nil, return nil unconditionally."
  3886. (and org-enable-table-editor
  3887. (save-excursion
  3888. (beginning-of-line)
  3889. (looking-at org-table-hline-regexp))))
  3890. (defun org-table-map-tables (function &optional quietly)
  3891. "Apply FUNCTION to the start of all tables in the buffer."
  3892. (org-with-wide-buffer
  3893. (goto-char (point-min))
  3894. (while (re-search-forward org-table-any-line-regexp nil t)
  3895. (unless quietly
  3896. (message "Mapping tables: %d%%"
  3897. (floor (* 100.0 (point)) (buffer-size))))
  3898. (beginning-of-line 1)
  3899. (when (and (looking-at org-table-line-regexp)
  3900. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3901. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3902. (save-excursion (funcall function))
  3903. (or (looking-at org-table-line-regexp)
  3904. (forward-char 1)))
  3905. (re-search-forward org-table-any-border-regexp nil 1)))
  3906. (unless quietly (message "Mapping tables: done")))
  3907. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3908. (declare-function org-clock-update-mode-line "org-clock" ())
  3909. (declare-function org-resolve-clocks "org-clock"
  3910. (&optional also-non-dangling-p prompt last-valid))
  3911. (defun org-at-TBLFM-p (&optional pos)
  3912. "Non-nil when point (or POS) is in #+TBLFM line."
  3913. (save-excursion
  3914. (goto-char (or pos (point)))
  3915. (beginning-of-line)
  3916. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3917. (eq (org-element-type (org-element-at-point)) 'table))))
  3918. (defvar org-clock-start-time)
  3919. (defvar org-clock-marker (make-marker)
  3920. "Marker recording the last clock-in.")
  3921. (defvar org-clock-hd-marker (make-marker)
  3922. "Marker recording the last clock-in, but the headline position.")
  3923. (defvar org-clock-heading ""
  3924. "The heading of the current clock entry.")
  3925. (defun org-clock-is-active ()
  3926. "Return the buffer where the clock is currently running.
  3927. Return nil if no clock is running."
  3928. (marker-buffer org-clock-marker))
  3929. (defun org-check-running-clock ()
  3930. "Check if the current buffer contains the running clock.
  3931. If yes, offer to stop it and to save the buffer with the changes."
  3932. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3933. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3934. (buffer-name))))
  3935. (org-clock-out)
  3936. (when (y-or-n-p "Save changed buffer?")
  3937. (save-buffer))))
  3938. (defun org-clocktable-try-shift (dir n)
  3939. "Check if this line starts a clock table, if yes, shift the time block."
  3940. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3941. (org-clocktable-shift dir n)))
  3942. ;;;###autoload
  3943. (defun org-clock-persistence-insinuate ()
  3944. "Set up hooks for clock persistence."
  3945. (require 'org-clock)
  3946. (add-hook 'org-mode-hook 'org-clock-load)
  3947. (add-hook 'kill-emacs-hook 'org-clock-save))
  3948. (defgroup org-archive nil
  3949. "Options concerning archiving in Org mode."
  3950. :tag "Org Archive"
  3951. :group 'org-structure)
  3952. (defcustom org-archive-location "%s_archive::"
  3953. "The location where subtrees should be archived.
  3954. The value of this variable is a string, consisting of two parts,
  3955. separated by a double-colon. The first part is a filename and
  3956. the second part is a headline.
  3957. When the filename is omitted, archiving happens in the same file.
  3958. %s in the filename will be replaced by the current file
  3959. name (without the directory part). Archiving to a different file
  3960. is useful to keep archived entries from contributing to the
  3961. Org Agenda.
  3962. The archived entries will be filed as subtrees of the specified
  3963. headline. When the headline is omitted, the subtrees are simply
  3964. filed away at the end of the file, as top-level entries. Also in
  3965. the heading you can use %s to represent the file name, this can be
  3966. useful when using the same archive for a number of different files.
  3967. Here are a few examples:
  3968. \"%s_archive::\"
  3969. If the current file is Projects.org, archive in file
  3970. Projects.org_archive, as top-level trees. This is the default.
  3971. \"::* Archived Tasks\"
  3972. Archive in the current file, under the top-level headline
  3973. \"* Archived Tasks\".
  3974. \"~/org/archive.org::\"
  3975. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3976. \"~/org/archive.org::* From %s\"
  3977. Archive in file ~/org/archive.org (absolute path), under headlines
  3978. \"From FILENAME\" where file name is the current file name.
  3979. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3980. The \"datetree/\" string is special, signifying to archive
  3981. items to the datetree. Items are placed in either the CLOSED
  3982. date of the item, or the current date if there is no CLOSED date.
  3983. The heading will be a subentry to the current date. There doesn't
  3984. need to be a heading, but there always needs to be a slash after
  3985. datetree. For example, to store archived items directly in the
  3986. datetree, use \"~/org/datetree.org::datetree/\".
  3987. \"basement::** Finished Tasks\"
  3988. Archive in file ./basement (relative path), as level 3 trees
  3989. below the level 2 heading \"** Finished Tasks\".
  3990. You may set this option on a per-file basis by adding to the buffer a
  3991. line like
  3992. #+ARCHIVE: basement::** Finished Tasks
  3993. You may also define it locally for a subtree by setting an ARCHIVE property
  3994. in the entry. If such a property is found in an entry, or anywhere up
  3995. the hierarchy, it will be used."
  3996. :group 'org-archive
  3997. :type 'string)
  3998. (defcustom org-agenda-skip-archived-trees t
  3999. "Non-nil means the agenda will skip any items located in archived trees.
  4000. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4001. variable is no longer recommended, you should leave it at the value t.
  4002. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4003. :group 'org-archive
  4004. :group 'org-agenda-skip
  4005. :type 'boolean)
  4006. (defcustom org-columns-skip-archived-trees t
  4007. "Non-nil means ignore archived trees when creating column view."
  4008. :group 'org-archive
  4009. :group 'org-properties
  4010. :type 'boolean)
  4011. (defcustom org-cycle-open-archived-trees nil
  4012. "Non-nil means `org-cycle' will open archived trees.
  4013. An archived tree is a tree marked with the tag ARCHIVE.
  4014. When nil, archived trees will stay folded. You can still open them with
  4015. normal outline commands like `show-all', but not with the cycling commands."
  4016. :group 'org-archive
  4017. :group 'org-cycle
  4018. :type 'boolean)
  4019. (defcustom org-sparse-tree-open-archived-trees nil
  4020. "Non-nil means sparse tree construction shows matches in archived trees.
  4021. When nil, matches in these trees are highlighted, but the trees are kept in
  4022. collapsed state."
  4023. :group 'org-archive
  4024. :group 'org-sparse-trees
  4025. :type 'boolean)
  4026. (defcustom org-sparse-tree-default-date-type nil
  4027. "The default date type when building a sparse tree.
  4028. When this is nil, a date is a scheduled or a deadline timestamp.
  4029. Otherwise, these types are allowed:
  4030. all: all timestamps
  4031. active: only active timestamps (<...>)
  4032. inactive: only inactive timestamps ([...])
  4033. scheduled: only scheduled timestamps
  4034. deadline: only deadline timestamps"
  4035. :type '(choice (const :tag "Scheduled or deadline" nil)
  4036. (const :tag "All timestamps" all)
  4037. (const :tag "Only active timestamps" active)
  4038. (const :tag "Only inactive timestamps" inactive)
  4039. (const :tag "Only scheduled timestamps" scheduled)
  4040. (const :tag "Only deadline timestamps" deadline)
  4041. (const :tag "Only closed timestamps" closed))
  4042. :version "26.1"
  4043. :package-version '(Org . "8.3")
  4044. :group 'org-sparse-trees)
  4045. (defun org-cycle-hide-archived-subtrees (state)
  4046. "Re-hide all archived subtrees after a visibility state change."
  4047. (when (and (not org-cycle-open-archived-trees)
  4048. (not (memq state '(overview folded))))
  4049. (save-excursion
  4050. (let* ((globalp (memq state '(contents all)))
  4051. (beg (if globalp (point-min) (point)))
  4052. (end (if globalp (point-max) (org-end-of-subtree t))))
  4053. (org-hide-archived-subtrees beg end)
  4054. (goto-char beg)
  4055. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4056. (message "%s" (substitute-command-keys
  4057. "Subtree is archived and stays closed. Use \
  4058. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4059. (defun org-force-cycle-archived ()
  4060. "Cycle subtree even if it is archived."
  4061. (interactive)
  4062. (setq this-command 'org-cycle)
  4063. (let ((org-cycle-open-archived-trees t))
  4064. (call-interactively 'org-cycle)))
  4065. (defun org-hide-archived-subtrees (beg end)
  4066. "Re-hide all archived subtrees after a visibility state change."
  4067. (org-with-wide-buffer
  4068. (let ((case-fold-search nil)
  4069. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4070. (goto-char beg)
  4071. ;; Include headline point is currently on.
  4072. (beginning-of-line)
  4073. (while (and (< (point) end) (re-search-forward re end t))
  4074. (when (member org-archive-tag (org-get-tags))
  4075. (org-flag-subtree t)
  4076. (org-end-of-subtree t))))))
  4077. (declare-function outline-end-of-heading "outline" ())
  4078. (declare-function outline-flag-region "outline" (from to flag))
  4079. (defun org-flag-subtree (flag)
  4080. (save-excursion
  4081. (org-back-to-heading t)
  4082. (outline-end-of-heading)
  4083. (outline-flag-region (point)
  4084. (progn (org-end-of-subtree t) (point))
  4085. flag)))
  4086. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4087. ;; Declare Column View Code
  4088. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4089. (declare-function org-columns-compute "org-colview" (property))
  4090. ;; Declare ID code
  4091. (declare-function org-id-store-link "org-id")
  4092. (declare-function org-id-locations-load "org-id")
  4093. (declare-function org-id-locations-save "org-id")
  4094. (defvar org-id-track-globally)
  4095. ;;; Variables for pre-computed regular expressions, all buffer local
  4096. (defvar-local org-todo-regexp nil
  4097. "Matches any of the TODO state keywords.
  4098. Since TODO keywords are case-sensitive, `case-fold-search' is
  4099. expected to be bound to nil when matching against this regexp.")
  4100. (defvar-local org-not-done-regexp nil
  4101. "Matches any of the TODO state keywords except the last one.
  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-heading-regexp nil
  4105. "Matches a TODO headline that is not done.
  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-todo-line-regexp nil
  4109. "Matches a headline and puts TODO state into group 2 if present.
  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-complex-heading-regexp nil
  4113. "Matches a headline and puts everything into groups:
  4114. group 1: Stars
  4115. group 2: The TODO keyword, maybe
  4116. group 3: Priority cookie
  4117. group 4: True headline
  4118. group 5: Tags
  4119. Since TODO keywords are case-sensitive, `case-fold-search' is
  4120. expected to be bound to nil when matching against this regexp.")
  4121. (defvar-local org-complex-heading-regexp-format nil
  4122. "Printf format to make regexp to match an exact headline.
  4123. This regexp will match the headline of any node which has the
  4124. exact headline text that is put into the format, but may have any
  4125. TODO state, priority and tags.")
  4126. (defvar-local org-todo-line-tags-regexp nil
  4127. "Matches a headline and puts TODO state into group 2 if present.
  4128. Also put tags into group 4 if tags are present.")
  4129. (defconst org-plain-time-of-day-regexp
  4130. (concat
  4131. "\\(\\<[012]?[0-9]"
  4132. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4133. "\\(--?"
  4134. "\\(\\<[012]?[0-9]"
  4135. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4136. "\\)?")
  4137. "Regular expression to match a plain time or time range.
  4138. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4139. groups carry important information:
  4140. 0 the full match
  4141. 1 the first time, range or not
  4142. 8 the second time, if it is a range.")
  4143. (defconst org-plain-time-extension-regexp
  4144. (concat
  4145. "\\(\\<[012]?[0-9]"
  4146. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4147. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4148. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4149. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4150. groups carry important information:
  4151. 0 the full match
  4152. 7 hours of duration
  4153. 9 minutes of duration")
  4154. (defconst org-stamp-time-of-day-regexp
  4155. (concat
  4156. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4157. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4158. "\\(--?"
  4159. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4160. "Regular expression to match a timestamp time or time range.
  4161. After a match, the following groups carry important information:
  4162. 0 the full match
  4163. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4164. 2 the first time, range or not
  4165. 4 the second time, if it is a range.")
  4166. (defconst org-startup-options
  4167. '(("fold" org-startup-folded t)
  4168. ("overview" org-startup-folded t)
  4169. ("nofold" org-startup-folded nil)
  4170. ("showall" org-startup-folded nil)
  4171. ("showeverything" org-startup-folded showeverything)
  4172. ("content" org-startup-folded content)
  4173. ("indent" org-startup-indented t)
  4174. ("noindent" org-startup-indented nil)
  4175. ("hidestars" org-hide-leading-stars t)
  4176. ("showstars" org-hide-leading-stars nil)
  4177. ("odd" org-odd-levels-only t)
  4178. ("oddeven" org-odd-levels-only nil)
  4179. ("align" org-startup-align-all-tables t)
  4180. ("noalign" org-startup-align-all-tables nil)
  4181. ("inlineimages" org-startup-with-inline-images t)
  4182. ("noinlineimages" org-startup-with-inline-images nil)
  4183. ("latexpreview" org-startup-with-latex-preview t)
  4184. ("nolatexpreview" org-startup-with-latex-preview nil)
  4185. ("customtime" org-display-custom-times t)
  4186. ("logdone" org-log-done time)
  4187. ("lognotedone" org-log-done note)
  4188. ("nologdone" org-log-done nil)
  4189. ("lognoteclock-out" org-log-note-clock-out t)
  4190. ("nolognoteclock-out" org-log-note-clock-out nil)
  4191. ("logrepeat" org-log-repeat state)
  4192. ("lognoterepeat" org-log-repeat note)
  4193. ("logdrawer" org-log-into-drawer t)
  4194. ("nologdrawer" org-log-into-drawer nil)
  4195. ("logstatesreversed" org-log-states-order-reversed t)
  4196. ("nologstatesreversed" org-log-states-order-reversed nil)
  4197. ("nologrepeat" org-log-repeat nil)
  4198. ("logreschedule" org-log-reschedule time)
  4199. ("lognotereschedule" org-log-reschedule note)
  4200. ("nologreschedule" org-log-reschedule nil)
  4201. ("logredeadline" org-log-redeadline time)
  4202. ("lognoteredeadline" org-log-redeadline note)
  4203. ("nologredeadline" org-log-redeadline nil)
  4204. ("logrefile" org-log-refile time)
  4205. ("lognoterefile" org-log-refile note)
  4206. ("nologrefile" org-log-refile nil)
  4207. ("fninline" org-footnote-define-inline t)
  4208. ("nofninline" org-footnote-define-inline nil)
  4209. ("fnlocal" org-footnote-section nil)
  4210. ("fnauto" org-footnote-auto-label t)
  4211. ("fnprompt" org-footnote-auto-label nil)
  4212. ("fnconfirm" org-footnote-auto-label confirm)
  4213. ("fnplain" org-footnote-auto-label plain)
  4214. ("fnadjust" org-footnote-auto-adjust t)
  4215. ("nofnadjust" org-footnote-auto-adjust nil)
  4216. ("constcgs" constants-unit-system cgs)
  4217. ("constSI" constants-unit-system SI)
  4218. ("noptag" org-tag-persistent-alist nil)
  4219. ("hideblocks" org-hide-block-startup t)
  4220. ("nohideblocks" org-hide-block-startup nil)
  4221. ("beamer" org-startup-with-beamer-mode t)
  4222. ("entitiespretty" org-pretty-entities t)
  4223. ("entitiesplain" org-pretty-entities nil))
  4224. "Variable associated with STARTUP options for org-mode.
  4225. Each element is a list of three items: the startup options (as written
  4226. in the #+STARTUP line), the corresponding variable, and the value to set
  4227. this variable to if the option is found. An optional forth element PUSH
  4228. means to push this value onto the list in the variable.")
  4229. (defcustom org-group-tags t
  4230. "When non-nil (the default), use group tags.
  4231. This can be turned on/off through `org-toggle-tags-groups'."
  4232. :group 'org-tags
  4233. :group 'org-startup
  4234. :type 'boolean)
  4235. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4236. (defun org-toggle-tags-groups ()
  4237. "Toggle support for group tags.
  4238. Support for group tags is controlled by the option
  4239. `org-group-tags', which is non-nil by default."
  4240. (interactive)
  4241. (setq org-group-tags (not org-group-tags))
  4242. (cond ((and (derived-mode-p 'org-agenda-mode)
  4243. org-group-tags)
  4244. (org-agenda-redo))
  4245. ((derived-mode-p 'org-mode)
  4246. (let ((org-inhibit-startup t)) (org-mode))))
  4247. (message "Groups tags support has been turned %s"
  4248. (if org-group-tags "on" "off")))
  4249. (defun org-set-regexps-and-options (&optional tags-only)
  4250. "Precompute regular expressions used in the current buffer.
  4251. When optional argument TAGS-ONLY is non-nil, only compute tags
  4252. related expressions."
  4253. (when (derived-mode-p 'org-mode)
  4254. (let ((alist (org--setup-collect-keywords
  4255. (org-make-options-regexp
  4256. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4257. (and (not tags-only)
  4258. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4259. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4260. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4261. ;; Startup options. Get this early since it does change
  4262. ;; behavior for other options (e.g., tags).
  4263. (let ((startup (cdr (assq 'startup alist))))
  4264. (dolist (option startup)
  4265. (let ((entry (assoc-string option org-startup-options t)))
  4266. (when entry
  4267. (let ((var (nth 1 entry))
  4268. (val (nth 2 entry)))
  4269. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4270. (unless (listp (symbol-value var))
  4271. (set (make-local-variable var) nil))
  4272. (add-to-list var val)))))))
  4273. (setq-local org-file-tags
  4274. (mapcar #'org-add-prop-inherited
  4275. (cdr (assq 'filetags alist))))
  4276. (setq org-current-tag-alist
  4277. (append org-tag-persistent-alist
  4278. (let ((tags (cdr (assq 'tags alist))))
  4279. (if tags (org-tag-string-to-alist tags)
  4280. org-tag-alist))))
  4281. (setq org-tag-groups-alist
  4282. (org-tag-alist-to-groups org-current-tag-alist))
  4283. (unless tags-only
  4284. ;; File properties.
  4285. (setq-local org-file-properties (cdr (assq 'property alist)))
  4286. ;; Archive location.
  4287. (let ((archive (cdr (assq 'archive alist))))
  4288. (when archive (setq-local org-archive-location archive)))
  4289. ;; Category.
  4290. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4291. (when cat
  4292. (setq-local org-category (intern cat))
  4293. (setq-local org-file-properties
  4294. (org--update-property-plist
  4295. "CATEGORY" cat org-file-properties))))
  4296. ;; Columns.
  4297. (let ((column (cdr (assq 'columns alist))))
  4298. (when column (setq-local org-columns-default-format column)))
  4299. ;; Constants.
  4300. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4301. ;; Link abbreviations.
  4302. (let ((links (cdr (assq 'link alist))))
  4303. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4304. ;; Priorities.
  4305. (let ((priorities (cdr (assq 'priorities alist))))
  4306. (when priorities
  4307. (setq-local org-highest-priority (nth 0 priorities))
  4308. (setq-local org-lowest-priority (nth 1 priorities))
  4309. (setq-local org-default-priority (nth 2 priorities))))
  4310. ;; Scripts.
  4311. (let ((scripts (assq 'scripts alist)))
  4312. (when scripts
  4313. (setq-local org-use-sub-superscripts (cdr scripts))))
  4314. ;; TODO keywords.
  4315. (setq-local org-todo-kwd-alist nil)
  4316. (setq-local org-todo-key-alist nil)
  4317. (setq-local org-todo-key-trigger nil)
  4318. (setq-local org-todo-keywords-1 nil)
  4319. (setq-local org-done-keywords nil)
  4320. (setq-local org-todo-heads nil)
  4321. (setq-local org-todo-sets nil)
  4322. (setq-local org-todo-log-states nil)
  4323. (let ((todo-sequences
  4324. (or (nreverse (cdr (assq 'todo alist)))
  4325. (let ((d (default-value 'org-todo-keywords)))
  4326. (if (not (stringp (car d))) d
  4327. ;; XXX: Backward compatibility code.
  4328. (list (cons org-todo-interpretation d)))))))
  4329. (dolist (sequence todo-sequences)
  4330. (let* ((sequence (or (run-hook-with-args-until-success
  4331. 'org-todo-setup-filter-hook sequence)
  4332. sequence))
  4333. (sequence-type (car sequence))
  4334. (keywords (cdr sequence))
  4335. (sep (member "|" keywords))
  4336. names alist)
  4337. (dolist (k (remove "|" keywords))
  4338. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4339. k)
  4340. (error "Invalid TODO keyword %s" k))
  4341. (let ((name (match-string 1 k))
  4342. (key (match-string 2 k))
  4343. (log (org-extract-log-state-settings k)))
  4344. (push name names)
  4345. (push (cons name (and key (string-to-char key))) alist)
  4346. (when log (push log org-todo-log-states))))
  4347. (let* ((names (nreverse names))
  4348. (done (if sep (org-remove-keyword-keys (cdr sep))
  4349. (last names)))
  4350. (head (car names))
  4351. (tail (list sequence-type head (car done) (org-last done))))
  4352. (add-to-list 'org-todo-heads head 'append)
  4353. (push names org-todo-sets)
  4354. (setq org-done-keywords (append org-done-keywords done nil))
  4355. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4356. (setq org-todo-key-alist
  4357. (append org-todo-key-alist
  4358. (and alist
  4359. (append '((:startgroup))
  4360. (nreverse alist)
  4361. '((:endgroup))))))
  4362. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4363. (setq org-todo-sets (nreverse org-todo-sets)
  4364. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4365. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4366. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4367. ;; Compute the regular expressions and other local variables.
  4368. ;; Using `org-outline-regexp-bol' would complicate them much,
  4369. ;; because of the fixed white space at the end of that string.
  4370. (unless org-done-keywords
  4371. (setq org-done-keywords
  4372. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4373. (setq org-not-done-keywords
  4374. (org-delete-all org-done-keywords
  4375. (copy-sequence org-todo-keywords-1))
  4376. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4377. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4378. org-not-done-heading-regexp
  4379. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4380. org-todo-line-regexp
  4381. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4382. org-complex-heading-regexp
  4383. (concat "^\\(\\*+\\)"
  4384. "\\(?: +" org-todo-regexp "\\)?"
  4385. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4386. "\\(?: +\\(.*?\\)\\)??"
  4387. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4388. "[ \t]*$")
  4389. org-complex-heading-regexp-format
  4390. (concat "^\\(\\*+\\)"
  4391. "\\(?: +" org-todo-regexp "\\)?"
  4392. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4393. "\\(?: +"
  4394. ;; Stats cookies can be stuck to body.
  4395. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4396. "\\(%s\\)"
  4397. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4398. "\\)"
  4399. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4400. "[ \t]*$")
  4401. org-todo-line-tags-regexp
  4402. (concat "^\\(\\*+\\)"
  4403. "\\(?: +" org-todo-regexp "\\)?"
  4404. "\\(?: +\\(.*?\\)\\)??"
  4405. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4406. "[ \t]*$"))
  4407. (org-compute-latex-and-related-regexp)))))
  4408. (defun org--setup-collect-keywords (regexp &optional files alist)
  4409. "Return setup keywords values as an alist.
  4410. REGEXP matches a subset of setup keywords. FILES is a list of
  4411. file names already visited. It is used to avoid circular setup
  4412. files. ALIST, when non-nil, is the alist computed so far.
  4413. Return value contains the following keys: `archive', `category',
  4414. `columns', `constants', `filetags', `link', `priorities',
  4415. `property', `scripts', `startup', `tags' and `todo'."
  4416. (org-with-wide-buffer
  4417. (goto-char (point-min))
  4418. (let ((case-fold-search t))
  4419. (while (re-search-forward regexp nil t)
  4420. (let ((element (org-element-at-point)))
  4421. (when (eq (org-element-type element) 'keyword)
  4422. (let ((key (org-element-property :key element))
  4423. (value (org-element-property :value element)))
  4424. (cond
  4425. ((equal key "ARCHIVE")
  4426. (when (org-string-nw-p value)
  4427. (push (cons 'archive value) alist)))
  4428. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4429. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4430. ((equal key "CONSTANTS")
  4431. (let* ((constants (assq 'constants alist))
  4432. (store (cdr constants)))
  4433. (dolist (pair (org-split-string value))
  4434. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4435. pair)
  4436. (let* ((name (match-string 1 pair))
  4437. (value (match-string 2 pair))
  4438. (old (assoc name store)))
  4439. (if old (setcdr old value)
  4440. (push (cons name value) store)))))
  4441. (if constants (setcdr constants store)
  4442. (push (cons 'constants store) alist))))
  4443. ((equal key "FILETAGS")
  4444. (when (org-string-nw-p value)
  4445. (let ((old (assq 'filetags alist))
  4446. (new (apply #'nconc
  4447. (mapcar (lambda (x) (org-split-string x ":"))
  4448. (org-split-string value)))))
  4449. (if old (setcdr old (append new (cdr old)))
  4450. (push (cons 'filetags new) alist)))))
  4451. ((equal key "LINK")
  4452. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4453. (let ((links (assq 'link alist))
  4454. (pair (cons (match-string-no-properties 1 value)
  4455. (match-string-no-properties 2 value))))
  4456. (if links (push pair (cdr links))
  4457. (push (list 'link pair) alist)))))
  4458. ((equal key "OPTIONS")
  4459. (when (and (org-string-nw-p value)
  4460. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4461. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4462. ((equal key "PRIORITIES")
  4463. (push (cons 'priorities
  4464. (let ((prio (org-split-string value)))
  4465. (if (< (length prio) 3) '(?A ?C ?B)
  4466. (mapcar #'string-to-char prio))))
  4467. alist))
  4468. ((equal key "PROPERTY")
  4469. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4470. (let* ((property (assq 'property alist))
  4471. (value (org--update-property-plist
  4472. (match-string-no-properties 1 value)
  4473. (match-string-no-properties 2 value)
  4474. (cdr property))))
  4475. (if property (setcdr property value)
  4476. (push (cons 'property value) alist)))))
  4477. ((equal key "STARTUP")
  4478. (let ((startup (assq 'startup alist)))
  4479. (if startup
  4480. (setcdr startup
  4481. (append (cdr startup) (org-split-string value)))
  4482. (push (cons 'startup (org-split-string value)) alist))))
  4483. ((equal key "TAGS")
  4484. (let ((tag-cell (assq 'tags alist)))
  4485. (if tag-cell
  4486. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4487. (push (cons 'tags value) alist))))
  4488. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4489. (let ((todo (assq 'todo alist))
  4490. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4491. (org-split-string value))))
  4492. (if todo (push value (cdr todo))
  4493. (push (list 'todo value) alist))))
  4494. ((equal key "SETUPFILE")
  4495. (unless buffer-read-only ; Do not check in Gnus messages.
  4496. (let ((f (and (org-string-nw-p value)
  4497. (expand-file-name
  4498. (org-unbracket-string "\"" "\"" value)))))
  4499. (when (and f (file-readable-p f) (not (member f files)))
  4500. (with-temp-buffer
  4501. (setq default-directory (file-name-directory f))
  4502. (insert-file-contents f)
  4503. (setq alist
  4504. ;; Fake Org mode to benefit from cache
  4505. ;; without recurring needlessly.
  4506. (let ((major-mode 'org-mode))
  4507. (org--setup-collect-keywords
  4508. regexp (cons f files) alist)))))))))))))))
  4509. alist)
  4510. (defun org-tag-string-to-alist (s)
  4511. "Return tag alist associated to string S.
  4512. S is a value for TAGS keyword or produced with
  4513. `org-tag-alist-to-string'. Return value is an alist suitable for
  4514. `org-tag-alist' or `org-tag-persistent-alist'."
  4515. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4516. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4517. "\\|{.+?}\\)" ; regular expression
  4518. "\\(?:(\\(.\\))\\)?\\'"))
  4519. alist group-flag)
  4520. (dolist (tokens lines (cdr (nreverse alist)))
  4521. (push '(:newline) alist)
  4522. (while tokens
  4523. (let ((token (pop tokens)))
  4524. (pcase token
  4525. ("{"
  4526. (push '(:startgroup) alist)
  4527. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4528. ("}"
  4529. (push '(:endgroup) alist)
  4530. (setq group-flag nil))
  4531. ("["
  4532. (push '(:startgrouptag) alist)
  4533. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4534. ("]"
  4535. (push '(:endgrouptag) alist)
  4536. (setq group-flag nil))
  4537. (":"
  4538. (push '(:grouptags) alist))
  4539. ((guard (string-match tag-re token))
  4540. (let ((tag (match-string 1 token))
  4541. (key (and (match-beginning 2)
  4542. (string-to-char (match-string 2 token)))))
  4543. ;; Push all tags in groups, no matter if they already
  4544. ;; appear somewhere else in the list.
  4545. (when (or group-flag (not (assoc tag alist)))
  4546. (push (cons tag key) alist))))))))))
  4547. (defun org-tag-alist-to-string (alist &optional skip-key)
  4548. "Return tag string associated to ALIST.
  4549. ALIST is an alist, as defined in `org-tag-alist' or
  4550. `org-tag-persistent-alist', or produced with
  4551. `org-tag-string-to-alist'.
  4552. Return value is a string suitable as a value for \"TAGS\"
  4553. keyword.
  4554. When optional argument SKIP-KEY is non-nil, skip selection keys
  4555. next to tags."
  4556. (mapconcat (lambda (token)
  4557. (pcase token
  4558. (`(:startgroup) "{")
  4559. (`(:endgroup) "}")
  4560. (`(:startgrouptag) "[")
  4561. (`(:endgrouptag) "]")
  4562. (`(:grouptags) ":")
  4563. (`(:newline) "\\n")
  4564. ((and
  4565. (guard (not skip-key))
  4566. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4567. (format "%s(%c)" tag key))
  4568. (`(,(and tag (pred stringp)) . ,_) tag)
  4569. (_ (user-error "Invalid tag token: %S" token))))
  4570. alist
  4571. " "))
  4572. (defun org-tag-alist-to-groups (alist)
  4573. "Return group alist from tag ALIST.
  4574. ALIST is an alist, as defined in `org-tag-alist' or
  4575. `org-tag-persistent-alist', or produced with
  4576. `org-tag-string-to-alist'. Return value is an alist following
  4577. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4578. a string, summarizing TAGS, as a list of strings."
  4579. (let (groups group-status current-group)
  4580. (dolist (token alist (nreverse groups))
  4581. (pcase token
  4582. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4583. (`(,(or :endgroup :endgrouptag))
  4584. (when (eq group-status 'append)
  4585. (push (nreverse current-group) groups))
  4586. (setq group-status nil))
  4587. (`(:grouptags) (setq group-status 'append))
  4588. ((and `(,tag . ,_) (guard group-status))
  4589. (if (eq group-status 'append) (push tag current-group)
  4590. (setq current-group (list tag))))
  4591. (_ nil)))))
  4592. (defun org-file-contents (file &optional noerror)
  4593. "Return the contents of FILE, as a string."
  4594. (if (and file (file-readable-p file))
  4595. (with-temp-buffer
  4596. (insert-file-contents file)
  4597. (buffer-string))
  4598. (funcall (if noerror 'message 'error)
  4599. "Cannot read file \"%s\"%s"
  4600. file
  4601. (let ((from (buffer-file-name (buffer-base-buffer))))
  4602. (if from (concat " (referenced in file \"" from "\")") "")))))
  4603. (defun org-extract-log-state-settings (x)
  4604. "Extract the log state setting from a TODO keyword string.
  4605. This will extract info from a string like \"WAIT(w@/!)\"."
  4606. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4607. (let ((kw (match-string 1 x))
  4608. (log1 (and (match-end 3) (match-string 3 x)))
  4609. (log2 (and (match-end 4) (match-string 4 x))))
  4610. (and (or log1 log2)
  4611. (list kw
  4612. (and log1 (if (equal log1 "!") 'time 'note))
  4613. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4614. (defun org-remove-keyword-keys (list)
  4615. "Remove a pair of parenthesis at the end of each string in LIST."
  4616. (mapcar (lambda (x)
  4617. (if (string-match "(.*)$" x)
  4618. (substring x 0 (match-beginning 0))
  4619. x))
  4620. list))
  4621. (defun org-assign-fast-keys (alist)
  4622. "Assign fast keys to a keyword-key alist.
  4623. Respect keys that are already there."
  4624. (let (new e (alt ?0))
  4625. (while (setq e (pop alist))
  4626. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4627. (cdr e)) ;; Key already assigned.
  4628. (push e new)
  4629. (let ((clist (string-to-list (downcase (car e))))
  4630. (used (append new alist)))
  4631. (when (= (car clist) ?@)
  4632. (pop clist))
  4633. (while (and clist (rassoc (car clist) used))
  4634. (pop clist))
  4635. (unless clist
  4636. (while (rassoc alt used)
  4637. (cl-incf alt)))
  4638. (push (cons (car e) (or (car clist) alt)) new))))
  4639. (nreverse new)))
  4640. ;;; Some variables used in various places
  4641. (defvar org-window-configuration nil
  4642. "Used in various places to store a window configuration.")
  4643. (defvar org-selected-window nil
  4644. "Used in various places to store a window configuration.")
  4645. (defvar org-finish-function nil
  4646. "Function to be called when `C-c C-c' is used.
  4647. This is for getting out of special buffers like capture.")
  4648. (defvar org-last-state)
  4649. ;; Defined somewhere in this file, but used before definition.
  4650. (defvar org-entities) ;; defined in org-entities.el
  4651. (defvar org-struct-menu)
  4652. (defvar org-org-menu)
  4653. (defvar org-tbl-menu)
  4654. ;;;; Define the Org mode
  4655. ;; We use a before-change function to check if a table might need
  4656. ;; an update.
  4657. (defvar org-table-may-need-update t
  4658. "Indicates that a table might need an update.
  4659. This variable is set by `org-before-change-function'.
  4660. `org-table-align' sets it back to nil.")
  4661. (defun org-before-change-function (_beg _end)
  4662. "Every change indicates that a table might need an update."
  4663. (setq org-table-may-need-update t))
  4664. (defvar org-mode-map)
  4665. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4666. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4667. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4668. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4669. (defvar org-table-buffer-is-an nil)
  4670. (defvar bidi-paragraph-direction)
  4671. (defvar buffer-face-mode-face)
  4672. (require 'outline)
  4673. ;; Other stuff we need.
  4674. (require 'time-date)
  4675. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4676. (require 'easymenu)
  4677. (autoload 'easy-menu-add "easymenu")
  4678. (require 'overlay)
  4679. ;; (require 'org-macs) moved higher up in the file before it is first used
  4680. (require 'org-entities)
  4681. ;; (require 'org-compat) moved higher up in the file before it is first used
  4682. (require 'org-faces)
  4683. (require 'org-list)
  4684. (require 'org-pcomplete)
  4685. (require 'org-src)
  4686. (require 'org-footnote)
  4687. (require 'org-macro)
  4688. ;; babel
  4689. (require 'ob)
  4690. ;;;###autoload
  4691. (define-derived-mode org-mode outline-mode "Org"
  4692. "Outline-based notes management and organizer, alias
  4693. \"Carsten's outline-mode for keeping track of everything.\"
  4694. Org mode develops organizational tasks around a NOTES file which
  4695. contains information about projects as plain text. Org mode is
  4696. implemented on top of Outline mode, which is ideal to keep the content
  4697. of large files well structured. It supports ToDo items, deadlines and
  4698. time stamps, which magically appear in the diary listing of the Emacs
  4699. calendar. Tables are easily created with a built-in table editor.
  4700. Plain text URL-like links connect to websites, emails (VM), Usenet
  4701. messages (Gnus), BBDB entries, and any files related to the project.
  4702. For printing and sharing of notes, an Org file (or a part of it)
  4703. can be exported as a structured ASCII or HTML file.
  4704. The following commands are available:
  4705. \\{org-mode-map}"
  4706. ;; Get rid of Outline menus, they are not needed
  4707. ;; Need to do this here because define-derived-mode sets up
  4708. ;; the keymap so late. Still, it is a waste to call this each time
  4709. ;; we switch another buffer into Org mode.
  4710. (define-key org-mode-map [menu-bar headings] 'undefined)
  4711. (define-key org-mode-map [menu-bar hide] 'undefined)
  4712. (define-key org-mode-map [menu-bar show] 'undefined)
  4713. (org-load-modules-maybe)
  4714. (org-install-agenda-files-menu)
  4715. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4716. (add-to-invisibility-spec '(org-cwidth))
  4717. (add-to-invisibility-spec '(org-hide-block . t))
  4718. (setq-local outline-regexp org-outline-regexp)
  4719. (setq-local outline-level 'org-outline-level)
  4720. (setq bidi-paragraph-direction 'left-to-right)
  4721. (when (and org-ellipsis
  4722. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4723. (fboundp 'make-glyph-code))
  4724. (unless org-display-table
  4725. (setq org-display-table (make-display-table)))
  4726. (set-display-table-slot
  4727. org-display-table 4
  4728. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4729. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4730. (setq buffer-display-table org-display-table))
  4731. (org-set-regexps-and-options)
  4732. (org-set-font-lock-defaults)
  4733. (when (and org-tag-faces (not org-tags-special-faces-re))
  4734. ;; tag faces set outside customize.... force initialization.
  4735. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4736. ;; Calc embedded
  4737. (setq-local calc-embedded-open-mode "# ")
  4738. ;; Modify a few syntax entries
  4739. (modify-syntax-entry ?@ "w")
  4740. (modify-syntax-entry ?\" "\"")
  4741. (modify-syntax-entry ?\\ "_")
  4742. (modify-syntax-entry ?~ "_")
  4743. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4744. ;; Activate before-change-function
  4745. (setq-local org-table-may-need-update t)
  4746. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4747. ;; Check for running clock before killing a buffer
  4748. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4749. ;; Initialize macros templates.
  4750. (org-macro-initialize-templates)
  4751. ;; Initialize radio targets.
  4752. (org-update-radio-target-regexp)
  4753. ;; Indentation.
  4754. (setq-local indent-line-function 'org-indent-line)
  4755. (setq-local indent-region-function 'org-indent-region)
  4756. ;; Filling and auto-filling.
  4757. (org-setup-filling)
  4758. ;; Comments.
  4759. (org-setup-comments-handling)
  4760. ;; Initialize cache.
  4761. (org-element-cache-reset)
  4762. ;; Beginning/end of defun
  4763. (setq-local beginning-of-defun-function 'org-backward-element)
  4764. (setq-local end-of-defun-function
  4765. (lambda ()
  4766. (if (not (org-at-heading-p))
  4767. (org-forward-element)
  4768. (org-forward-element)
  4769. (forward-char -1))))
  4770. ;; Next error for sparse trees
  4771. (setq-local next-error-function 'org-occur-next-match)
  4772. ;; Make sure dependence stuff works reliably, even for users who set it
  4773. ;; too late :-(
  4774. (if org-enforce-todo-dependencies
  4775. (add-hook 'org-blocker-hook
  4776. 'org-block-todo-from-children-or-siblings-or-parent)
  4777. (remove-hook 'org-blocker-hook
  4778. 'org-block-todo-from-children-or-siblings-or-parent))
  4779. (if org-enforce-todo-checkbox-dependencies
  4780. (add-hook 'org-blocker-hook
  4781. 'org-block-todo-from-checkboxes)
  4782. (remove-hook 'org-blocker-hook
  4783. 'org-block-todo-from-checkboxes))
  4784. ;; Align options lines
  4785. (setq-local
  4786. align-mode-rules-list
  4787. '((org-in-buffer-settings
  4788. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4789. (modes . '(org-mode)))))
  4790. ;; Imenu
  4791. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4792. ;; Make isearch reveal context
  4793. (setq-local outline-isearch-open-invisible-function
  4794. (lambda (&rest _) (org-show-context 'isearch)))
  4795. ;; Setup the pcomplete hooks
  4796. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4797. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4798. (setq-local pcomplete-default-completion-function 'ignore)
  4799. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4800. (setq-local pcomplete-termination-string "")
  4801. (setq-local buffer-face-mode-face 'org-default)
  4802. ;; If empty file that did not turn on Org mode automatically, make
  4803. ;; it to.
  4804. (when (and org-insert-mode-line-in-empty-file
  4805. (called-interactively-p 'any)
  4806. (= (point-min) (point-max)))
  4807. (insert "# -*- mode: org -*-\n\n"))
  4808. (unless org-inhibit-startup
  4809. (org-unmodified
  4810. (when org-startup-with-beamer-mode (org-beamer-mode))
  4811. (when org-startup-align-all-tables
  4812. (org-table-map-tables #'org-table-align t))
  4813. (when org-startup-with-inline-images (org-display-inline-images))
  4814. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4815. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4816. (when org-startup-truncated (setq truncate-lines t))
  4817. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4818. (org-refresh-effort-properties)))
  4819. ;; Try to set `org-hide' face correctly.
  4820. (let ((foreground (org-find-invisible-foreground)))
  4821. (when foreground
  4822. (set-face-foreground 'org-hide foreground))))
  4823. ;; Update `customize-package-emacs-version-alist'
  4824. (add-to-list 'customize-package-emacs-version-alist
  4825. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4826. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4827. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4828. ("9.0" . "26.1")))
  4829. (defvar org-mode-transpose-word-syntax-table
  4830. (let ((st (make-syntax-table text-mode-syntax-table)))
  4831. (dolist (c org-emphasis-alist st)
  4832. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4833. (when (fboundp 'abbrev-table-put)
  4834. (abbrev-table-put org-mode-abbrev-table
  4835. :parents (list text-mode-abbrev-table)))
  4836. (defun org-find-invisible-foreground ()
  4837. (let ((candidates (remove
  4838. "unspecified-bg"
  4839. (nconc
  4840. (list (face-background 'default)
  4841. (face-background 'org-default))
  4842. (mapcar
  4843. (lambda (alist)
  4844. (when (boundp alist)
  4845. (cdr (assq 'background-color (symbol-value alist)))))
  4846. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4847. (list (face-foreground 'org-hide))))))
  4848. (car (remove nil candidates))))
  4849. (defun org-current-time (&optional rounding-minutes past)
  4850. "Current time, possibly rounded to ROUNDING-MINUTES.
  4851. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4852. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4853. the rounding returns a past time."
  4854. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4855. (car org-time-stamp-rounding-minutes)))
  4856. (time (decode-time)) res)
  4857. (if (< r 1)
  4858. (current-time)
  4859. (setq res
  4860. (apply 'encode-time
  4861. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4862. (nthcdr 2 time))))
  4863. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4864. (seconds-to-time (- (float-time res) (* r 60)))
  4865. res))))
  4866. (defun org-today ()
  4867. "Return today date, considering `org-extend-today-until'."
  4868. (time-to-days
  4869. (time-subtract (current-time)
  4870. (list 0 (* 3600 org-extend-today-until) 0))))
  4871. ;;;; Font-Lock stuff, including the activators
  4872. (defvar org-mouse-map (make-sparse-keymap))
  4873. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4874. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4875. (when org-mouse-1-follows-link
  4876. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4877. (when org-tab-follows-link
  4878. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4879. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4880. (require 'font-lock)
  4881. (defconst org-non-link-chars "]\t\n\r<>")
  4882. (defvar org-link-types-re nil
  4883. "Matches a link that has a url-like prefix like \"http:\"")
  4884. (defvar org-link-re-with-space nil
  4885. "Matches a link with spaces, optional angular brackets around it.")
  4886. (defvar org-link-re-with-space2 nil
  4887. "Matches a link with spaces, optional angular brackets around it.")
  4888. (defvar org-link-re-with-space3 nil
  4889. "Matches a link with spaces, only for internal part in bracket links.")
  4890. (defvar org-angle-link-re nil
  4891. "Matches link with angular brackets, spaces are allowed.")
  4892. (defvar org-plain-link-re nil
  4893. "Matches plain link, without spaces.")
  4894. (defvar org-bracket-link-regexp nil
  4895. "Matches a link in double brackets.")
  4896. (defvar org-bracket-link-analytic-regexp nil
  4897. "Regular expression used to analyze links.
  4898. Here is what the match groups contain after a match:
  4899. 1: http:
  4900. 2: http
  4901. 3: path
  4902. 4: [desc]
  4903. 5: desc")
  4904. (defvar org-bracket-link-analytic-regexp++ nil
  4905. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4906. (defvar org-any-link-re nil
  4907. "Regular expression matching any link.")
  4908. (defconst org-match-sexp-depth 3
  4909. "Number of stacked braces for sub/superscript matching.")
  4910. (defun org-create-multibrace-regexp (left right n)
  4911. "Create a regular expression which will match a balanced sexp.
  4912. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4913. as single character strings.
  4914. The regexp returned will match the entire expression including the
  4915. delimiters. It will also define a single group which contains the
  4916. match except for the outermost delimiters. The maximum depth of
  4917. stacked delimiters is N. Escaping delimiters is not possible."
  4918. (let* ((nothing (concat "[^" left right "]*?"))
  4919. (or "\\|")
  4920. (re nothing)
  4921. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4922. (while (> n 1)
  4923. (setq n (1- n)
  4924. re (concat re or next)
  4925. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4926. (concat left "\\(" re "\\)" right)))
  4927. (defconst org-match-substring-regexp
  4928. (concat
  4929. "\\(\\S-\\)\\([_^]\\)\\("
  4930. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4931. "\\|"
  4932. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4933. "\\|"
  4934. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4935. "The regular expression matching a sub- or superscript.")
  4936. (defconst org-match-substring-with-braces-regexp
  4937. (concat
  4938. "\\(\\S-\\)\\([_^]\\)"
  4939. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4940. "The regular expression matching a sub- or superscript, forcing braces.")
  4941. (defun org-make-link-regexps ()
  4942. "Update the link regular expressions.
  4943. This should be called after the variable `org-link-parameters' has changed."
  4944. (let ((types-re (regexp-opt (org-link-types) t)))
  4945. (setq org-link-types-re
  4946. (concat "\\`" types-re ":")
  4947. org-link-re-with-space
  4948. (concat "<?" types-re ":"
  4949. "\\([^" org-non-link-chars " ]"
  4950. "[^" org-non-link-chars "]*"
  4951. "[^" org-non-link-chars " ]\\)>?")
  4952. org-link-re-with-space2
  4953. (concat "<?" types-re ":"
  4954. "\\([^" org-non-link-chars " ]"
  4955. "[^\t\n\r]*"
  4956. "[^" org-non-link-chars " ]\\)>?")
  4957. org-link-re-with-space3
  4958. (concat "<?" types-re ":"
  4959. "\\([^" org-non-link-chars " ]"
  4960. "[^\t\n\r]*\\)")
  4961. org-angle-link-re
  4962. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4963. types-re)
  4964. org-plain-link-re
  4965. (concat
  4966. "\\<" types-re ":"
  4967. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4968. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4969. org-bracket-link-regexp
  4970. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4971. org-bracket-link-analytic-regexp
  4972. (concat
  4973. "\\[\\["
  4974. "\\(" types-re ":\\)?"
  4975. "\\([^]]+\\)"
  4976. "\\]"
  4977. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4978. "\\]")
  4979. org-bracket-link-analytic-regexp++
  4980. (concat
  4981. "\\[\\["
  4982. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4983. "\\([^]]+\\)"
  4984. "\\]"
  4985. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4986. "\\]")
  4987. org-any-link-re
  4988. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4989. org-angle-link-re "\\)\\|\\("
  4990. org-plain-link-re "\\)"))))
  4991. (org-make-link-regexps)
  4992. (defvar org-emph-face nil)
  4993. (defun org-do-emphasis-faces (limit)
  4994. "Run through the buffer and emphasize strings."
  4995. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4996. (car org-emphasis-regexp-components))))
  4997. (catch :exit
  4998. (while (re-search-forward quick-re limit t)
  4999. (let* ((marker (match-string 2))
  5000. (verbatim? (member marker '("~" "="))))
  5001. (when (save-excursion
  5002. (goto-char (match-beginning 0))
  5003. ;; Do not match headline stars. Do not consider
  5004. ;; stars of a headline as closing marker for bold
  5005. ;; markup either.
  5006. (and (not (looking-at-p org-outline-regexp-bol))
  5007. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5008. (not (string-match-p
  5009. (concat org-outline-regexp-bol "\\'")
  5010. (match-string 0)))))
  5011. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5012. (font-lock-prepend-text-property
  5013. (match-beginning 2) (match-end 2) 'face face)
  5014. (when verbatim?
  5015. (org-remove-flyspell-overlays-in
  5016. (match-beginning 0) (match-end 0)))
  5017. (add-text-properties (match-beginning 2) (match-end 2)
  5018. '(font-lock-multiline t org-emphasis t))
  5019. (when org-hide-emphasis-markers
  5020. (add-text-properties (match-end 4) (match-beginning 5)
  5021. '(invisible org-link))
  5022. (add-text-properties (match-beginning 3) (match-end 3)
  5023. '(invisible org-link)))
  5024. (throw :exit t))))))))
  5025. (defun org-emphasize (&optional char)
  5026. "Insert or change an emphasis, i.e. a font like bold or italic.
  5027. If there is an active region, change that region to a new emphasis.
  5028. If there is no region, just insert the marker characters and position
  5029. the cursor between them.
  5030. CHAR should be the marker character. If it is a space, it means to
  5031. remove the emphasis of the selected region.
  5032. If CHAR is not given (for example in an interactive call) it will be
  5033. prompted for."
  5034. (interactive)
  5035. (let ((erc org-emphasis-regexp-components)
  5036. (string "") beg end move s)
  5037. (if (org-region-active-p)
  5038. (setq beg (region-beginning)
  5039. end (region-end)
  5040. string (buffer-substring beg end))
  5041. (setq move t))
  5042. (unless char
  5043. (message "Emphasis marker or tag: [%s]"
  5044. (mapconcat #'car org-emphasis-alist ""))
  5045. (setq char (read-char-exclusive)))
  5046. (if (equal char ?\s)
  5047. (setq s ""
  5048. move nil)
  5049. (unless (assoc (char-to-string char) org-emphasis-alist)
  5050. (user-error "No such emphasis marker: \"%c\"" char))
  5051. (setq s (char-to-string char)))
  5052. (while (and (> (length string) 1)
  5053. (equal (substring string 0 1) (substring string -1))
  5054. (assoc (substring string 0 1) org-emphasis-alist))
  5055. (setq string (substring string 1 -1)))
  5056. (setq string (concat s string s))
  5057. (when beg (delete-region beg end))
  5058. (unless (or (bolp)
  5059. (string-match (concat "[" (nth 0 erc) "\n]")
  5060. (char-to-string (char-before (point)))))
  5061. (insert " "))
  5062. (unless (or (eobp)
  5063. (string-match (concat "[" (nth 1 erc) "\n]")
  5064. (char-to-string (char-after (point)))))
  5065. (insert " ") (backward-char 1))
  5066. (insert string)
  5067. (and move (backward-char 1))))
  5068. (defconst org-nonsticky-props
  5069. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5070. (defsubst org-rear-nonsticky-at (pos)
  5071. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5072. (defun org-activate-links (limit)
  5073. "Add link properties to links.
  5074. This includes angle, plain, and bracket links."
  5075. (catch :exit
  5076. (while (re-search-forward org-any-link-re limit t)
  5077. (let* ((start (match-beginning 0))
  5078. (end (match-end 0))
  5079. (type (cond ((eq ?< (char-after start)) 'angle)
  5080. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5081. (t 'plain))))
  5082. (when (and (memq type org-highlight-links)
  5083. ;; Do not confuse plain links with tags.
  5084. (not (and (eq type 'plain)
  5085. (let ((face (get-text-property
  5086. (max (1- start) (point-min)) 'face)))
  5087. (if (consp face) (memq 'org-tag face)
  5088. (eq 'org-tag face))))))
  5089. (let* ((link-object (save-excursion
  5090. (goto-char start)
  5091. (save-match-data (org-element-link-parser))))
  5092. (link (org-element-property :raw-link link-object))
  5093. (path (org-element-property :path link-object))
  5094. (properties ;for link's visible part
  5095. (list
  5096. 'face (pcase (org-link-get-parameter type :face)
  5097. ((and (pred functionp) face) (funcall face path))
  5098. ((and (pred facep) face) face)
  5099. ((and (pred consp) face) face) ;anonymous
  5100. (_ 'org-link))
  5101. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5102. 'highlight)
  5103. 'keymap (or (org-link-get-parameter type :keymap)
  5104. org-mouse-map)
  5105. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5106. ((and (pred stringp) echo) echo)
  5107. ((and (pred functionp) echo) echo)
  5108. (_ (concat "LINK: " link)))
  5109. 'htmlize-link (pcase (org-link-get-parameter type
  5110. :htmlize-link)
  5111. ((and (pred functionp) f) (funcall f))
  5112. (_ `(:uri ,link)))
  5113. 'font-lock-multiline t)))
  5114. (org-remove-flyspell-overlays-in start end)
  5115. (org-rear-nonsticky-at end)
  5116. (if (not (eq 'bracket type))
  5117. (add-text-properties start end properties)
  5118. ;; Handle invisible parts in bracket links.
  5119. (remove-text-properties start end '(invisible nil))
  5120. (let ((hidden
  5121. (append `(invisible
  5122. ,(or (org-link-get-parameter type :display)
  5123. 'org-link))
  5124. properties))
  5125. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5126. (visible-end (or (match-end 4) (match-end 2))))
  5127. (add-text-properties start visible-start hidden)
  5128. (add-text-properties visible-start visible-end properties)
  5129. (add-text-properties visible-end end hidden)
  5130. (org-rear-nonsticky-at visible-start)
  5131. (org-rear-nonsticky-at visible-end)))
  5132. (let ((f (org-link-get-parameter type :activate-func)))
  5133. (when (functionp f)
  5134. (funcall f start end path (eq type 'bracket))))
  5135. (throw :exit t))))) ;signal success
  5136. nil))
  5137. (defun org-activate-code (limit)
  5138. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5139. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5140. (remove-text-properties (match-beginning 0) (match-end 0)
  5141. '(display t invisible t intangible t))
  5142. t))
  5143. (defcustom org-src-fontify-natively t
  5144. "When non-nil, fontify code in code blocks.
  5145. See also the `org-block' face."
  5146. :type 'boolean
  5147. :version "24.4"
  5148. :package-version '(Org . "8.3")
  5149. :group 'org-appearance
  5150. :group 'org-babel)
  5151. (defcustom org-allow-promoting-top-level-subtree nil
  5152. "When non-nil, allow promoting a top level subtree.
  5153. The leading star of the top level headline will be replaced
  5154. by a #."
  5155. :type 'boolean
  5156. :version "24.1"
  5157. :group 'org-appearance)
  5158. (defun org-fontify-meta-lines-and-blocks (limit)
  5159. (condition-case nil
  5160. (org-fontify-meta-lines-and-blocks-1 limit)
  5161. (error (message "org-mode fontification error in %S at %d"
  5162. (current-buffer)
  5163. (line-number-at-pos)))))
  5164. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5165. "Fontify #+ lines and blocks."
  5166. (let ((case-fold-search t))
  5167. (when (re-search-forward
  5168. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5169. limit t)
  5170. (let ((beg (match-beginning 0))
  5171. (block-start (match-end 0))
  5172. (block-end nil)
  5173. (lang (match-string 7))
  5174. (beg1 (line-beginning-position 2))
  5175. (dc1 (downcase (match-string 2)))
  5176. (dc3 (downcase (match-string 3)))
  5177. end end1 quoting block-type)
  5178. (cond
  5179. ((and (match-end 4) (equal dc3 "+begin"))
  5180. ;; Truly a block
  5181. (setq block-type (downcase (match-string 5))
  5182. quoting (member block-type org-protecting-blocks))
  5183. (when (re-search-forward
  5184. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5185. nil t) ;; on purpose, we look further than LIMIT
  5186. (setq end (min (point-max) (match-end 0))
  5187. end1 (min (point-max) (1- (match-beginning 0))))
  5188. (setq block-end (match-beginning 0))
  5189. (when quoting
  5190. (org-remove-flyspell-overlays-in beg1 end1)
  5191. (remove-text-properties beg end
  5192. '(display t invisible t intangible t)))
  5193. (add-text-properties
  5194. beg end '(font-lock-fontified t font-lock-multiline t))
  5195. (add-text-properties beg beg1 '(face org-meta-line))
  5196. (org-remove-flyspell-overlays-in beg beg1)
  5197. (add-text-properties ; For end_src
  5198. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5199. (org-remove-flyspell-overlays-in end1 end)
  5200. (cond
  5201. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5202. (org-src-font-lock-fontify-block lang block-start block-end)
  5203. (add-text-properties beg1 block-end '(src-block t)))
  5204. (quoting
  5205. (add-text-properties beg1 (min (point-max) (1+ end1))
  5206. (list 'face
  5207. (list :inherit
  5208. (let ((face-name
  5209. (intern (format "org-block-%s" lang))))
  5210. (append (and (facep face-name) (list face-name))
  5211. '(org-block))))))) ; end of source block
  5212. ((not org-fontify-quote-and-verse-blocks))
  5213. ((string= block-type "quote")
  5214. (add-face-text-property
  5215. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5216. ((string= block-type "verse")
  5217. (add-face-text-property
  5218. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5219. (add-text-properties beg beg1 '(face org-block-begin-line))
  5220. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5221. '(face org-block-end-line))
  5222. t))
  5223. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5224. (org-remove-flyspell-overlays-in
  5225. (match-beginning 0)
  5226. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5227. (add-text-properties
  5228. beg (match-end 3)
  5229. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5230. '(font-lock-fontified t invisible t)
  5231. '(font-lock-fontified t face org-document-info-keyword)))
  5232. (add-text-properties
  5233. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5234. (if (string-equal dc1 "+title:")
  5235. '(font-lock-fontified t face org-document-title)
  5236. '(font-lock-fontified t face org-document-info))))
  5237. ((string-prefix-p "+caption" dc1)
  5238. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5239. (remove-text-properties (match-beginning 0) (match-end 0)
  5240. '(display t invisible t intangible t))
  5241. ;; Handle short captions.
  5242. (save-excursion
  5243. (beginning-of-line)
  5244. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5245. (add-text-properties (line-beginning-position) (match-end 1)
  5246. '(font-lock-fontified t face org-meta-line))
  5247. (add-text-properties (match-end 0) (line-end-position)
  5248. '(font-lock-fontified t face org-block))
  5249. t)
  5250. ((member dc3 '(" " ""))
  5251. (org-remove-flyspell-overlays-in beg (match-end 0))
  5252. (add-text-properties
  5253. beg (match-end 0)
  5254. '(font-lock-fontified t face font-lock-comment-face)))
  5255. (t ;; just any other in-buffer setting, but not indented
  5256. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5257. (remove-text-properties (match-beginning 0) (match-end 0)
  5258. '(display t invisible t intangible t))
  5259. (add-text-properties beg (match-end 0)
  5260. '(font-lock-fontified t face org-meta-line))
  5261. t))))))
  5262. (defun org-fontify-drawers (limit)
  5263. "Fontify drawers."
  5264. (when (re-search-forward org-drawer-regexp limit t)
  5265. (add-text-properties
  5266. (match-beginning 0) (match-end 0)
  5267. '(font-lock-fontified t face org-special-keyword))
  5268. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5269. t))
  5270. (defun org-fontify-macros (limit)
  5271. "Fontify macros."
  5272. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5273. (add-text-properties
  5274. (match-beginning 0) (match-end 0)
  5275. '(font-lock-fontified t face org-macro))
  5276. (when org-hide-macro-markers
  5277. (add-text-properties (match-end 2) (match-beginning 2)
  5278. '(invisible t))
  5279. (add-text-properties (match-beginning 1) (match-end 1)
  5280. '(invisible t)))
  5281. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5282. t))
  5283. (defun org-activate-footnote-links (limit)
  5284. "Add text properties for footnotes."
  5285. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5286. (when fn
  5287. (let* ((beg (nth 1 fn))
  5288. (end (nth 2 fn))
  5289. (label (car fn))
  5290. (referencep (/= (line-beginning-position) beg)))
  5291. (when (and referencep (nth 3 fn))
  5292. (save-excursion
  5293. (goto-char beg)
  5294. (search-forward (or label "fn:"))
  5295. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5296. (add-text-properties beg end
  5297. (list 'mouse-face 'highlight
  5298. 'keymap org-mouse-map
  5299. 'help-echo
  5300. (if referencep "Footnote reference"
  5301. "Footnote definition")
  5302. 'font-lock-fontified t
  5303. 'font-lock-multiline t
  5304. 'face 'org-footnote))))))
  5305. (defun org-activate-dates (limit)
  5306. "Add text properties for dates."
  5307. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5308. (not (equal (char-before (match-beginning 0)) 91)))
  5309. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5310. (add-text-properties (match-beginning 0) (match-end 0)
  5311. (list 'mouse-face 'highlight
  5312. 'keymap org-mouse-map))
  5313. (org-rear-nonsticky-at (match-end 0))
  5314. (when org-display-custom-times
  5315. (if (match-end 3)
  5316. (org-display-custom-time (match-beginning 3) (match-end 3))
  5317. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5318. t))
  5319. (defvar-local org-target-link-regexp nil
  5320. "Regular expression matching radio targets in plain text.")
  5321. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5322. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5323. border border border))
  5324. "Regular expression matching a link target.")
  5325. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5326. "Regular expression matching a radio target.")
  5327. (defconst org-any-target-regexp
  5328. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5329. "Regular expression matching any target.")
  5330. (defun org-activate-target-links (limit)
  5331. "Add text properties for target matches."
  5332. (when org-target-link-regexp
  5333. (let ((case-fold-search t))
  5334. (when (re-search-forward org-target-link-regexp limit t)
  5335. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5336. (add-text-properties (match-beginning 1) (match-end 1)
  5337. (list 'mouse-face 'highlight
  5338. 'keymap org-mouse-map
  5339. 'help-echo "Radio target link"
  5340. 'org-linked-text t))
  5341. (org-rear-nonsticky-at (match-end 1))
  5342. t))))
  5343. (defun org-update-radio-target-regexp ()
  5344. "Find all radio targets in this file and update the regular expression.
  5345. Also refresh fontification if needed."
  5346. (interactive)
  5347. (let ((old-regexp org-target-link-regexp)
  5348. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5349. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5350. (targets
  5351. (org-with-wide-buffer
  5352. (goto-char (point-min))
  5353. (let (rtn)
  5354. (while (re-search-forward org-radio-target-regexp nil t)
  5355. ;; Make sure point is really within the object.
  5356. (backward-char)
  5357. (let ((obj (org-element-context)))
  5358. (when (eq (org-element-type obj) 'radio-target)
  5359. (cl-pushnew (org-element-property :value obj) rtn
  5360. :test #'equal))))
  5361. rtn))))
  5362. (setq org-target-link-regexp
  5363. (and targets
  5364. (concat before-re
  5365. (mapconcat
  5366. (lambda (x)
  5367. (replace-regexp-in-string
  5368. " +" "\\s-+" (regexp-quote x) t t))
  5369. targets
  5370. "\\|")
  5371. after-re)))
  5372. (unless (equal old-regexp org-target-link-regexp)
  5373. ;; Clean-up cache.
  5374. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5375. ((not org-target-link-regexp) old-regexp)
  5376. (t
  5377. (concat before-re
  5378. (mapconcat
  5379. (lambda (re)
  5380. (substring re (length before-re)
  5381. (- (length after-re))))
  5382. (list old-regexp org-target-link-regexp)
  5383. "\\|")
  5384. after-re)))))
  5385. (org-with-wide-buffer
  5386. (goto-char (point-min))
  5387. (while (re-search-forward regexp nil t)
  5388. (org-element-cache-refresh (match-beginning 1)))))
  5389. ;; Re fontify buffer.
  5390. (when (memq 'radio org-highlight-links)
  5391. (org-restart-font-lock)))))
  5392. (defun org-hide-wide-columns (limit)
  5393. (let (s e)
  5394. (setq s (text-property-any (point) (or limit (point-max))
  5395. 'org-cwidth t))
  5396. (when s
  5397. (setq e (next-single-property-change s 'org-cwidth))
  5398. (add-text-properties s e '(invisible org-cwidth))
  5399. (goto-char e)
  5400. t)))
  5401. (defvar org-latex-and-related-regexp nil
  5402. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5403. (defun org-compute-latex-and-related-regexp ()
  5404. "Compute regular expression for LaTeX, entities and sub/superscript.
  5405. Result depends on variable `org-highlight-latex-and-related'."
  5406. (setq-local
  5407. org-latex-and-related-regexp
  5408. (let* ((re-sub
  5409. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5410. ((eq org-use-sub-superscripts '{})
  5411. (list org-match-substring-with-braces-regexp))
  5412. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5413. (re-latex
  5414. (when (memq 'latex org-highlight-latex-and-related)
  5415. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5416. (delq nil
  5417. (mapcar (lambda (x)
  5418. (and (member (car x) matchers) (nth 1 x)))
  5419. org-latex-regexps)))))
  5420. (re-entities
  5421. (when (memq 'entities org-highlight-latex-and-related)
  5422. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5423. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5424. (defun org-do-latex-and-related (limit)
  5425. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5426. LIMIT bounds the search for syntax to highlight. Stop at first
  5427. highlighted object, if any. Return t if some highlighting was
  5428. done, nil otherwise."
  5429. (when (org-string-nw-p org-latex-and-related-regexp)
  5430. (catch 'found
  5431. (while (re-search-forward org-latex-and-related-regexp limit t)
  5432. (unless
  5433. (cl-some
  5434. (lambda (f)
  5435. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5436. (save-excursion
  5437. (goto-char (1+ (match-beginning 0)))
  5438. (face-at-point nil t)))
  5439. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5440. '(?_ ?^))
  5441. 1
  5442. 0)))
  5443. (font-lock-prepend-text-property
  5444. (+ offset (match-beginning 0)) (match-end 0)
  5445. 'face 'org-latex-and-related)
  5446. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5447. '(font-lock-multiline t)))
  5448. (throw 'found t)))
  5449. nil)))
  5450. (defun org-restart-font-lock ()
  5451. "Restart `font-lock-mode', to force refontification."
  5452. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5453. (font-lock-mode -1)
  5454. (font-lock-mode 1)))
  5455. (defun org-activate-tags (limit)
  5456. (when (re-search-forward
  5457. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5458. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5459. (add-text-properties (match-beginning 1) (match-end 1)
  5460. (list 'mouse-face 'highlight
  5461. 'keymap org-mouse-map))
  5462. (org-rear-nonsticky-at (match-end 1))
  5463. t))
  5464. (defun org-outline-level ()
  5465. "Compute the outline level of the heading at point.
  5466. If this is called at a normal headline, the level is the number
  5467. of stars. Use `org-reduced-level' to remove the effect of
  5468. `org-odd-levels'. Unlike to `org-current-level', this function
  5469. takes into consideration inlinetasks."
  5470. (org-with-wide-buffer
  5471. (end-of-line)
  5472. (if (re-search-backward org-outline-regexp-bol nil t)
  5473. (1- (- (match-end 0) (match-beginning 0)))
  5474. 0)))
  5475. (defvar org-font-lock-keywords nil)
  5476. (defsubst org-re-property (property &optional literal allow-null value)
  5477. "Return a regexp matching a PROPERTY line.
  5478. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5479. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5480. non-nil, match properties even without a value.
  5481. Match group 3 is set to the value when it exists. If there is no
  5482. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5483. With optional argument VALUE, match only property lines with
  5484. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5485. unless LITERAL is non-nil."
  5486. (concat
  5487. "^\\(?4:[ \t]*\\)"
  5488. (format "\\(?1::\\(?2:%s\\):\\)"
  5489. (if literal property (regexp-quote property)))
  5490. (cond (value
  5491. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5492. (if literal value (regexp-quote value))))
  5493. (allow-null
  5494. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5495. (t
  5496. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5497. (defconst org-property-re
  5498. (org-re-property "\\S-+" 'literal t)
  5499. "Regular expression matching a property line.
  5500. There are four matching groups:
  5501. 1: :PROPKEY: including the leading and trailing colon,
  5502. 2: PROPKEY without the leading and trailing colon,
  5503. 3: PROPVAL without leading or trailing spaces,
  5504. 4: the indentation of the current line,
  5505. 5: trailing whitespace.")
  5506. (defvar org-font-lock-hook nil
  5507. "Functions to be called for special font lock stuff.")
  5508. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5509. (defvar org-font-lock-set-keywords-hook nil
  5510. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5511. This is called after `org-font-lock-extra-keywords' is defined, but before
  5512. it is installed to be used by font lock. This can be useful if something
  5513. needs to be inserted at a specific position in the font-lock sequence.")
  5514. (defun org-font-lock-hook (limit)
  5515. "Run `org-font-lock-hook' within LIMIT."
  5516. (run-hook-with-args 'org-font-lock-hook limit))
  5517. (defun org-set-font-lock-defaults ()
  5518. "Set font lock defaults for the current buffer."
  5519. (let* ((em org-fontify-emphasized-text)
  5520. (lk org-highlight-links)
  5521. (org-font-lock-extra-keywords
  5522. (list
  5523. ;; Call the hook
  5524. '(org-font-lock-hook)
  5525. ;; Headlines
  5526. `(,(if org-fontify-whole-heading-line
  5527. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5528. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5529. (1 (org-get-level-face 1))
  5530. (2 (org-get-level-face 2))
  5531. (3 (org-get-level-face 3)))
  5532. ;; Table lines
  5533. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5534. (1 'org-table t))
  5535. ;; Table internals
  5536. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5537. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5538. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5539. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5540. ;; Drawers
  5541. '(org-fontify-drawers)
  5542. ;; Properties
  5543. (list org-property-re
  5544. '(1 'org-special-keyword t)
  5545. '(3 'org-property-value t))
  5546. ;; Link related fontification.
  5547. '(org-activate-links)
  5548. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5549. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5550. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5551. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5552. ;; Targets.
  5553. (list org-any-target-regexp '(0 'org-target t))
  5554. ;; Diary sexps.
  5555. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5556. ;; Macro
  5557. '(org-fontify-macros)
  5558. '(org-hide-wide-columns (0 nil append))
  5559. ;; TODO keyword
  5560. (list (format org-heading-keyword-regexp-format
  5561. org-todo-regexp)
  5562. '(2 (org-get-todo-face 2) t))
  5563. ;; DONE
  5564. (if org-fontify-done-headline
  5565. (list (format org-heading-keyword-regexp-format
  5566. (concat
  5567. "\\(?:"
  5568. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5569. "\\)"))
  5570. '(2 'org-headline-done t))
  5571. nil)
  5572. ;; Priorities
  5573. '(org-font-lock-add-priority-faces)
  5574. ;; Tags
  5575. '(org-font-lock-add-tag-faces)
  5576. ;; Tags groups
  5577. (when (and org-group-tags org-tag-groups-alist)
  5578. (list (concat org-outline-regexp-bol ".+\\(:"
  5579. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5580. ":\\).*$")
  5581. '(1 'org-tag-group prepend)))
  5582. ;; Special keywords
  5583. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5584. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5585. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5586. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5587. ;; Emphasis
  5588. (when em '(org-do-emphasis-faces))
  5589. ;; Checkboxes
  5590. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5591. 1 'org-checkbox prepend)
  5592. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5593. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5594. (0 (org-get-checkbox-statistics-face) t)))
  5595. ;; Description list items
  5596. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5597. 1 'org-list-dt prepend)
  5598. ;; ARCHIVEd headings
  5599. (list (concat
  5600. org-outline-regexp-bol
  5601. "\\(.*:" org-archive-tag ":.*\\)")
  5602. '(1 'org-archived prepend))
  5603. ;; Specials
  5604. '(org-do-latex-and-related)
  5605. '(org-fontify-entities)
  5606. '(org-raise-scripts)
  5607. ;; Code
  5608. '(org-activate-code (1 'org-code t))
  5609. ;; COMMENT
  5610. (list (format
  5611. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5612. org-todo-regexp
  5613. org-comment-string)
  5614. '(9 'org-special-keyword t))
  5615. ;; Blocks and meta lines
  5616. '(org-fontify-meta-lines-and-blocks))))
  5617. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5618. (run-hooks 'org-font-lock-set-keywords-hook)
  5619. ;; Now set the full font-lock-keywords
  5620. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5621. (setq-local font-lock-defaults
  5622. '(org-font-lock-keywords t nil nil backward-paragraph))
  5623. (kill-local-variable 'font-lock-keywords)
  5624. nil))
  5625. (defun org-toggle-pretty-entities ()
  5626. "Toggle the composition display of entities as UTF8 characters."
  5627. (interactive)
  5628. (setq-local org-pretty-entities (not org-pretty-entities))
  5629. (org-restart-font-lock)
  5630. (if org-pretty-entities
  5631. (message "Entities are now displayed as UTF8 characters")
  5632. (save-restriction
  5633. (widen)
  5634. (decompose-region (point-min) (point-max))
  5635. (message "Entities are now displayed as plain text"))))
  5636. (defvar-local org-custom-properties-overlays nil
  5637. "List of overlays used for custom properties.")
  5638. (defun org-toggle-custom-properties-visibility ()
  5639. "Display or hide properties in `org-custom-properties'."
  5640. (interactive)
  5641. (if org-custom-properties-overlays
  5642. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5643. (setq org-custom-properties-overlays nil))
  5644. (when org-custom-properties
  5645. (org-with-wide-buffer
  5646. (goto-char (point-min))
  5647. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5648. (while (re-search-forward regexp nil t)
  5649. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5650. (when (and end (< (point) end))
  5651. ;; Hide first custom property in current drawer.
  5652. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5653. (overlay-put o 'invisible t)
  5654. (overlay-put o 'org-custom-property t)
  5655. (push o org-custom-properties-overlays))
  5656. ;; Hide additional custom properties in the same drawer.
  5657. (while (re-search-forward regexp end t)
  5658. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5659. (overlay-put o 'invisible t)
  5660. (overlay-put o 'org-custom-property t)
  5661. (push o org-custom-properties-overlays)))))
  5662. ;; Each entry is limited to a single property drawer.
  5663. (outline-next-heading)))))))
  5664. (defun org-fontify-entities (limit)
  5665. "Find an entity to fontify."
  5666. (let (ee)
  5667. (when org-pretty-entities
  5668. (catch 'match
  5669. ;; "\_ "-family is left out on purpose. Only the first one,
  5670. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5671. ;; confusing when adding a second white space character.
  5672. (while (re-search-forward
  5673. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5674. limit t)
  5675. (when (and (not (org-at-comment-p))
  5676. (setq ee (org-entity-get (match-string 1)))
  5677. (= (length (nth 6 ee)) 1))
  5678. (let* ((end (if (equal (match-string 2) "{}")
  5679. (match-end 2)
  5680. (match-end 1))))
  5681. (add-text-properties
  5682. (match-beginning 0) end
  5683. (list 'font-lock-fontified t))
  5684. (compose-region (match-beginning 0) end
  5685. (nth 6 ee) nil)
  5686. (backward-char 1)
  5687. (throw 'match t))))
  5688. nil))))
  5689. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5690. "Fontify string S like in Org mode."
  5691. (with-temp-buffer
  5692. (insert s)
  5693. (let ((org-odd-levels-only odd-levels))
  5694. (org-mode)
  5695. (org-font-lock-ensure)
  5696. (buffer-string))))
  5697. (defvar org-m nil)
  5698. (defvar org-l nil)
  5699. (defvar org-f nil)
  5700. (defun org-get-level-face (n)
  5701. "Get the right face for match N in font-lock matching of headlines."
  5702. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5703. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5704. (if org-cycle-level-faces
  5705. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5706. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5707. (cond
  5708. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5709. ((eq n 2) org-f)
  5710. (t (unless org-level-color-stars-only org-f))))
  5711. (defun org-face-from-face-or-color (context inherit face-or-color)
  5712. "Create a face list that inherits INHERIT, but sets the foreground color.
  5713. When FACE-OR-COLOR is not a string, just return it."
  5714. (if (stringp face-or-color)
  5715. (list :inherit inherit
  5716. (cdr (assoc context org-faces-easy-properties))
  5717. face-or-color)
  5718. face-or-color))
  5719. (defun org-get-todo-face (kwd)
  5720. "Get the right face for a TODO keyword KWD.
  5721. If KWD is a number, get the corresponding match group."
  5722. (when (numberp kwd) (setq kwd (match-string kwd)))
  5723. (or (org-face-from-face-or-color
  5724. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5725. (and (member kwd org-done-keywords) 'org-done)
  5726. 'org-todo))
  5727. (defun org-get-priority-face (priority)
  5728. "Get the right face for PRIORITY.
  5729. PRIORITY is a character."
  5730. (or (org-face-from-face-or-color
  5731. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5732. 'org-priority))
  5733. (defun org-get-tag-face (tag)
  5734. "Get the right face for TAG.
  5735. If TAG is a number, get the corresponding match group."
  5736. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5737. (or (org-face-from-face-or-color
  5738. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5739. 'org-tag)))
  5740. (defun org-font-lock-add-priority-faces (limit)
  5741. "Add the special priority faces."
  5742. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5743. (add-text-properties
  5744. (match-beginning 1) (match-end 1)
  5745. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5746. 'font-lock-fontified t))))
  5747. (defun org-font-lock-add-tag-faces (limit)
  5748. "Add the special tag faces."
  5749. (when (and org-tag-faces org-tags-special-faces-re)
  5750. (while (re-search-forward org-tags-special-faces-re limit t)
  5751. (add-text-properties (match-beginning 1) (match-end 1)
  5752. (list 'face (org-get-tag-face 1)
  5753. 'font-lock-fontified t))
  5754. (backward-char 1))))
  5755. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5756. "Remove fontification and activation overlays from links."
  5757. (font-lock-default-unfontify-region beg end)
  5758. (let* ((buffer-undo-list t)
  5759. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5760. (inhibit-modification-hooks t)
  5761. deactivate-mark buffer-file-name buffer-file-truename)
  5762. (decompose-region beg end)
  5763. (remove-text-properties beg end
  5764. '(mouse-face t keymap t org-linked-text t
  5765. invisible t intangible t
  5766. org-emphasis t))
  5767. (org-remove-font-lock-display-properties beg end)))
  5768. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5769. ((raise 0.3) (height 0.7))
  5770. ((raise -0.5))
  5771. ((raise 0.5)))
  5772. "Display properties for showing superscripts and subscripts.")
  5773. (defun org-remove-font-lock-display-properties (beg end)
  5774. "Remove specific display properties that have been added by font lock.
  5775. The will remove the raise properties that are used to show superscripts
  5776. and subscripts."
  5777. (let (next prop)
  5778. (while (< beg end)
  5779. (setq next (next-single-property-change beg 'display nil end)
  5780. prop (get-text-property beg 'display))
  5781. (when (member prop org-script-display)
  5782. (put-text-property beg next 'display nil))
  5783. (setq beg next))))
  5784. (defun org-raise-scripts (limit)
  5785. "Add raise properties to sub/superscripts."
  5786. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5787. (re-search-forward
  5788. (if (eq org-use-sub-superscripts t)
  5789. org-match-substring-regexp
  5790. org-match-substring-with-braces-regexp)
  5791. limit t))
  5792. (let* ((pos (point)) table-p comment-p
  5793. (mpos (match-beginning 3))
  5794. (emph-p (get-text-property mpos 'org-emphasis))
  5795. (link-p (get-text-property mpos 'mouse-face))
  5796. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5797. (goto-char (point-at-bol))
  5798. (setq table-p (looking-at-p org-table-dataline-regexp)
  5799. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5800. (goto-char pos)
  5801. ;; Handle a_b^c
  5802. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5803. (unless (or comment-p emph-p link-p keyw-p)
  5804. (put-text-property (match-beginning 3) (match-end 0)
  5805. 'display
  5806. (if (equal (char-after (match-beginning 2)) ?^)
  5807. (nth (if table-p 3 1) org-script-display)
  5808. (nth (if table-p 2 0) org-script-display)))
  5809. (add-text-properties (match-beginning 2) (match-end 2)
  5810. (list 'invisible t
  5811. 'org-dwidth t 'org-dwidth-n 1))
  5812. (if (and (eq (char-after (match-beginning 3)) ?{)
  5813. (eq (char-before (match-end 3)) ?}))
  5814. (progn
  5815. (add-text-properties
  5816. (match-beginning 3) (1+ (match-beginning 3))
  5817. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5818. (add-text-properties
  5819. (1- (match-end 3)) (match-end 3)
  5820. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5821. t)))
  5822. ;;;; Visibility cycling, including org-goto and indirect buffer
  5823. ;;; Cycling
  5824. (defvar-local org-cycle-global-status nil)
  5825. (put 'org-cycle-global-status 'org-state t)
  5826. (defvar-local org-cycle-subtree-status nil)
  5827. (put 'org-cycle-subtree-status 'org-state t)
  5828. (defvar org-inlinetask-min-level)
  5829. (defun org-unlogged-message (&rest args)
  5830. "Display a message, but avoid logging it in the *Messages* buffer."
  5831. (let ((message-log-max nil))
  5832. (apply 'message args)))
  5833. ;;;###autoload
  5834. (defun org-cycle (&optional arg)
  5835. "TAB-action and visibility cycling for Org mode.
  5836. This is the command invoked in Org mode by the `TAB' key. Its main
  5837. purpose is outline visibility cycling, but it also invokes other actions
  5838. in special contexts.
  5839. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5840. the entire
  5841. buffer through 3 states (global cycling)
  5842. 1. OVERVIEW: Show only top-level headlines.
  5843. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5844. 3. SHOW ALL: Show everything.
  5845. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5846. switch to the startup visibility,
  5847. determined by the variable `org-startup-folded', and by any VISIBILITY
  5848. properties in the buffer.
  5849. With a `\\[universal-argument] \\[universal-argument] \
  5850. \\[universal-argument]' prefix argument, show the entire buffer, including
  5851. any drawers.
  5852. When inside a table, re-align the table and move to the next field.
  5853. When point is at the beginning of a headline, rotate the subtree started
  5854. by this line through 3 different states (local cycling)
  5855. 1. FOLDED: Only the main headline is shown.
  5856. 2. CHILDREN: The main headline and the direct children are shown.
  5857. From this state, you can move to one of the children
  5858. and zoom in further.
  5859. 3. SUBTREE: Show the entire subtree, including body text.
  5860. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5861. When point is at the beginning of an empty headline and the variable
  5862. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5863. of the headline by demoting and promoting it to likely levels. This
  5864. speeds up creation document structure by pressing `TAB' once or several
  5865. times right after creating a new headline.
  5866. When there is a numeric prefix, go up to a heading with level ARG, do
  5867. a `show-subtree' and return to the previous cursor position. If ARG
  5868. is negative, go up that many levels.
  5869. When point is not at the beginning of a headline, execute the global
  5870. binding for `TAB', which is re-indenting the line. See the option
  5871. `org-cycle-emulate-tab' for details.
  5872. As a special case, if point is at the beginning of the buffer and there is
  5873. no headline in line 1, this function will act as if called with prefix arg
  5874. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5875. prefix arg, but only
  5876. if the variable `org-cycle-global-at-bob' is t."
  5877. (interactive "P")
  5878. (org-load-modules-maybe)
  5879. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5880. (and org-cycle-level-after-item/entry-creation
  5881. (or (org-cycle-level)
  5882. (org-cycle-item-indentation))))
  5883. (let* ((limit-level
  5884. (or org-cycle-max-level
  5885. (and (boundp 'org-inlinetask-min-level)
  5886. org-inlinetask-min-level
  5887. (1- org-inlinetask-min-level))))
  5888. (nstars (and limit-level
  5889. (if org-odd-levels-only
  5890. (and limit-level (1- (* limit-level 2)))
  5891. limit-level)))
  5892. (org-outline-regexp
  5893. (if (not (derived-mode-p 'org-mode))
  5894. outline-regexp
  5895. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5896. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5897. (not (looking-at org-outline-regexp))))
  5898. (org-cycle-hook
  5899. (if bob-special
  5900. (delq 'org-optimize-window-after-visibility-change
  5901. (copy-sequence org-cycle-hook))
  5902. org-cycle-hook))
  5903. (pos (point)))
  5904. (cond
  5905. ((equal arg '(16))
  5906. (setq last-command 'dummy)
  5907. (org-set-startup-visibility)
  5908. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5909. ((equal arg '(64))
  5910. (outline-show-all)
  5911. (org-unlogged-message "Entire buffer visible, including drawers"))
  5912. ((equal arg '(4)) (org-cycle-internal-global))
  5913. ;; Try hiding block at point.
  5914. ((org-hide-block-toggle-maybe))
  5915. ;; Try cdlatex TAB completion
  5916. ((org-try-cdlatex-tab))
  5917. ;; Table: enter it or move to the next field.
  5918. ((org-at-table-p 'any)
  5919. (if (org-at-table.el-p)
  5920. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5921. Use `\\[org-edit-special]' to edit table.el tables"))
  5922. (if arg (org-table-edit-field t)
  5923. (org-table-justify-field-maybe)
  5924. (call-interactively 'org-table-next-field))))
  5925. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5926. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5927. (bob-special (org-cycle-internal-global))
  5928. ;; Drawers: delegate to `org-flag-drawer'.
  5929. ((save-excursion
  5930. (beginning-of-line 1)
  5931. (looking-at org-drawer-regexp))
  5932. (org-flag-drawer ; toggle block visibility
  5933. (not (get-char-property (match-end 0) 'invisible))))
  5934. ;; Show-subtree, ARG levels up from here.
  5935. ((integerp arg)
  5936. (save-excursion
  5937. (org-back-to-heading)
  5938. (outline-up-heading (if (< arg 0) (- arg)
  5939. (- (funcall outline-level) arg)))
  5940. (org-show-subtree)))
  5941. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5942. ((and (featurep 'org-inlinetask)
  5943. (org-inlinetask-at-task-p)
  5944. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5945. (org-inlinetask-toggle-visibility))
  5946. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5947. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5948. (save-excursion (move-beginning-of-line 1)
  5949. (looking-at org-outline-regexp)))
  5950. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5951. (org-cycle-internal-local))
  5952. ;; From there: TAB emulation and template completion.
  5953. (buffer-read-only (org-back-to-heading))
  5954. ((run-hook-with-args-until-success
  5955. 'org-tab-after-check-for-cycling-hook))
  5956. ((org-try-structure-completion))
  5957. ((run-hook-with-args-until-success
  5958. 'org-tab-before-tab-emulation-hook))
  5959. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5960. (or (not (bolp))
  5961. (not (looking-at org-outline-regexp))))
  5962. (call-interactively (global-key-binding "\t")))
  5963. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5964. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5965. (or (and (eq org-cycle-emulate-tab 'white)
  5966. (= (match-end 0) (point-at-eol)))
  5967. (and (eq org-cycle-emulate-tab 'whitestart)
  5968. (>= (match-end 0) pos))))
  5969. t
  5970. (eq org-cycle-emulate-tab t))
  5971. (call-interactively (global-key-binding "\t")))
  5972. (t (save-excursion
  5973. (org-back-to-heading)
  5974. (org-cycle)))))))
  5975. (defun org-cycle-internal-global ()
  5976. "Do the global cycling action."
  5977. ;; Hack to avoid display of messages for .org attachments in Gnus
  5978. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5979. (cond
  5980. ((and (eq last-command this-command)
  5981. (eq org-cycle-global-status 'overview))
  5982. ;; We just created the overview - now do table of contents
  5983. ;; This can be slow in very large buffers, so indicate action
  5984. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5985. (unless ga (org-unlogged-message "CONTENTS..."))
  5986. (org-content)
  5987. (unless ga (org-unlogged-message "CONTENTS...done"))
  5988. (setq org-cycle-global-status 'contents)
  5989. (run-hook-with-args 'org-cycle-hook 'contents))
  5990. ((and (eq last-command this-command)
  5991. (eq org-cycle-global-status 'contents))
  5992. ;; We just showed the table of contents - now show everything
  5993. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5994. (outline-show-all)
  5995. (unless ga (org-unlogged-message "SHOW ALL"))
  5996. (setq org-cycle-global-status 'all)
  5997. (run-hook-with-args 'org-cycle-hook 'all))
  5998. (t
  5999. ;; Default action: go to overview
  6000. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6001. (org-overview)
  6002. (unless ga (org-unlogged-message "OVERVIEW"))
  6003. (setq org-cycle-global-status 'overview)
  6004. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6005. (defvar org-called-with-limited-levels nil
  6006. "Non-nil when `org-with-limited-levels' is currently active.")
  6007. (defun org-cycle-internal-local ()
  6008. "Do the local cycling action."
  6009. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6010. ;; First, determine end of headline (EOH), end of subtree or item
  6011. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6012. (save-excursion
  6013. (if (org-at-item-p)
  6014. (progn
  6015. (beginning-of-line)
  6016. (setq struct (org-list-struct))
  6017. (setq eoh (point-at-eol))
  6018. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6019. (setq has-children (org-list-has-child-p (point) struct)))
  6020. (org-back-to-heading)
  6021. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6022. (setq eos (save-excursion (org-end-of-subtree t t)
  6023. (when (bolp) (backward-char)) (point)))
  6024. (setq has-children
  6025. (or (save-excursion
  6026. (let ((level (funcall outline-level)))
  6027. (outline-next-heading)
  6028. (and (org-at-heading-p t)
  6029. (> (funcall outline-level) level))))
  6030. (save-excursion
  6031. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6032. ;; Determine end invisible part of buffer (EOL)
  6033. (beginning-of-line 2)
  6034. (while (and (not (eobp)) ;This is like `next-line'.
  6035. (get-char-property (1- (point)) 'invisible))
  6036. (goto-char (next-single-char-property-change (point) 'invisible))
  6037. (and (eolp) (beginning-of-line 2)))
  6038. (setq eol (point)))
  6039. ;; Find out what to do next and set `this-command'
  6040. (cond
  6041. ((= eos eoh)
  6042. ;; Nothing is hidden behind this heading
  6043. (unless (org-before-first-heading-p)
  6044. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6045. (org-unlogged-message "EMPTY ENTRY")
  6046. (setq org-cycle-subtree-status nil)
  6047. (save-excursion
  6048. (goto-char eos)
  6049. (outline-next-heading)
  6050. (when (outline-invisible-p) (org-flag-heading nil))))
  6051. ((and (or (>= eol eos)
  6052. (not (string-match "\\S-" (buffer-substring eol eos))))
  6053. (or has-children
  6054. (not (setq children-skipped
  6055. org-cycle-skip-children-state-if-no-children))))
  6056. ;; Entire subtree is hidden in one line: children view
  6057. (unless (org-before-first-heading-p)
  6058. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6059. (if (org-at-item-p)
  6060. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6061. (org-show-entry)
  6062. (org-with-limited-levels (org-show-children))
  6063. ;; FIXME: This slows down the func way too much.
  6064. ;; How keep drawers hidden in subtree anyway?
  6065. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6066. ;; (org-cycle-hide-drawers 'subtree))
  6067. ;; Fold every list in subtree to top-level items.
  6068. (when (eq org-cycle-include-plain-lists 'integrate)
  6069. (save-excursion
  6070. (org-back-to-heading)
  6071. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6072. (beginning-of-line 1)
  6073. (let* ((struct (org-list-struct))
  6074. (prevs (org-list-prevs-alist struct))
  6075. (end (org-list-get-bottom-point struct)))
  6076. (dolist (e (org-list-get-all-items (point) struct prevs))
  6077. (org-list-set-item-visibility e struct 'folded))
  6078. (goto-char (if (< end eos) end eos)))))))
  6079. (org-unlogged-message "CHILDREN")
  6080. (save-excursion
  6081. (goto-char eos)
  6082. (outline-next-heading)
  6083. (when (outline-invisible-p) (org-flag-heading nil)))
  6084. (setq org-cycle-subtree-status 'children)
  6085. (unless (org-before-first-heading-p)
  6086. (run-hook-with-args 'org-cycle-hook 'children)))
  6087. ((or children-skipped
  6088. (and (eq last-command this-command)
  6089. (eq org-cycle-subtree-status 'children)))
  6090. ;; We just showed the children, or no children are there,
  6091. ;; now show everything.
  6092. (unless (org-before-first-heading-p)
  6093. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6094. (outline-flag-region eoh eos nil)
  6095. (org-unlogged-message
  6096. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6097. (setq org-cycle-subtree-status 'subtree)
  6098. (unless (org-before-first-heading-p)
  6099. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6100. (t
  6101. ;; Default action: hide the subtree.
  6102. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6103. (outline-flag-region eoh eos t)
  6104. (org-unlogged-message "FOLDED")
  6105. (setq org-cycle-subtree-status 'folded)
  6106. (unless (org-before-first-heading-p)
  6107. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6108. ;;;###autoload
  6109. (defun org-global-cycle (&optional arg)
  6110. "Cycle the global visibility. For details see `org-cycle'.
  6111. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6112. With a numeric prefix, show all headlines up to that level."
  6113. (interactive "P")
  6114. (let ((org-cycle-include-plain-lists
  6115. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6116. (cond
  6117. ((integerp arg)
  6118. (outline-show-all)
  6119. (outline-hide-sublevels arg)
  6120. (setq org-cycle-global-status 'contents))
  6121. ((equal arg '(4))
  6122. (org-set-startup-visibility)
  6123. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6124. (t
  6125. (org-cycle '(4))))))
  6126. (defun org-set-startup-visibility ()
  6127. "Set the visibility required by startup options and properties."
  6128. (cond
  6129. ((eq org-startup-folded t)
  6130. (org-overview))
  6131. ((eq org-startup-folded 'content)
  6132. (org-content))
  6133. ((or (eq org-startup-folded 'showeverything)
  6134. (eq org-startup-folded nil))
  6135. (outline-show-all)))
  6136. (unless (eq org-startup-folded 'showeverything)
  6137. (when org-hide-block-startup (org-hide-block-all))
  6138. (org-set-visibility-according-to-property 'no-cleanup)
  6139. (org-cycle-hide-archived-subtrees 'all)
  6140. (org-cycle-hide-drawers 'all)
  6141. (org-cycle-show-empty-lines t)))
  6142. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6143. "Switch subtree visibilities according to :VISIBILITY: property."
  6144. (interactive)
  6145. (org-with-wide-buffer
  6146. (goto-char (point-min))
  6147. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6148. (if (not (org-at-property-p)) (outline-next-heading)
  6149. (let ((state (match-string 3)))
  6150. (save-excursion
  6151. (org-back-to-heading t)
  6152. (outline-hide-subtree)
  6153. (org-reveal)
  6154. (cond
  6155. ((equal state "folded")
  6156. (outline-hide-subtree))
  6157. ((equal state "children")
  6158. (org-show-hidden-entry)
  6159. (org-show-children))
  6160. ((equal state "content")
  6161. (save-excursion
  6162. (save-restriction
  6163. (org-narrow-to-subtree)
  6164. (org-content))))
  6165. ((member state '("all" "showall"))
  6166. (outline-show-subtree)))))))
  6167. (unless no-cleanup
  6168. (org-cycle-hide-archived-subtrees 'all)
  6169. (org-cycle-hide-drawers 'all)
  6170. (org-cycle-show-empty-lines 'all))))
  6171. ;; This function uses outline-regexp instead of the more fundamental
  6172. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6173. ;; buffers, where outline-regexp is needed.
  6174. (defun org-overview ()
  6175. "Switch to overview mode, showing only top-level headlines.
  6176. This shows all headlines with a level equal or greater than the level
  6177. of the first headline in the buffer. This is important, because if the
  6178. first headline is not level one, then (hide-sublevels 1) gives confusing
  6179. results."
  6180. (interactive)
  6181. (save-excursion
  6182. (let ((level
  6183. (save-excursion
  6184. (goto-char (point-min))
  6185. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6186. (goto-char (match-beginning 0))
  6187. (funcall outline-level)))))
  6188. (and level (outline-hide-sublevels level)))))
  6189. (defun org-content (&optional arg)
  6190. "Show all headlines in the buffer, like a table of contents.
  6191. With numerical argument N, show content up to level N."
  6192. (interactive "P")
  6193. (org-overview)
  6194. (save-excursion
  6195. ;; Visit all headings and show their offspring
  6196. (and (integerp arg) (org-overview))
  6197. (goto-char (point-max))
  6198. (catch 'exit
  6199. (while (and (progn (condition-case nil
  6200. (outline-previous-visible-heading 1)
  6201. (error (goto-char (point-min))))
  6202. t)
  6203. (looking-at org-outline-regexp))
  6204. (if (integerp arg)
  6205. (org-show-children (1- arg))
  6206. (outline-show-branches))
  6207. (when (bobp) (throw 'exit nil))))))
  6208. (defun org-optimize-window-after-visibility-change (state)
  6209. "Adjust the window after a change in outline visibility.
  6210. This function is the default value of the hook `org-cycle-hook'."
  6211. (when (get-buffer-window (current-buffer))
  6212. (cond
  6213. ((eq state 'content) nil)
  6214. ((eq state 'all) nil)
  6215. ((eq state 'folded) nil)
  6216. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6217. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6218. (defun org-remove-empty-overlays-at (pos)
  6219. "Remove outline overlays that do not contain non-white stuff."
  6220. (dolist (o (overlays-at pos))
  6221. (and (eq 'outline (overlay-get o 'invisible))
  6222. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6223. (overlay-end o))))
  6224. (delete-overlay o))))
  6225. (defun org-clean-visibility-after-subtree-move ()
  6226. "Fix visibility issues after moving a subtree."
  6227. ;; First, find a reasonable region to look at:
  6228. ;; Start two siblings above, end three below
  6229. (let* ((beg (save-excursion
  6230. (and (org-get-last-sibling)
  6231. (org-get-last-sibling))
  6232. (point)))
  6233. (end (save-excursion
  6234. (and (org-get-next-sibling)
  6235. (org-get-next-sibling)
  6236. (org-get-next-sibling))
  6237. (if (org-at-heading-p)
  6238. (point-at-eol)
  6239. (point))))
  6240. (level (looking-at "\\*+"))
  6241. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6242. (save-excursion
  6243. (save-restriction
  6244. (narrow-to-region beg end)
  6245. (when re
  6246. ;; Properly fold already folded siblings
  6247. (goto-char (point-min))
  6248. (while (re-search-forward re nil t)
  6249. (when (and (not (outline-invisible-p))
  6250. (save-excursion
  6251. (goto-char (point-at-eol)) (outline-invisible-p)))
  6252. (outline-hide-entry))))
  6253. (org-cycle-show-empty-lines 'overview)
  6254. (org-cycle-hide-drawers 'overview)))))
  6255. (defun org-cycle-show-empty-lines (state)
  6256. "Show empty lines above all visible headlines.
  6257. The region to be covered depends on STATE when called through
  6258. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6259. entire buffer covered. Note that an empty line is only shown if there
  6260. are at least `org-cycle-separator-lines' empty lines before the headline."
  6261. (when (/= org-cycle-separator-lines 0)
  6262. (save-excursion
  6263. (let* ((n (abs org-cycle-separator-lines))
  6264. (re (cond
  6265. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6266. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6267. (t (let ((ns (number-to-string (- n 2))))
  6268. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6269. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6270. beg end)
  6271. (cond
  6272. ((memq state '(overview contents t))
  6273. (setq beg (point-min) end (point-max)))
  6274. ((memq state '(children folded))
  6275. (setq beg (point)
  6276. end (progn (org-end-of-subtree t t)
  6277. (line-beginning-position 2)))))
  6278. (when beg
  6279. (goto-char beg)
  6280. (while (re-search-forward re end t)
  6281. (unless (get-char-property (match-end 1) 'invisible)
  6282. (let ((e (match-end 1))
  6283. (b (if (>= org-cycle-separator-lines 0)
  6284. (match-beginning 1)
  6285. (save-excursion
  6286. (goto-char (match-beginning 0))
  6287. (skip-chars-backward " \t\n")
  6288. (line-end-position)))))
  6289. (outline-flag-region b e nil))))))))
  6290. ;; Never hide empty lines at the end of the file.
  6291. (save-excursion
  6292. (goto-char (point-max))
  6293. (outline-previous-heading)
  6294. (outline-end-of-heading)
  6295. (when (and (looking-at "[ \t\n]+")
  6296. (= (match-end 0) (point-max)))
  6297. (outline-flag-region (point) (match-end 0) nil))))
  6298. (defun org-show-empty-lines-in-parent ()
  6299. "Move to the parent and re-show empty lines before visible headlines."
  6300. (save-excursion
  6301. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6302. (org-cycle-show-empty-lines context))))
  6303. (defun org-files-list ()
  6304. "Return `org-agenda-files' list, plus all open Org files.
  6305. This is useful for operations that need to scan all of a user's
  6306. open and agenda-wise Org files."
  6307. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6308. (dolist (buf (buffer-list))
  6309. (with-current-buffer buf
  6310. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6311. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6312. files))
  6313. (defsubst org-entry-beginning-position ()
  6314. "Return the beginning position of the current entry."
  6315. (save-excursion (org-back-to-heading t) (point)))
  6316. (defsubst org-entry-end-position ()
  6317. "Return the end position of the current entry."
  6318. (save-excursion (outline-next-heading) (point)))
  6319. (defun org-cycle-hide-drawers (state &optional exceptions)
  6320. "Re-hide all drawers after a visibility state change.
  6321. When non-nil, optional argument EXCEPTIONS is a list of strings
  6322. specifying which drawers should not be hidden."
  6323. (when (and (derived-mode-p 'org-mode)
  6324. (not (memq state '(overview folded contents))))
  6325. (save-excursion
  6326. (let* ((globalp (memq state '(contents all)))
  6327. (beg (if globalp (point-min) (point)))
  6328. (end (if globalp (point-max)
  6329. (if (eq state 'children)
  6330. (save-excursion (outline-next-heading) (point))
  6331. (org-end-of-subtree t)))))
  6332. (goto-char beg)
  6333. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6334. (unless (member-ignore-case (match-string 1) exceptions)
  6335. (let ((drawer (org-element-at-point)))
  6336. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6337. (org-flag-drawer t drawer)
  6338. ;; Make sure to skip drawer entirely or we might flag
  6339. ;; it another time when matching its ending line with
  6340. ;; `org-drawer-regexp'.
  6341. (goto-char (org-element-property :end drawer))))))))))
  6342. (defun org-flag-drawer (flag &optional element)
  6343. "When FLAG is non-nil, hide the drawer we are at.
  6344. Otherwise make it visible. When optional argument ELEMENT is
  6345. a parsed drawer, as returned by `org-element-at-point', hide or
  6346. show that drawer instead."
  6347. (let ((drawer (or element
  6348. (and (save-excursion
  6349. (beginning-of-line)
  6350. (looking-at-p org-drawer-regexp))
  6351. (org-element-at-point)))))
  6352. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6353. (let ((post (org-element-property :post-affiliated drawer)))
  6354. (save-excursion
  6355. (outline-flag-region
  6356. (progn (goto-char post) (line-end-position))
  6357. (progn (goto-char (org-element-property :end drawer))
  6358. (skip-chars-backward " \r\t\n")
  6359. (line-end-position))
  6360. flag))
  6361. ;; When the drawer is hidden away, make sure point lies in
  6362. ;; a visible part of the buffer.
  6363. (when (and flag (> (line-beginning-position) post))
  6364. (goto-char post))))))
  6365. (defun org-subtree-end-visible-p ()
  6366. "Is the end of the current subtree visible?"
  6367. (pos-visible-in-window-p
  6368. (save-excursion (org-end-of-subtree t) (point))))
  6369. (defun org-first-headline-recenter ()
  6370. "Move cursor to the first headline and recenter the headline."
  6371. (let ((window (get-buffer-window)))
  6372. (when window
  6373. (goto-char (point-min))
  6374. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6375. (set-window-start window (line-beginning-position))))))
  6376. ;;; Saving and restoring visibility
  6377. (defun org-outline-overlay-data (&optional use-markers)
  6378. "Return a list of the locations of all outline overlays.
  6379. These are overlays with the `invisible' property value `outline'.
  6380. The return value is a list of cons cells, with start and stop
  6381. positions for each overlay.
  6382. If USE-MARKERS is set, return the positions as markers."
  6383. (let (beg end)
  6384. (org-with-wide-buffer
  6385. (delq nil
  6386. (mapcar (lambda (o)
  6387. (when (eq (overlay-get o 'invisible) 'outline)
  6388. (setq beg (overlay-start o)
  6389. end (overlay-end o))
  6390. (and beg end (> end beg)
  6391. (if use-markers
  6392. (cons (copy-marker beg)
  6393. (copy-marker end t))
  6394. (cons beg end)))))
  6395. (overlays-in (point-min) (point-max)))))))
  6396. (defun org-set-outline-overlay-data (data)
  6397. "Create visibility overlays for all positions in DATA.
  6398. DATA should have been made by `org-outline-overlay-data'."
  6399. (org-with-wide-buffer
  6400. (outline-show-all)
  6401. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6402. ;;; Folding of blocks
  6403. (defvar-local org-hide-block-overlays nil
  6404. "Overlays hiding blocks.")
  6405. (defun org-block-map (function &optional start end)
  6406. "Call FUNCTION at the head of all source blocks in the current buffer.
  6407. Optional arguments START and END can be used to limit the range."
  6408. (let ((start (or start (point-min)))
  6409. (end (or end (point-max))))
  6410. (save-excursion
  6411. (goto-char start)
  6412. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6413. (save-excursion
  6414. (save-match-data
  6415. (goto-char (match-beginning 0))
  6416. (funcall function)))))))
  6417. (defun org-hide-block-toggle-all ()
  6418. "Toggle the visibility of all blocks in the current buffer."
  6419. (org-block-map 'org-hide-block-toggle))
  6420. (defun org-hide-block-all ()
  6421. "Fold all blocks in the current buffer."
  6422. (interactive)
  6423. (org-show-block-all)
  6424. (org-block-map 'org-hide-block-toggle-maybe))
  6425. (defun org-show-block-all ()
  6426. "Unfold all blocks in the current buffer."
  6427. (interactive)
  6428. (mapc #'delete-overlay org-hide-block-overlays)
  6429. (setq org-hide-block-overlays nil))
  6430. (defun org-hide-block-toggle-maybe ()
  6431. "Toggle visibility of block at point.
  6432. Unlike to `org-hide-block-toggle', this function does not throw
  6433. an error. Return a non-nil value when toggling is successful."
  6434. (interactive)
  6435. (ignore-errors (org-hide-block-toggle)))
  6436. (defun org-hide-block-toggle (&optional force)
  6437. "Toggle the visibility of the current block.
  6438. When optional argument FORCE is `off', make block visible. If it
  6439. is non-nil, hide it unconditionally. Throw an error when not at
  6440. a block. Return a non-nil value when toggling is successful."
  6441. (interactive)
  6442. (let ((element (org-element-at-point)))
  6443. (unless (memq (org-element-type element)
  6444. '(center-block comment-block dynamic-block example-block
  6445. export-block quote-block special-block
  6446. src-block verse-block))
  6447. (user-error "Not at a block"))
  6448. (let* ((start (save-excursion
  6449. (goto-char (org-element-property :post-affiliated element))
  6450. (line-end-position)))
  6451. (end (save-excursion
  6452. (goto-char (org-element-property :end element))
  6453. (skip-chars-backward " \r\t\n")
  6454. (line-end-position)))
  6455. (overlays (overlays-at start)))
  6456. (cond
  6457. ;; Do nothing when not before or at the block opening line or
  6458. ;; at the block closing line.
  6459. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6460. ((and (not (eq force 'off))
  6461. (not (memq t (mapcar
  6462. (lambda (o)
  6463. (eq (overlay-get o 'invisible) 'org-hide-block))
  6464. overlays))))
  6465. (let ((ov (make-overlay start end)))
  6466. (overlay-put ov 'invisible 'org-hide-block)
  6467. ;; Make the block accessible to `isearch'.
  6468. (overlay-put
  6469. ov 'isearch-open-invisible
  6470. (lambda (ov)
  6471. (when (memq ov org-hide-block-overlays)
  6472. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6473. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6474. (delete-overlay ov))))
  6475. (push ov org-hide-block-overlays)
  6476. ;; When the block is hidden away, make sure point is left in
  6477. ;; a visible part of the buffer.
  6478. (when (> (line-beginning-position) start)
  6479. (goto-char start)
  6480. (beginning-of-line))
  6481. ;; Signal successful toggling.
  6482. t))
  6483. ((or (not force) (eq force 'off))
  6484. (dolist (ov overlays t)
  6485. (when (memq ov org-hide-block-overlays)
  6486. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6487. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6488. (delete-overlay ov))))))))
  6489. ;; Remove overlays when changing major mode
  6490. (add-hook 'org-mode-hook
  6491. (lambda () (add-hook 'change-major-mode-hook
  6492. 'org-show-block-all 'append 'local)))
  6493. ;;; Org-goto
  6494. (defvar org-goto-window-configuration nil)
  6495. (defvar org-goto-marker nil)
  6496. (defvar org-goto-map)
  6497. (defun org-goto-map ()
  6498. "Set the keymap `org-goto'."
  6499. (setq org-goto-map
  6500. (let ((map (make-sparse-keymap)))
  6501. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6502. mouse-drag-region universal-argument org-occur)))
  6503. (dolist (cmd cmds)
  6504. (substitute-key-definition cmd cmd map global-map)))
  6505. (suppress-keymap map)
  6506. (org-defkey map "\C-m" 'org-goto-ret)
  6507. (org-defkey map [(return)] 'org-goto-ret)
  6508. (org-defkey map [(left)] 'org-goto-left)
  6509. (org-defkey map [(right)] 'org-goto-right)
  6510. (org-defkey map [(control ?g)] 'org-goto-quit)
  6511. (org-defkey map "\C-i" 'org-cycle)
  6512. (org-defkey map [(tab)] 'org-cycle)
  6513. (org-defkey map [(down)] 'outline-next-visible-heading)
  6514. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6515. (if org-goto-auto-isearch
  6516. (if (fboundp 'define-key-after)
  6517. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6518. nil)
  6519. (org-defkey map "q" 'org-goto-quit)
  6520. (org-defkey map "n" 'outline-next-visible-heading)
  6521. (org-defkey map "p" 'outline-previous-visible-heading)
  6522. (org-defkey map "f" 'outline-forward-same-level)
  6523. (org-defkey map "b" 'outline-backward-same-level)
  6524. (org-defkey map "u" 'outline-up-heading))
  6525. (org-defkey map "/" 'org-occur)
  6526. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6527. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6528. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6529. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6530. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6531. map)))
  6532. (defconst org-goto-help
  6533. "Browse buffer copy, to find location or copy text.%s
  6534. RET=jump to location C-g=quit and return to previous location
  6535. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6536. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6537. (defun org-goto (&optional alternative-interface)
  6538. "Look up a different location in the current file, keeping current visibility.
  6539. When you want look-up or go to a different location in a
  6540. document, the fastest way is often to fold the entire buffer and
  6541. then dive into the tree. This method has the disadvantage, that
  6542. the previous location will be folded, which may not be what you
  6543. want.
  6544. This command works around this by showing a copy of the current
  6545. buffer in an indirect buffer, in overview mode. You can dive
  6546. into the tree in that copy, use org-occur and incremental search
  6547. to find a location. When pressing RET or `Q', the command
  6548. returns to the original buffer in which the visibility is still
  6549. unchanged. After RET it will also jump to the location selected
  6550. in the indirect buffer and expose the headline hierarchy above.
  6551. With a prefix argument, use the alternative interface: e.g., if
  6552. `org-goto-interface' is `outline' use `outline-path-completion'."
  6553. (interactive "P")
  6554. (org-goto-map)
  6555. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6556. (org-refile-use-outline-path t)
  6557. (org-refile-target-verify-function nil)
  6558. (interface
  6559. (if (not alternative-interface)
  6560. org-goto-interface
  6561. (if (eq org-goto-interface 'outline)
  6562. 'outline-path-completion
  6563. 'outline)))
  6564. (org-goto-start-pos (point))
  6565. (selected-point
  6566. (if (eq interface 'outline)
  6567. (car (org-get-location (current-buffer) org-goto-help))
  6568. (let ((pa (org-refile-get-location "Goto")))
  6569. (org-refile-check-position pa)
  6570. (nth 3 pa)))))
  6571. (if selected-point
  6572. (progn
  6573. (org-mark-ring-push org-goto-start-pos)
  6574. (goto-char selected-point)
  6575. (when (or (outline-invisible-p) (org-invisible-p2))
  6576. (org-show-context 'org-goto)))
  6577. (message "Quit"))))
  6578. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6579. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6580. (defvar org-goto-local-auto-isearch-map) ; defined below
  6581. (defun org-get-location (_buf help)
  6582. "Let the user select a location in current buffer.
  6583. This function uses a recursive edit. It returns the selected position
  6584. or nil."
  6585. (org-no-popups
  6586. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6587. (isearch-hide-immediately nil)
  6588. (isearch-search-fun-function
  6589. (lambda () 'org-goto-local-search-headings))
  6590. (org-goto-selected-point org-goto-exit-command))
  6591. (save-excursion
  6592. (save-window-excursion
  6593. (delete-other-windows)
  6594. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6595. (pop-to-buffer-same-window
  6596. (condition-case nil
  6597. (make-indirect-buffer (current-buffer) "*org-goto*")
  6598. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6599. (with-output-to-temp-buffer "*Org Help*"
  6600. (princ (format help (if org-goto-auto-isearch
  6601. " Just type for auto-isearch."
  6602. " n/p/f/b/u to navigate, q to quit."))))
  6603. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6604. (setq buffer-read-only nil)
  6605. (let ((org-startup-truncated t)
  6606. (org-startup-folded nil)
  6607. (org-startup-align-all-tables nil))
  6608. (org-mode)
  6609. (org-overview))
  6610. (setq buffer-read-only t)
  6611. (if (and (boundp 'org-goto-start-pos)
  6612. (integer-or-marker-p org-goto-start-pos))
  6613. (progn (goto-char org-goto-start-pos)
  6614. (when (outline-invisible-p)
  6615. (org-show-set-visibility 'lineage)))
  6616. (goto-char (point-min)))
  6617. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6618. (message "Select location and press RET")
  6619. (use-local-map org-goto-map)
  6620. (recursive-edit)))
  6621. (kill-buffer "*org-goto*")
  6622. (cons org-goto-selected-point org-goto-exit-command))))
  6623. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6624. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6625. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6626. (if (fboundp 'isearch-other-control-char)
  6627. (progn
  6628. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6629. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6630. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6631. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6632. (define-key org-goto-local-auto-isearch-map [return] nil))
  6633. (defun org-goto-local-search-headings (string bound noerror)
  6634. "Search and make sure that any matches are in headlines."
  6635. (catch 'return
  6636. (while (if isearch-forward
  6637. (search-forward string bound noerror)
  6638. (search-backward string bound noerror))
  6639. (when (save-match-data
  6640. (and (save-excursion
  6641. (beginning-of-line)
  6642. (looking-at org-complex-heading-regexp))
  6643. (or (not (match-beginning 5))
  6644. (< (point) (match-beginning 5)))))
  6645. (throw 'return (point))))))
  6646. (defun org-goto-local-auto-isearch ()
  6647. "Start isearch."
  6648. (interactive)
  6649. (goto-char (point-min))
  6650. (let ((keys (this-command-keys)))
  6651. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6652. (isearch-mode t)
  6653. (isearch-process-search-char (string-to-char keys)))))
  6654. (defun org-goto-ret (&optional _arg)
  6655. "Finish `org-goto' by going to the new location."
  6656. (interactive "P")
  6657. (setq org-goto-selected-point (point))
  6658. (setq org-goto-exit-command 'return)
  6659. (throw 'exit nil))
  6660. (defun org-goto-left ()
  6661. "Finish `org-goto' by going to the new location."
  6662. (interactive)
  6663. (if (org-at-heading-p)
  6664. (progn
  6665. (beginning-of-line 1)
  6666. (setq org-goto-selected-point (point)
  6667. org-goto-exit-command 'left)
  6668. (throw 'exit nil))
  6669. (user-error "Not on a heading")))
  6670. (defun org-goto-right ()
  6671. "Finish `org-goto' by going to the new location."
  6672. (interactive)
  6673. (if (org-at-heading-p)
  6674. (progn
  6675. (setq org-goto-selected-point (point)
  6676. org-goto-exit-command 'right)
  6677. (throw 'exit nil))
  6678. (user-error "Not on a heading")))
  6679. (defun org-goto-quit ()
  6680. "Finish `org-goto' without cursor motion."
  6681. (interactive)
  6682. (setq org-goto-selected-point nil)
  6683. (setq org-goto-exit-command 'quit)
  6684. (throw 'exit nil))
  6685. ;;; Indirect buffer display of subtrees
  6686. (defvar org-indirect-dedicated-frame nil
  6687. "This is the frame being used for indirect tree display.")
  6688. (defvar org-last-indirect-buffer nil)
  6689. (defun org-tree-to-indirect-buffer (&optional arg)
  6690. "Create indirect buffer and narrow it to current subtree.
  6691. With a numerical prefix ARG, go up to this level and then take that tree.
  6692. If ARG is negative, go up that many levels.
  6693. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6694. indirect buffer previously made with this command, to avoid proliferation of
  6695. indirect buffers. However, when you call the command with a \
  6696. `\\[universal-argument]' prefix, or
  6697. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6698. so that you can work with several indirect buffers at the same time. If
  6699. `org-indirect-buffer-display' is `dedicated-frame', the \
  6700. `\\[universal-argument]' prefix also
  6701. requests that a new frame be made for the new buffer, so that the dedicated
  6702. frame is not changed."
  6703. (interactive "P")
  6704. (let ((cbuf (current-buffer))
  6705. (cwin (selected-window))
  6706. (pos (point))
  6707. beg end level heading ibuf)
  6708. (save-excursion
  6709. (org-back-to-heading t)
  6710. (when (numberp arg)
  6711. (setq level (org-outline-level))
  6712. (when (< arg 0) (setq arg (+ level arg)))
  6713. (while (> (setq level (org-outline-level)) arg)
  6714. (org-up-heading-safe)))
  6715. (setq beg (point)
  6716. heading (org-get-heading 'no-tags))
  6717. (org-end-of-subtree t t)
  6718. (when (org-at-heading-p) (backward-char 1))
  6719. (setq end (point)))
  6720. (when (and (buffer-live-p org-last-indirect-buffer)
  6721. (not (eq org-indirect-buffer-display 'new-frame))
  6722. (not arg))
  6723. (kill-buffer org-last-indirect-buffer))
  6724. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6725. org-last-indirect-buffer ibuf)
  6726. (cond
  6727. ((or (eq org-indirect-buffer-display 'new-frame)
  6728. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6729. (select-frame (make-frame))
  6730. (delete-other-windows)
  6731. (pop-to-buffer-same-window ibuf)
  6732. (org-set-frame-title heading))
  6733. ((eq org-indirect-buffer-display 'dedicated-frame)
  6734. (raise-frame
  6735. (select-frame (or (and org-indirect-dedicated-frame
  6736. (frame-live-p org-indirect-dedicated-frame)
  6737. org-indirect-dedicated-frame)
  6738. (setq org-indirect-dedicated-frame (make-frame)))))
  6739. (delete-other-windows)
  6740. (pop-to-buffer-same-window ibuf)
  6741. (org-set-frame-title (concat "Indirect: " heading)))
  6742. ((eq org-indirect-buffer-display 'current-window)
  6743. (pop-to-buffer-same-window ibuf))
  6744. ((eq org-indirect-buffer-display 'other-window)
  6745. (pop-to-buffer ibuf))
  6746. (t (error "Invalid value")))
  6747. (narrow-to-region beg end)
  6748. (outline-show-all)
  6749. (goto-char pos)
  6750. (run-hook-with-args 'org-cycle-hook 'all)
  6751. (and (window-live-p cwin) (select-window cwin))))
  6752. (defun org-get-indirect-buffer (&optional buffer heading)
  6753. (setq buffer (or buffer (current-buffer)))
  6754. (let ((n 1) (base (buffer-name buffer)) bname)
  6755. (while (buffer-live-p
  6756. (get-buffer
  6757. (setq bname
  6758. (concat base "-"
  6759. (if heading (concat heading "-" (number-to-string n))
  6760. (number-to-string n))))))
  6761. (setq n (1+ n)))
  6762. (condition-case nil
  6763. (make-indirect-buffer buffer bname 'clone)
  6764. (error (make-indirect-buffer buffer bname)))))
  6765. (defun org-set-frame-title (title)
  6766. "Set the title of the current frame to the string TITLE."
  6767. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6768. ;;;; Structure editing
  6769. ;;; Inserting headlines
  6770. (defun org--line-empty-p (n)
  6771. "Is the Nth next line empty?
  6772. Counts the current line as N = 1 and the previous line as N = 0;
  6773. see `beginning-of-line'."
  6774. (save-excursion
  6775. (and (not (bobp))
  6776. (or (beginning-of-line n) t)
  6777. (save-match-data
  6778. (looking-at "[ \t]*$")))))
  6779. (defun org-previous-line-empty-p ()
  6780. "Is the previous line a blank line?
  6781. When NEXT is non-nil, check the next line instead."
  6782. (org--line-empty-p 0))
  6783. (defun org-next-line-empty-p ()
  6784. "Is the previous line a blank line?
  6785. When NEXT is non-nil, check the next line instead."
  6786. (org--line-empty-p 2))
  6787. (defun org--blank-before-heading-p (&optional parent)
  6788. "Non-nil when an empty line should precede a new heading here.
  6789. When optional argument PARENT is non-nil, consider parent
  6790. headline instead of current one."
  6791. (pcase (assq 'heading org-blank-before-new-entry)
  6792. (`(heading . auto)
  6793. (save-excursion
  6794. (org-with-limited-levels
  6795. (unless (and (org-before-first-heading-p)
  6796. (not (outline-next-heading)))
  6797. (org-back-to-heading t)
  6798. (when parent (org-up-heading-safe))
  6799. (cond ((not (bobp))
  6800. (org-previous-line-empty-p))
  6801. ((outline-next-heading)
  6802. (org-previous-line-empty-p))
  6803. ;; Ignore trailing spaces on last buffer line.
  6804. ((progn (skip-chars-backward " \t") (bolp))
  6805. (org-previous-line-empty-p))
  6806. (t nil))))))
  6807. (`(heading . ,value) value)
  6808. (_ nil)))
  6809. (defun org-insert-heading (&optional arg invisible-ok top)
  6810. "Insert a new heading or an item with the same depth at point.
  6811. If point is at the beginning of a heading, insert a new heading
  6812. or a new headline above the current one. When at the beginning
  6813. of a regular line of text, turn it into a heading.
  6814. If point is in the middle of a line, split it and create a new
  6815. headline with the text in the current line after point (see
  6816. `org-M-RET-may-split-line' on how to modify this behavior). As
  6817. a special case, on a headline, splitting can only happen on the
  6818. title itself. E.g., this excludes breaking stars or tags.
  6819. With a `\\[universal-argument]' prefix, set \
  6820. `org-insert-heading-respect-content' to
  6821. a non-nil value for the duration of the command. This forces the
  6822. insertion of a heading after the current subtree, independently
  6823. on the location of point.
  6824. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6825. insert the heading at the end of the tree
  6826. above the current heading. For example, if point is within a
  6827. 2nd-level heading, then it will insert a 2nd-level heading at
  6828. the end of the 1st-level parent subtree.
  6829. When INVISIBLE-OK is set, stop at invisible headlines when going
  6830. back. This is important for non-interactive uses of the
  6831. command.
  6832. When optional argument TOP is non-nil, insert a level 1 heading,
  6833. unconditionally."
  6834. (interactive "P")
  6835. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6836. (level (org-current-level))
  6837. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6838. (cond
  6839. ((or org-insert-heading-respect-content
  6840. (member arg '((4) (16)))
  6841. (and (not invisible-ok)
  6842. (invisible-p (max (1- (point)) (point-min)))))
  6843. ;; Position point at the location of insertion.
  6844. (if (not level) ;before first headline
  6845. (org-with-limited-levels (outline-next-heading))
  6846. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6847. ;; is nil.
  6848. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6849. (cond ((equal arg '(16))
  6850. (org-up-heading-safe)
  6851. (org-end-of-subtree t t))
  6852. (t
  6853. (org-end-of-subtree t t))))
  6854. (unless (bolp) (insert "\n")) ;ensure final newline
  6855. (unless (and blank? (org-previous-line-empty-p))
  6856. (org-N-empty-lines-before-current (if blank? 1 0)))
  6857. (insert stars " \n")
  6858. (forward-char -1))
  6859. ;; At a headline...
  6860. ((org-at-heading-p)
  6861. (cond ((bolp)
  6862. (when blank? (save-excursion (insert "\n")))
  6863. (save-excursion (insert stars " \n"))
  6864. (unless (and blank? (org-previous-line-empty-p))
  6865. (org-N-empty-lines-before-current (if blank? 1 0)))
  6866. (end-of-line))
  6867. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6868. (org-match-line org-complex-heading-regexp)
  6869. (org-pos-in-match-range (point) 4))
  6870. ;; Grab the text that should moved to the new headline.
  6871. ;; Preserve tags.
  6872. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6873. (if (looking-at "[ \t]*$") (replace-match "")
  6874. (org-set-tags nil t))
  6875. (end-of-line)
  6876. (when blank? (insert "\n"))
  6877. (insert "\n" stars " ")
  6878. (when (org-string-nw-p split) (insert split))
  6879. (when (eobp) (save-excursion (insert "\n")))))
  6880. (t
  6881. (end-of-line)
  6882. (when blank? (insert "\n"))
  6883. (insert "\n" stars " ")
  6884. (when (eobp) (save-excursion (insert "\n"))))))
  6885. ;; On regular text, turn line into a headline or split, if
  6886. ;; appropriate.
  6887. ((bolp)
  6888. (insert stars " ")
  6889. (unless (and blank? (org-previous-line-empty-p))
  6890. (org-N-empty-lines-before-current (if blank? 1 0))))
  6891. (t
  6892. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6893. (end-of-line))
  6894. (insert "\n" stars " ")
  6895. (unless (and blank? (org-previous-line-empty-p))
  6896. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6897. (run-hooks 'org-insert-heading-hook))
  6898. (defun org-N-empty-lines-before-current (n)
  6899. "Make the number of empty lines before current exactly N.
  6900. So this will delete or add empty lines."
  6901. (let ((column (current-column)))
  6902. (beginning-of-line)
  6903. (unless (bobp)
  6904. (let ((start (save-excursion
  6905. (skip-chars-backward " \r\t\n")
  6906. (line-end-position))))
  6907. (delete-region start (line-end-position 0))))
  6908. (insert (make-string n ?\n))
  6909. (move-to-column column)))
  6910. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6911. "Return the heading of the current entry, without the stars.
  6912. When NO-TAGS is non-nil, don't include tags.
  6913. When NO-TODO is non-nil, don't include TODO keywords.
  6914. When NO-PRIORITY is non-nil, don't include priority cookie.
  6915. When NO-COMMENT is non-nil, don't include COMMENT string."
  6916. (save-excursion
  6917. (org-back-to-heading t)
  6918. (let ((case-fold-search nil))
  6919. (looking-at org-complex-heading-regexp)
  6920. (let ((todo (and (not no-todo) (match-string 2)))
  6921. (priority (and (not no-priority) (match-string 3)))
  6922. (headline (pcase (match-string 4)
  6923. (`nil "")
  6924. ((and (guard no-comment) h)
  6925. (replace-regexp-in-string
  6926. (eval-when-compile
  6927. (format "\\`%s[ \t]+" org-comment-string))
  6928. "" h))
  6929. (h h)))
  6930. (tags (and (not no-tags) (match-string 5))))
  6931. (mapconcat #'identity
  6932. (delq nil (list todo priority headline tags))
  6933. " ")))))
  6934. (defvar orgstruct-mode) ; defined below
  6935. (defun org-heading-components ()
  6936. "Return the components of the current heading.
  6937. This is a list with the following elements:
  6938. - the level as an integer
  6939. - the reduced level, different if `org-odd-levels-only' is set.
  6940. - the TODO keyword, or nil
  6941. - the priority character, like ?A, or nil if no priority is given
  6942. - the headline text itself, or the tags string if no headline text
  6943. - the tags string, or nil."
  6944. (save-excursion
  6945. (org-back-to-heading t)
  6946. (when (let (case-fold-search)
  6947. (looking-at
  6948. (if orgstruct-mode
  6949. org-heading-regexp
  6950. org-complex-heading-regexp)))
  6951. (if orgstruct-mode
  6952. (list (length (match-string 1))
  6953. (org-reduced-level (length (match-string 1)))
  6954. nil
  6955. nil
  6956. (match-string 2)
  6957. nil)
  6958. (list (length (match-string 1))
  6959. (org-reduced-level (length (match-string 1)))
  6960. (match-string-no-properties 2)
  6961. (and (match-end 3) (aref (match-string 3) 2))
  6962. (match-string-no-properties 4)
  6963. (match-string-no-properties 5))))))
  6964. (defun org-get-entry ()
  6965. "Get the entry text, after heading, entire subtree."
  6966. (save-excursion
  6967. (org-back-to-heading t)
  6968. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6969. (defun org-edit-headline (&optional heading)
  6970. "Edit the current headline.
  6971. Set it to HEADING when provided."
  6972. (interactive)
  6973. (org-with-wide-buffer
  6974. (org-back-to-heading t)
  6975. (let ((case-fold-search nil))
  6976. (when (looking-at org-complex-heading-regexp)
  6977. (let* ((old (match-string-no-properties 4))
  6978. (new (save-match-data
  6979. (org-trim (or heading (read-string "Edit: " old))))))
  6980. (unless (equal old new)
  6981. (if old (replace-match new t t nil 4)
  6982. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6983. (insert " " new))
  6984. (org-set-tags nil t)
  6985. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6986. (defun org-insert-heading-after-current ()
  6987. "Insert a new heading with same level as current, after current subtree."
  6988. (interactive)
  6989. (org-back-to-heading)
  6990. (org-insert-heading)
  6991. (org-move-subtree-down)
  6992. (end-of-line 1))
  6993. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6994. "Insert heading with `org-insert-heading-respect-content' set to t."
  6995. (interactive)
  6996. (org-insert-heading '(4) invisible-ok))
  6997. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6998. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6999. (interactive)
  7000. (org-insert-todo-heading force-state '(4)))
  7001. (defun org-insert-todo-heading (arg &optional force-heading)
  7002. "Insert a new heading with the same level and TODO state as current heading.
  7003. If the heading has no TODO state, or if the state is DONE, use
  7004. the first state (TODO by default). Also with one prefix arg,
  7005. force first state. With two prefix args, force inserting at the
  7006. end of the parent subtree.
  7007. When called at a plain list item, insert a new item with an
  7008. unchecked check box."
  7009. (interactive "P")
  7010. (when (or force-heading (not (org-insert-item 'checkbox)))
  7011. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7012. force-heading))
  7013. (save-excursion
  7014. (org-back-to-heading)
  7015. (outline-previous-heading)
  7016. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7017. (let* ((new-mark-x
  7018. (if (or (equal arg '(4))
  7019. (not (match-beginning 2))
  7020. (member (match-string 2) org-done-keywords))
  7021. (car org-todo-keywords-1)
  7022. (match-string 2)))
  7023. (new-mark
  7024. (or
  7025. (run-hook-with-args-until-success
  7026. 'org-todo-get-default-hook new-mark-x nil)
  7027. new-mark-x)))
  7028. (beginning-of-line 1)
  7029. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7030. (if org-treat-insert-todo-heading-as-state-change
  7031. (org-todo new-mark)
  7032. (insert new-mark " "))))
  7033. (when org-provide-todo-statistics
  7034. (org-update-parent-todo-statistics))))
  7035. (defun org-insert-subheading (arg)
  7036. "Insert a new subheading and demote it.
  7037. Works for outline headings and for plain lists alike."
  7038. (interactive "P")
  7039. (org-insert-heading arg)
  7040. (cond
  7041. ((org-at-heading-p) (org-do-demote))
  7042. ((org-at-item-p) (org-indent-item))))
  7043. (defun org-insert-todo-subheading (arg)
  7044. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7045. Works for outline headings and for plain lists alike."
  7046. (interactive "P")
  7047. (org-insert-todo-heading arg)
  7048. (cond
  7049. ((org-at-heading-p) (org-do-demote))
  7050. ((org-at-item-p) (org-indent-item))))
  7051. ;;; Promotion and Demotion
  7052. (defvar org-after-demote-entry-hook nil
  7053. "Hook run after an entry has been demoted.
  7054. The cursor will be at the beginning of the entry.
  7055. When a subtree is being demoted, the hook will be called for each node.")
  7056. (defvar org-after-promote-entry-hook nil
  7057. "Hook run after an entry has been promoted.
  7058. The cursor will be at the beginning of the entry.
  7059. When a subtree is being promoted, the hook will be called for each node.")
  7060. (defun org-promote-subtree ()
  7061. "Promote the entire subtree.
  7062. See also `org-promote'."
  7063. (interactive)
  7064. (save-excursion
  7065. (org-with-limited-levels (org-map-tree 'org-promote)))
  7066. (org-fix-position-after-promote))
  7067. (defun org-demote-subtree ()
  7068. "Demote the entire subtree.
  7069. See `org-demote' and `org-promote'."
  7070. (interactive)
  7071. (save-excursion
  7072. (org-with-limited-levels (org-map-tree 'org-demote)))
  7073. (org-fix-position-after-promote))
  7074. (defun org-do-promote ()
  7075. "Promote the current heading higher up the tree.
  7076. If the region is active in `transient-mark-mode', promote all
  7077. headings in the region."
  7078. (interactive)
  7079. (save-excursion
  7080. (if (org-region-active-p)
  7081. (org-map-region 'org-promote (region-beginning) (region-end))
  7082. (org-promote)))
  7083. (org-fix-position-after-promote))
  7084. (defun org-do-demote ()
  7085. "Demote the current heading lower down the tree.
  7086. If the region is active in `transient-mark-mode', demote all
  7087. headings in the region."
  7088. (interactive)
  7089. (save-excursion
  7090. (if (org-region-active-p)
  7091. (org-map-region 'org-demote (region-beginning) (region-end))
  7092. (org-demote)))
  7093. (org-fix-position-after-promote))
  7094. (defun org-fix-position-after-promote ()
  7095. "Fix cursor position and indentation after demoting/promoting."
  7096. (let ((pos (point)))
  7097. (when (save-excursion
  7098. (beginning-of-line)
  7099. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7100. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7101. (cond ((eobp) (insert " "))
  7102. ((eolp) (insert " "))
  7103. ((equal (char-after) ?\s) (forward-char 1))))))
  7104. (defun org-current-level ()
  7105. "Return the level of the current entry, or nil if before the first headline.
  7106. The level is the number of stars at the beginning of the
  7107. headline. Use `org-reduced-level' to remove the effect of
  7108. `org-odd-levels'. Unlike to `org-outline-level', this function
  7109. ignores inlinetasks."
  7110. (let ((level (org-with-limited-levels (org-outline-level))))
  7111. (and (> level 0) level)))
  7112. (defun org-get-previous-line-level ()
  7113. "Return the outline depth of the last headline before the current line.
  7114. Returns 0 for the first headline in the buffer, and nil if before the
  7115. first headline."
  7116. (and (org-current-level)
  7117. (or (and (/= (line-beginning-position) (point-min))
  7118. (save-excursion (beginning-of-line 0) (org-current-level)))
  7119. 0)))
  7120. (defun org-reduced-level (l)
  7121. "Compute the effective level of a heading.
  7122. This takes into account the setting of `org-odd-levels-only'."
  7123. (cond
  7124. ((zerop l) 0)
  7125. (org-odd-levels-only (1+ (floor (/ l 2))))
  7126. (t l)))
  7127. (defun org-level-increment ()
  7128. "Return the number of stars that will be added or removed at a
  7129. time to headlines when structure editing, based on the value of
  7130. `org-odd-levels-only'."
  7131. (if org-odd-levels-only 2 1))
  7132. (defun org-get-valid-level (level &optional change)
  7133. "Rectify a level change under the influence of `org-odd-levels-only'.
  7134. LEVEL is a current level, CHANGE is by how much the level should
  7135. be modified. Even if CHANGE is nil, LEVEL may be returned
  7136. modified because even level numbers will become the next higher
  7137. odd number. Returns values greater than 0."
  7138. (if org-odd-levels-only
  7139. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7140. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7141. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7142. (max 1 (+ level (or change 0)))))
  7143. (defun org-promote ()
  7144. "Promote the current heading higher up the tree."
  7145. (org-with-wide-buffer
  7146. (org-back-to-heading t)
  7147. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7148. after-change-functions))
  7149. (level (save-match-data (funcall outline-level)))
  7150. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7151. (diff (abs (- level (length up-head) -1))))
  7152. (cond
  7153. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7154. (replace-match "# " nil t))
  7155. ((= level 1)
  7156. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7157. (t (replace-match up-head nil t)))
  7158. (unless (= level 1)
  7159. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7160. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7161. (run-hooks 'org-after-promote-entry-hook))))
  7162. (defun org-demote ()
  7163. "Demote the current heading lower down the tree."
  7164. (org-with-wide-buffer
  7165. (org-back-to-heading t)
  7166. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7167. after-change-functions))
  7168. (level (save-match-data (funcall outline-level)))
  7169. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7170. (diff (abs (- level (length down-head) -1))))
  7171. (replace-match down-head nil t)
  7172. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7173. (when org-adapt-indentation (org-fixup-indentation diff))
  7174. (run-hooks 'org-after-demote-entry-hook))))
  7175. (defun org-cycle-level ()
  7176. "Cycle the level of an empty headline through possible states.
  7177. This goes first to child, then to parent, level, then up the hierarchy.
  7178. After top level, it switches back to sibling level."
  7179. (interactive)
  7180. (let ((org-adapt-indentation nil))
  7181. (when (org-point-at-end-of-empty-headline)
  7182. (setq this-command 'org-cycle-level) ; Only needed for caching
  7183. (let ((cur-level (org-current-level))
  7184. (prev-level (org-get-previous-line-level)))
  7185. (cond
  7186. ;; If first headline in file, promote to top-level.
  7187. ((= prev-level 0)
  7188. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7189. do (org-do-promote)))
  7190. ;; If same level as prev, demote one.
  7191. ((= prev-level cur-level)
  7192. (org-do-demote))
  7193. ;; If parent is top-level, promote to top level if not already.
  7194. ((= prev-level 1)
  7195. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7196. do (org-do-promote)))
  7197. ;; If top-level, return to prev-level.
  7198. ((= cur-level 1)
  7199. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7200. do (org-do-demote)))
  7201. ;; If less than prev-level, promote one.
  7202. ((< cur-level prev-level)
  7203. (org-do-promote))
  7204. ;; If deeper than prev-level, promote until higher than
  7205. ;; prev-level.
  7206. ((> cur-level prev-level)
  7207. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7208. do (org-do-promote))))
  7209. t))))
  7210. (defun org-map-tree (fun)
  7211. "Call FUN for every heading underneath the current one."
  7212. (org-back-to-heading t)
  7213. (let ((level (funcall outline-level)))
  7214. (save-excursion
  7215. (funcall fun)
  7216. (while (and (progn
  7217. (outline-next-heading)
  7218. (> (funcall outline-level) level))
  7219. (not (eobp)))
  7220. (funcall fun)))))
  7221. (defun org-map-region (fun beg end)
  7222. "Call FUN for every heading between BEG and END."
  7223. (let ((org-ignore-region t))
  7224. (save-excursion
  7225. (setq end (copy-marker end))
  7226. (goto-char beg)
  7227. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7228. (< (point) end))
  7229. (funcall fun))
  7230. (while (and (progn
  7231. (outline-next-heading)
  7232. (< (point) end))
  7233. (not (eobp)))
  7234. (funcall fun)))))
  7235. (defun org-fixup-indentation (diff)
  7236. "Change the indentation in the current entry by DIFF.
  7237. DIFF is an integer. Indentation is done according to the
  7238. following rules:
  7239. - Planning information and property drawers are always indented
  7240. according to the new level of the headline;
  7241. - Footnote definitions and their contents are ignored;
  7242. - Inlinetasks' boundaries are not shifted;
  7243. - Empty lines are ignored;
  7244. - Other lines' indentation are shifted by DIFF columns, unless
  7245. it would introduce a structural change in the document, in
  7246. which case no shifting is done at all.
  7247. Assume point is at a heading or an inlinetask beginning."
  7248. (org-with-wide-buffer
  7249. (narrow-to-region (line-beginning-position)
  7250. (save-excursion
  7251. (if (org-with-limited-levels (org-at-heading-p))
  7252. (org-with-limited-levels (outline-next-heading))
  7253. (org-inlinetask-goto-end))
  7254. (point)))
  7255. (forward-line)
  7256. ;; Indent properly planning info and property drawer.
  7257. (when (looking-at-p org-planning-line-re)
  7258. (org-indent-line)
  7259. (forward-line))
  7260. (when (looking-at org-property-drawer-re)
  7261. (goto-char (match-end 0))
  7262. (forward-line)
  7263. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7264. (catch 'no-shift
  7265. (when (zerop diff) (throw 'no-shift nil))
  7266. ;; If DIFF is negative, first check if a shift is possible at all
  7267. ;; (e.g., it doesn't break structure). This can only happen if
  7268. ;; some contents are not properly indented.
  7269. (let ((case-fold-search t))
  7270. (when (< diff 0)
  7271. (let ((diff (- diff))
  7272. (forbidden-re (concat org-outline-regexp
  7273. "\\|"
  7274. (substring org-footnote-definition-re 1))))
  7275. (save-excursion
  7276. (while (not (eobp))
  7277. (cond
  7278. ((looking-at-p "[ \t]*$") (forward-line))
  7279. ((and (looking-at-p org-footnote-definition-re)
  7280. (let ((e (org-element-at-point)))
  7281. (and (eq (org-element-type e) 'footnote-definition)
  7282. (goto-char (org-element-property :end e))))))
  7283. ((looking-at-p org-outline-regexp) (forward-line))
  7284. ;; Give up if shifting would move before column 0 or
  7285. ;; if it would introduce a headline or a footnote
  7286. ;; definition.
  7287. (t
  7288. (skip-chars-forward " \t")
  7289. (let ((ind (current-column)))
  7290. (when (or (< ind diff)
  7291. (and (= ind diff) (looking-at-p forbidden-re)))
  7292. (throw 'no-shift nil)))
  7293. ;; Ignore contents of example blocks and source
  7294. ;; blocks if their indentation is meant to be
  7295. ;; preserved. Jump to block's closing line.
  7296. (beginning-of-line)
  7297. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7298. (let ((e (org-element-at-point)))
  7299. (and (memq (org-element-type e)
  7300. '(example-block src-block))
  7301. (or org-src-preserve-indentation
  7302. (org-element-property :preserve-indent e))
  7303. (goto-char (org-element-property :end e))
  7304. (progn (skip-chars-backward " \r\t\n")
  7305. (beginning-of-line)
  7306. t))))
  7307. (forward-line))))))))
  7308. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7309. ;; by DIFF. Also skip contents of source or example blocks
  7310. ;; when indentation is meant to be preserved.
  7311. (while (not (eobp))
  7312. (cond
  7313. ((and (looking-at-p org-footnote-definition-re)
  7314. (let ((e (org-element-at-point)))
  7315. (and (eq (org-element-type e) 'footnote-definition)
  7316. (goto-char (org-element-property :end e))))))
  7317. ((looking-at-p org-outline-regexp) (forward-line))
  7318. ((looking-at-p "[ \t]*$") (forward-line))
  7319. (t
  7320. (indent-line-to (+ (org-get-indentation) diff))
  7321. (beginning-of-line)
  7322. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7323. (let ((e (org-element-at-point)))
  7324. (and (memq (org-element-type e)
  7325. '(example-block src-block))
  7326. (or org-src-preserve-indentation
  7327. (org-element-property :preserve-indent e))
  7328. (goto-char (org-element-property :end e))
  7329. (progn (skip-chars-backward " \r\t\n")
  7330. (beginning-of-line)
  7331. t))))
  7332. (forward-line)))))))))
  7333. (defun org-convert-to-odd-levels ()
  7334. "Convert an Org file with all levels allowed to one with odd levels.
  7335. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7336. level 5 etc."
  7337. (interactive)
  7338. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7339. (let ((outline-level 'org-outline-level)
  7340. (org-odd-levels-only nil) n)
  7341. (save-excursion
  7342. (goto-char (point-min))
  7343. (while (re-search-forward "^\\*\\*+ " nil t)
  7344. (setq n (- (length (match-string 0)) 2))
  7345. (while (>= (setq n (1- n)) 0)
  7346. (org-demote))
  7347. (end-of-line 1))))))
  7348. (defun org-convert-to-oddeven-levels ()
  7349. "Convert an Org file with only odd levels to one with odd/even levels.
  7350. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7351. file contains a section with an even level, conversion would
  7352. destroy the structure of the file. An error is signaled in this
  7353. case."
  7354. (interactive)
  7355. (goto-char (point-min))
  7356. ;; First check if there are no even levels
  7357. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7358. (org-show-set-visibility 'canonical)
  7359. (error "Not all levels are odd in this file. Conversion not possible"))
  7360. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7361. (let ((outline-regexp org-outline-regexp)
  7362. (outline-level 'org-outline-level)
  7363. (org-odd-levels-only nil) n)
  7364. (save-excursion
  7365. (goto-char (point-min))
  7366. (while (re-search-forward "^\\*\\*+ " nil t)
  7367. (setq n (/ (1- (length (match-string 0))) 2))
  7368. (while (>= (setq n (1- n)) 0)
  7369. (org-promote))
  7370. (end-of-line 1))))))
  7371. (defun org-tr-level (n)
  7372. "Make N odd if required."
  7373. (if org-odd-levels-only (1+ (/ n 2)) n))
  7374. ;;; Vertical tree motion, cutting and pasting of subtrees
  7375. (defun org-move-subtree-up (&optional arg)
  7376. "Move the current subtree up past ARG headlines of the same level."
  7377. (interactive "p")
  7378. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7379. (defun org-move-subtree-down (&optional arg)
  7380. "Move the current subtree down past ARG headlines of the same level."
  7381. (interactive "p")
  7382. (setq arg (prefix-numeric-value arg))
  7383. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7384. 'org-get-last-sibling))
  7385. (ins-point (make-marker))
  7386. (cnt (abs arg))
  7387. (col (current-column))
  7388. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7389. ;; Select the tree
  7390. (org-back-to-heading)
  7391. (setq beg0 (point))
  7392. (save-excursion
  7393. (setq ne-beg (org-back-over-empty-lines))
  7394. (setq beg (point)))
  7395. (save-match-data
  7396. (save-excursion (outline-end-of-heading)
  7397. (setq folded (outline-invisible-p)))
  7398. (progn (org-end-of-subtree nil t)
  7399. (unless (eobp) (backward-char))))
  7400. (outline-next-heading)
  7401. (setq ne-end (org-back-over-empty-lines))
  7402. (setq end (point))
  7403. (goto-char beg0)
  7404. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7405. ;; include less whitespace
  7406. (save-excursion
  7407. (goto-char beg)
  7408. (forward-line (- ne-beg ne-end))
  7409. (setq beg (point))))
  7410. ;; Find insertion point, with error handling
  7411. (while (> cnt 0)
  7412. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7413. (progn (goto-char beg0)
  7414. (user-error "Cannot move past superior level or buffer limit")))
  7415. (setq cnt (1- cnt)))
  7416. (when (> arg 0)
  7417. ;; Moving forward - still need to move over subtree
  7418. (org-end-of-subtree t t)
  7419. (save-excursion
  7420. (org-back-over-empty-lines)
  7421. (or (bolp) (newline))))
  7422. (setq ne-ins (org-back-over-empty-lines))
  7423. (move-marker ins-point (point))
  7424. (setq txt (buffer-substring beg end))
  7425. (org-save-markers-in-region beg end)
  7426. (delete-region beg end)
  7427. (org-remove-empty-overlays-at beg)
  7428. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7429. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7430. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7431. (let ((bbb (point)))
  7432. (insert-before-markers txt)
  7433. (org-reinstall-markers-in-region bbb)
  7434. (move-marker ins-point bbb))
  7435. (or (bolp) (insert "\n"))
  7436. (setq ins-end (point))
  7437. (goto-char ins-point)
  7438. (org-skip-whitespace)
  7439. (when (and (< arg 0)
  7440. (org-first-sibling-p)
  7441. (> ne-ins ne-beg))
  7442. ;; Move whitespace back to beginning
  7443. (save-excursion
  7444. (goto-char ins-end)
  7445. (let ((kill-whole-line t))
  7446. (kill-line (- ne-ins ne-beg)) (point)))
  7447. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7448. (move-marker ins-point nil)
  7449. (if folded
  7450. (outline-hide-subtree)
  7451. (org-show-entry)
  7452. (org-show-children)
  7453. (org-cycle-hide-drawers 'children))
  7454. (org-clean-visibility-after-subtree-move)
  7455. ;; move back to the initial column we were at
  7456. (move-to-column col)))
  7457. (defvar org-subtree-clip ""
  7458. "Clipboard for cut and paste of subtrees.
  7459. This is actually only a copy of the kill, because we use the normal kill
  7460. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7461. (defvar org-subtree-clip-folded nil
  7462. "Was the last copied subtree folded?
  7463. This is used to fold the tree back after pasting.")
  7464. (defun org-cut-subtree (&optional n)
  7465. "Cut the current subtree into the clipboard.
  7466. With prefix arg N, cut this many sequential subtrees.
  7467. This is a short-hand for marking the subtree and then cutting it."
  7468. (interactive "p")
  7469. (org-copy-subtree n 'cut))
  7470. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7471. "Copy the current subtree it in the clipboard.
  7472. With prefix arg N, copy this many sequential subtrees.
  7473. This is a short-hand for marking the subtree and then copying it.
  7474. If CUT is non-nil, actually cut the subtree.
  7475. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7476. of some markers in the region, even if CUT is non-nil. This is
  7477. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7478. (interactive "p")
  7479. (let (beg end folded (beg0 (point)))
  7480. (if (called-interactively-p 'any)
  7481. (org-back-to-heading nil) ; take what looks like a subtree
  7482. (org-back-to-heading t)) ; take what is really there
  7483. (setq beg (point))
  7484. (skip-chars-forward " \t\r\n")
  7485. (save-match-data
  7486. (if nosubtrees
  7487. (outline-next-heading)
  7488. (save-excursion (outline-end-of-heading)
  7489. (setq folded (outline-invisible-p)))
  7490. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7491. (org-end-of-subtree t t)))
  7492. ;; Include the end of an inlinetask
  7493. (when (and (featurep 'org-inlinetask)
  7494. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7495. "END[ \t]*$")))
  7496. (end-of-line))
  7497. (setq end (point))
  7498. (goto-char beg0)
  7499. (when (> end beg)
  7500. (setq org-subtree-clip-folded folded)
  7501. (when (or cut force-store-markers)
  7502. (org-save-markers-in-region beg end))
  7503. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7504. (setq org-subtree-clip (current-kill 0))
  7505. (message "%s: Subtree(s) with %d characters"
  7506. (if cut "Cut" "Copied")
  7507. (length org-subtree-clip)))))
  7508. (defun org-paste-subtree (&optional level tree for-yank remove)
  7509. "Paste the clipboard as a subtree, with modification of headline level.
  7510. The entire subtree is promoted or demoted in order to match a new headline
  7511. level.
  7512. If the cursor is at the beginning of a headline, the same level as
  7513. that headline is used to paste the tree.
  7514. If not, the new level is derived from the *visible* headings
  7515. before and after the insertion point, and taken to be the inferior headline
  7516. level of the two. So if the previous visible heading is level 3 and the
  7517. next is level 4 (or vice versa), level 4 will be used for insertion.
  7518. This makes sure that the subtree remains an independent subtree and does
  7519. not swallow low level entries.
  7520. You can also force a different level, either by using a numeric prefix
  7521. argument, or by inserting the heading marker by hand. For example, if the
  7522. cursor is after \"*****\", then the tree will be shifted to level 5.
  7523. If optional TREE is given, use this text instead of the kill ring.
  7524. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7525. move back over whitespace before inserting, and move point to the end of
  7526. the inserted text when done.
  7527. When REMOVE is non-nil, remove the subtree from the clipboard."
  7528. (interactive "P")
  7529. (setq tree (or tree (and kill-ring (current-kill 0))))
  7530. (unless (org-kill-is-subtree-p tree)
  7531. (user-error "%s"
  7532. (substitute-command-keys
  7533. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7534. (org-with-limited-levels
  7535. (let* ((visp (not (outline-invisible-p)))
  7536. (txt tree)
  7537. (^re_ "\\(\\*+\\)[ \t]*")
  7538. (old-level (if (string-match org-outline-regexp-bol txt)
  7539. (- (match-end 0) (match-beginning 0) 1)
  7540. -1))
  7541. (force-level (cond (level (prefix-numeric-value level))
  7542. ((and (looking-at "[ \t]*$")
  7543. (string-match
  7544. "^\\*+$" (buffer-substring
  7545. (point-at-bol) (point))))
  7546. (- (match-end 0) (match-beginning 0)))
  7547. ((and (bolp)
  7548. (looking-at org-outline-regexp))
  7549. (- (match-end 0) (point) 1))))
  7550. (previous-level (save-excursion
  7551. (condition-case nil
  7552. (progn
  7553. (outline-previous-visible-heading 1)
  7554. (if (looking-at ^re_)
  7555. (- (match-end 0) (match-beginning 0) 1)
  7556. 1))
  7557. (error 1))))
  7558. (next-level (save-excursion
  7559. (condition-case nil
  7560. (progn
  7561. (or (looking-at org-outline-regexp)
  7562. (outline-next-visible-heading 1))
  7563. (if (looking-at ^re_)
  7564. (- (match-end 0) (match-beginning 0) 1)
  7565. 1))
  7566. (error 1))))
  7567. (new-level (or force-level (max previous-level next-level)))
  7568. (shift (if (or (= old-level -1)
  7569. (= new-level -1)
  7570. (= old-level new-level))
  7571. 0
  7572. (- new-level old-level)))
  7573. (delta (if (> shift 0) -1 1))
  7574. (func (if (> shift 0) 'org-demote 'org-promote))
  7575. (org-odd-levels-only nil)
  7576. beg end newend)
  7577. ;; Remove the forced level indicator
  7578. (when force-level
  7579. (delete-region (point-at-bol) (point)))
  7580. ;; Paste
  7581. (beginning-of-line (if (bolp) 1 2))
  7582. (setq beg (point))
  7583. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7584. (insert-before-markers txt)
  7585. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7586. (setq newend (point))
  7587. (org-reinstall-markers-in-region beg)
  7588. (setq end (point))
  7589. (goto-char beg)
  7590. (skip-chars-forward " \t\n\r")
  7591. (setq beg (point))
  7592. (when (and (outline-invisible-p) visp)
  7593. (save-excursion (outline-show-heading)))
  7594. ;; Shift if necessary
  7595. (unless (= shift 0)
  7596. (save-restriction
  7597. (narrow-to-region beg end)
  7598. (while (not (= shift 0))
  7599. (org-map-region func (point-min) (point-max))
  7600. (setq shift (+ delta shift)))
  7601. (goto-char (point-min))
  7602. (setq newend (point-max))))
  7603. (when (or (called-interactively-p 'interactive) for-yank)
  7604. (message "Clipboard pasted as level %d subtree" new-level))
  7605. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7606. kill-ring
  7607. (eq org-subtree-clip (current-kill 0))
  7608. org-subtree-clip-folded)
  7609. ;; The tree was folded before it was killed/copied
  7610. (outline-hide-subtree))
  7611. (and for-yank (goto-char newend))
  7612. (and remove (setq kill-ring (cdr kill-ring))))))
  7613. (defun org-kill-is-subtree-p (&optional txt)
  7614. "Check if the current kill is an outline subtree, or a set of trees.
  7615. Returns nil if kill does not start with a headline, or if the first
  7616. headline level is not the largest headline level in the tree.
  7617. So this will actually accept several entries of equal levels as well,
  7618. which is OK for `org-paste-subtree'.
  7619. If optional TXT is given, check this string instead of the current kill."
  7620. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7621. (re (org-get-limited-outline-regexp))
  7622. (^re (concat "^" re))
  7623. (start-level (and kill
  7624. (string-match
  7625. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7626. kill)
  7627. (- (match-end 2) (match-beginning 2) 1)))
  7628. (start (1+ (or (match-beginning 2) -1))))
  7629. (if (not start-level)
  7630. (progn
  7631. nil) ;; does not even start with a heading
  7632. (catch 'exit
  7633. (while (setq start (string-match ^re kill (1+ start)))
  7634. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7635. (throw 'exit nil)))
  7636. t))))
  7637. (defvar org-markers-to-move nil
  7638. "Markers that should be moved with a cut-and-paste operation.
  7639. Those markers are stored together with their positions relative to
  7640. the start of the region.")
  7641. (defun org-save-markers-in-region (beg end)
  7642. "Check markers in region.
  7643. If these markers are between BEG and END, record their position relative
  7644. to BEG, so that after moving the block of text, we can put the markers back
  7645. into place.
  7646. This function gets called just before an entry or tree gets cut from the
  7647. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7648. called immediately, to move the markers with the entries."
  7649. (setq org-markers-to-move nil)
  7650. (when (featurep 'org-clock)
  7651. (org-clock-save-markers-for-cut-and-paste beg end))
  7652. (when (featurep 'org-agenda)
  7653. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7654. (defun org-check-and-save-marker (marker beg end)
  7655. "Check if MARKER is between BEG and END.
  7656. If yes, remember the marker and the distance to BEG."
  7657. (when (and (marker-buffer marker)
  7658. (equal (marker-buffer marker) (current-buffer))
  7659. (>= marker beg) (< marker end))
  7660. (push (cons marker (- marker beg)) org-markers-to-move)))
  7661. (defun org-reinstall-markers-in-region (beg)
  7662. "Move all remembered markers to their position relative to BEG."
  7663. (dolist (x org-markers-to-move)
  7664. (move-marker (car x) (+ beg (cdr x))))
  7665. (setq org-markers-to-move nil))
  7666. (defun org-narrow-to-subtree ()
  7667. "Narrow buffer to the current subtree."
  7668. (interactive)
  7669. (save-excursion
  7670. (save-match-data
  7671. (org-with-limited-levels
  7672. (narrow-to-region
  7673. (progn (org-back-to-heading t) (point))
  7674. (progn (org-end-of-subtree t t)
  7675. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7676. (point)))))))
  7677. (defun org-narrow-to-block ()
  7678. "Narrow buffer to the current block."
  7679. (interactive)
  7680. (let* ((case-fold-search t)
  7681. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7682. "^[ \t]*#\\+end_.*")))
  7683. (if blockp
  7684. (narrow-to-region (car blockp) (cdr blockp))
  7685. (user-error "Not in a block"))))
  7686. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7687. "Clone the task (subtree) at point N times.
  7688. The clones will be inserted as siblings.
  7689. In interactive use, the user will be prompted for the number of
  7690. clones to be produced. If the entry has a timestamp, the user
  7691. will also be prompted for a time shift, which may be a repeater
  7692. as used in time stamps, for example `+3d'. To disable this,
  7693. you can call the function with a universal prefix argument.
  7694. When a valid repeater is given and the entry contains any time
  7695. stamps, the clones will become a sequence in time, with time
  7696. stamps in the subtree shifted for each clone produced. If SHIFT
  7697. is nil or the empty string, time stamps will be left alone. The
  7698. ID property of the original subtree is removed.
  7699. In each clone, all the CLOCK entries will be removed. This
  7700. prevents Org from considering that the clocked times overlap.
  7701. If the original subtree did contain time stamps with a repeater,
  7702. the following will happen:
  7703. - the repeater will be removed in each clone
  7704. - an additional clone will be produced, with the current, unshifted
  7705. date(s) in the entry.
  7706. - the original entry will be placed *after* all the clones, with
  7707. repeater intact.
  7708. - the start days in the repeater in the original entry will be shifted
  7709. to past the last clone.
  7710. In this way you can spell out a number of instances of a repeating task,
  7711. and still retain the repeater to cover future instances of the task.
  7712. As described above, N+1 clones are produced when the original
  7713. subtree has a repeater. Setting N to 0, then, can be used to
  7714. remove the repeater from a subtree and create a shifted clone
  7715. with the original repeater."
  7716. (interactive "nNumber of clones to produce: ")
  7717. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7718. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7719. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7720. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7721. (shift
  7722. (or shift
  7723. (if (and (not (equal current-prefix-arg '(4)))
  7724. (save-excursion
  7725. (goto-char beg)
  7726. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7727. (read-from-minibuffer
  7728. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7729. ""))) ;No time shift
  7730. (doshift
  7731. (and (org-string-nw-p shift)
  7732. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7733. shift)
  7734. (user-error "Invalid shift specification %s" shift)))))
  7735. (goto-char end-of-tree)
  7736. (unless (bolp) (insert "\n"))
  7737. (let* ((end (point))
  7738. (template (buffer-substring beg end))
  7739. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7740. (shift-what (pcase (and doshift (match-string 2 shift))
  7741. (`nil nil)
  7742. ("d" 'day)
  7743. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7744. ("m" 'month)
  7745. ("y" 'year)
  7746. (_ (error "Unsupported time unit"))))
  7747. (nmin 1)
  7748. (nmax n)
  7749. (n-no-remove -1)
  7750. (idprop (org-entry-get nil "ID")))
  7751. (when (and doshift
  7752. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7753. template))
  7754. (delete-region beg end)
  7755. (setq end beg)
  7756. (setq nmin 0)
  7757. (setq nmax (1+ nmax))
  7758. (setq n-no-remove nmax))
  7759. (goto-char end)
  7760. (cl-loop for n from nmin to nmax do
  7761. (insert
  7762. ;; Prepare clone.
  7763. (with-temp-buffer
  7764. (insert template)
  7765. (org-mode)
  7766. (goto-char (point-min))
  7767. (org-show-subtree)
  7768. (and idprop (if org-clone-delete-id
  7769. (org-entry-delete nil "ID")
  7770. (org-id-get-create t)))
  7771. (unless (= n 0)
  7772. (while (re-search-forward org-clock-line-re nil t)
  7773. (delete-region (line-beginning-position)
  7774. (line-beginning-position 2)))
  7775. (goto-char (point-min))
  7776. (while (re-search-forward org-drawer-regexp nil t)
  7777. (org-remove-empty-drawer-at (point))))
  7778. (goto-char (point-min))
  7779. (when doshift
  7780. (while (re-search-forward org-ts-regexp-both nil t)
  7781. (org-timestamp-change (* n shift-n) shift-what))
  7782. (unless (= n n-no-remove)
  7783. (goto-char (point-min))
  7784. (while (re-search-forward org-ts-regexp nil t)
  7785. (save-excursion
  7786. (goto-char (match-beginning 0))
  7787. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7788. (delete-region (match-beginning 1) (match-end 1)))))))
  7789. (buffer-string)))))
  7790. (goto-char beg)))
  7791. ;;; Outline Sorting
  7792. (defun org-sort (&optional with-case)
  7793. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7794. Optional argument WITH-CASE means sort case-sensitively."
  7795. (interactive "P")
  7796. (org-call-with-arg
  7797. (cond ((org-at-table-p) #'org-table-sort-lines)
  7798. ((org-at-item-p) #'org-sort-list)
  7799. (t #'org-sort-entries))
  7800. with-case))
  7801. (defun org-sort-remove-invisible (s)
  7802. "Remove invisible part of links and emphasis markers from string S."
  7803. (remove-text-properties 0 (length s) org-rm-props s)
  7804. (replace-regexp-in-string
  7805. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7806. (replace-regexp-in-string
  7807. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7808. (org-link-display-format s)
  7809. t t) t t))
  7810. (defvar org-priority-regexp) ; defined later in the file
  7811. (defvar org-after-sorting-entries-or-items-hook nil
  7812. "Hook that is run after a bunch of entries or items have been sorted.
  7813. When children are sorted, the cursor is in the parent line when this
  7814. hook gets called. When a region or a plain list is sorted, the cursor
  7815. will be in the first entry of the sorted region/list.")
  7816. (defun org-sort-entries
  7817. (&optional with-case sorting-type getkey-func compare-func property
  7818. interactive?)
  7819. "Sort entries on a certain level of an outline tree.
  7820. If there is an active region, the entries in the region are sorted.
  7821. Else, if the cursor is before the first entry, sort the top-level items.
  7822. Else, the children of the entry at point are sorted.
  7823. Sorting can be alphabetically, numerically, by date/time as given by
  7824. a time stamp, by a property, by priority order, or by a custom function.
  7825. The command prompts for the sorting type unless it has been given to the
  7826. function through the SORTING-TYPE argument, which needs to be a character,
  7827. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7828. the precise meaning of each character:
  7829. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7830. c By creation time, which is assumed to be the first inactive time stamp
  7831. at the beginning of a line.
  7832. d By deadline date/time.
  7833. k By clocking time.
  7834. n Numerically, by converting the beginning of the entry/item to a number.
  7835. o By order of TODO keywords.
  7836. p By priority according to the cookie.
  7837. r By the value of a property.
  7838. s By scheduled date/time.
  7839. t By date/time, either the first active time stamp in the entry, or, if
  7840. none exist, by the first inactive one.
  7841. Capital letters will reverse the sort order.
  7842. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7843. called with point at the beginning of the record. It must return a
  7844. value that is compatible with COMPARE-FUNC, the function used to
  7845. compare entries.
  7846. Comparing entries ignores case by default. However, with an optional argument
  7847. WITH-CASE, the sorting considers case as well.
  7848. Sorting is done against the visible part of the headlines, it ignores hidden
  7849. links.
  7850. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7851. A non-nil value for INTERACTIVE? is used to signal that this
  7852. function is being called interactively."
  7853. (interactive (list current-prefix-arg nil nil nil nil t))
  7854. (let ((case-func (if with-case 'identity 'downcase))
  7855. (cmstr
  7856. ;; The clock marker is lost when using `sort-subr', let's
  7857. ;; store the clocking string.
  7858. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7859. (save-excursion
  7860. (goto-char org-clock-marker)
  7861. (buffer-substring-no-properties (line-beginning-position)
  7862. (point)))))
  7863. start beg end stars re re2
  7864. txt what tmp)
  7865. ;; Find beginning and end of region to sort
  7866. (cond
  7867. ((org-region-active-p)
  7868. ;; we will sort the region
  7869. (setq end (region-end)
  7870. what "region")
  7871. (goto-char (region-beginning))
  7872. (unless (org-at-heading-p) (outline-next-heading))
  7873. (setq start (point)))
  7874. ((or (org-at-heading-p)
  7875. (ignore-errors (progn (org-back-to-heading) t)))
  7876. ;; we will sort the children of the current headline
  7877. (org-back-to-heading)
  7878. (setq start (point)
  7879. end (progn (org-end-of-subtree t t)
  7880. (or (bolp) (insert "\n"))
  7881. (when (>= (org-back-over-empty-lines) 1)
  7882. (forward-line 1))
  7883. (point))
  7884. what "children")
  7885. (goto-char start)
  7886. (outline-show-subtree)
  7887. (outline-next-heading))
  7888. (t
  7889. ;; we will sort the top-level entries in this file
  7890. (goto-char (point-min))
  7891. (or (org-at-heading-p) (outline-next-heading))
  7892. (setq start (point))
  7893. (goto-char (point-max))
  7894. (beginning-of-line 1)
  7895. (when (looking-at ".*?\\S-")
  7896. ;; File ends in a non-white line
  7897. (end-of-line 1)
  7898. (insert "\n"))
  7899. (setq end (point-max))
  7900. (setq what "top-level")
  7901. (goto-char start)
  7902. (outline-show-all)))
  7903. (setq beg (point))
  7904. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7905. (looking-at "\\(\\*+\\)")
  7906. (setq stars (match-string 1)
  7907. re (concat "^" (regexp-quote stars) " +")
  7908. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7909. txt (buffer-substring beg end))
  7910. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7911. (when (and (not (equal stars "*")) (string-match re2 txt))
  7912. (user-error "Region to sort contains a level above the first entry"))
  7913. (unless sorting-type
  7914. (message
  7915. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7916. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7917. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7918. what)
  7919. (setq sorting-type (read-char-exclusive)))
  7920. (unless getkey-func
  7921. (and (= (downcase sorting-type) ?f)
  7922. (setq getkey-func
  7923. (or (and interactive?
  7924. (org-read-function
  7925. "Function for extracting keys: "))
  7926. (error "Missing key extractor")))))
  7927. (and (= (downcase sorting-type) ?r)
  7928. (not property)
  7929. (setq property
  7930. (completing-read "Property: "
  7931. (mapcar #'list (org-buffer-property-keys t))
  7932. nil t)))
  7933. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7934. (message "Sorting entries...")
  7935. (save-restriction
  7936. (narrow-to-region start end)
  7937. (let ((dcst (downcase sorting-type))
  7938. (case-fold-search nil)
  7939. (now (current-time)))
  7940. (sort-subr
  7941. (/= dcst sorting-type)
  7942. ;; This function moves to the beginning character of the "record" to
  7943. ;; be sorted.
  7944. (lambda nil
  7945. (if (re-search-forward re nil t)
  7946. (goto-char (match-beginning 0))
  7947. (goto-char (point-max))))
  7948. ;; This function moves to the last character of the "record" being
  7949. ;; sorted.
  7950. (lambda nil
  7951. (save-match-data
  7952. (condition-case nil
  7953. (outline-forward-same-level 1)
  7954. (error
  7955. (goto-char (point-max))))))
  7956. ;; This function returns the value that gets sorted against.
  7957. (lambda nil
  7958. (cond
  7959. ((= dcst ?n)
  7960. (if (looking-at org-complex-heading-regexp)
  7961. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7962. nil))
  7963. ((= dcst ?a)
  7964. (if (looking-at org-complex-heading-regexp)
  7965. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7966. nil))
  7967. ((= dcst ?k)
  7968. (or (get-text-property (point) :org-clock-minutes) 0))
  7969. ((= dcst ?t)
  7970. (let ((end (save-excursion (outline-next-heading) (point))))
  7971. (if (or (re-search-forward org-ts-regexp end t)
  7972. (re-search-forward org-ts-regexp-both end t))
  7973. (org-time-string-to-seconds (match-string 0))
  7974. (float-time now))))
  7975. ((= dcst ?c)
  7976. (let ((end (save-excursion (outline-next-heading) (point))))
  7977. (if (re-search-forward
  7978. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7979. end t)
  7980. (org-time-string-to-seconds (match-string 0))
  7981. (float-time now))))
  7982. ((= dcst ?s)
  7983. (let ((end (save-excursion (outline-next-heading) (point))))
  7984. (if (re-search-forward org-scheduled-time-regexp end t)
  7985. (org-time-string-to-seconds (match-string 1))
  7986. (float-time now))))
  7987. ((= dcst ?d)
  7988. (let ((end (save-excursion (outline-next-heading) (point))))
  7989. (if (re-search-forward org-deadline-time-regexp end t)
  7990. (org-time-string-to-seconds (match-string 1))
  7991. (float-time now))))
  7992. ((= dcst ?p)
  7993. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7994. (string-to-char (match-string 2))
  7995. org-default-priority))
  7996. ((= dcst ?r)
  7997. (or (org-entry-get nil property) ""))
  7998. ((= dcst ?o)
  7999. (when (looking-at org-complex-heading-regexp)
  8000. (let* ((m (match-string 2))
  8001. (s (if (member m org-done-keywords) '- '+)))
  8002. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8003. ((= dcst ?f)
  8004. (if getkey-func
  8005. (progn
  8006. (setq tmp (funcall getkey-func))
  8007. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8008. tmp)
  8009. (error "Invalid key function `%s'" getkey-func)))
  8010. (t (error "Invalid sorting type `%c'" sorting-type))))
  8011. nil
  8012. (cond
  8013. ((= dcst ?a) 'string<)
  8014. ((= dcst ?f)
  8015. (or compare-func
  8016. (and interactive?
  8017. (org-read-function
  8018. (concat "Function for comparing keys "
  8019. "(empty for default `sort-subr' predicate): ")
  8020. 'allow-empty))))
  8021. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8022. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8023. ;; Reset the clock marker if needed
  8024. (when cmstr
  8025. (save-excursion
  8026. (goto-char start)
  8027. (search-forward cmstr nil t)
  8028. (move-marker org-clock-marker (point))))
  8029. (message "Sorting entries...done")))
  8030. ;;; The orgstruct minor mode
  8031. ;; Define a minor mode which can be used in other modes in order to
  8032. ;; integrate the Org mode structure editing commands.
  8033. ;; This is really a hack, because the Org mode structure commands use
  8034. ;; keys which normally belong to the major mode. Here is how it
  8035. ;; works: The minor mode defines all the keys necessary to operate the
  8036. ;; structure commands, but wraps the commands into a function which
  8037. ;; tests if the cursor is currently at a headline or a plain list
  8038. ;; item. If that is the case, the structure command is used,
  8039. ;; temporarily setting many Org mode variables like regular
  8040. ;; expressions for filling etc. However, when any of those keys is
  8041. ;; used at a different location, function uses `key-binding' to look
  8042. ;; up if the key has an associated command in another currently active
  8043. ;; keymap (minor modes, major mode, global), and executes that
  8044. ;; command. There might be problems if any of the keys is otherwise
  8045. ;; used as a prefix key.
  8046. (defcustom orgstruct-heading-prefix-regexp ""
  8047. "Regexp that matches the custom prefix of Org headlines in
  8048. orgstruct(++)-mode."
  8049. :group 'org
  8050. :version "24.4"
  8051. :package-version '(Org . "8.3")
  8052. :type 'regexp)
  8053. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8054. (defcustom orgstruct-setup-hook nil
  8055. "Hook run after orgstruct-mode-map is filled."
  8056. :group 'org
  8057. :version "24.4"
  8058. :package-version '(Org . "8.0")
  8059. :type 'hook)
  8060. (defvar orgstruct-initialized nil)
  8061. (defvar org-local-vars nil
  8062. "List of local variables, for use by `orgstruct-mode'.")
  8063. ;;;###autoload
  8064. (define-minor-mode orgstruct-mode
  8065. "Toggle the minor mode `orgstruct-mode'.
  8066. This mode is for using Org mode structure commands in other
  8067. modes. The following keys behave as if Org mode were active, if
  8068. the cursor is on a headline, or on a plain list item (both as
  8069. defined by Org mode)."
  8070. nil " OrgStruct" (make-sparse-keymap)
  8071. (funcall (if orgstruct-mode
  8072. 'add-to-invisibility-spec
  8073. 'remove-from-invisibility-spec)
  8074. '(outline . t))
  8075. (when orgstruct-mode
  8076. (org-load-modules-maybe)
  8077. (unless orgstruct-initialized
  8078. (orgstruct-setup)
  8079. (setq orgstruct-initialized t))))
  8080. ;;;###autoload
  8081. (defun turn-on-orgstruct ()
  8082. "Unconditionally turn on `orgstruct-mode'."
  8083. (orgstruct-mode 1))
  8084. (defvar-local orgstruct-is-++ nil
  8085. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8086. (defvar-local org-fb-vars nil)
  8087. (defun orgstruct++-mode (&optional arg)
  8088. "Toggle `orgstruct-mode', the enhanced version of it.
  8089. In addition to setting orgstruct-mode, this also exports all
  8090. indentation and autofilling variables from Org mode into the
  8091. buffer. It will also recognize item context in multiline items."
  8092. (interactive "P")
  8093. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8094. (if (< arg 1)
  8095. (progn (orgstruct-mode -1)
  8096. (dolist (v org-fb-vars)
  8097. (set (make-local-variable (car v))
  8098. (if (eq (car-safe (cadr v)) 'quote)
  8099. (cl-cadadr v)
  8100. (nth 1 v)))))
  8101. (orgstruct-mode 1)
  8102. (setq org-fb-vars nil)
  8103. (unless org-local-vars
  8104. (setq org-local-vars (org-get-local-variables)))
  8105. (let (var val)
  8106. (dolist (x org-local-vars)
  8107. (when (string-match
  8108. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8109. \\|fill-prefix\\|indent-\\)"
  8110. (symbol-name (car x)))
  8111. (setq var (car x) val (nth 1 x))
  8112. (push (list var `(quote ,(eval var))) org-fb-vars)
  8113. (set (make-local-variable var)
  8114. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8115. (setq-local orgstruct-is-++ t))))
  8116. ;;;###autoload
  8117. (defun turn-on-orgstruct++ ()
  8118. "Unconditionally turn on `orgstruct++-mode'."
  8119. (orgstruct++-mode 1))
  8120. (defun orgstruct-error ()
  8121. "Error when there is no default binding for a structure key."
  8122. (interactive)
  8123. (funcall (if (fboundp 'user-error)
  8124. 'user-error
  8125. 'error)
  8126. "This key has no function outside structure elements"))
  8127. (defun orgstruct-setup ()
  8128. "Setup orgstruct keymap."
  8129. (dolist (cell '((org-demote . t)
  8130. (org-metaleft . t)
  8131. (org-metaright . t)
  8132. (org-promote . t)
  8133. (org-shiftmetaleft . t)
  8134. (org-shiftmetaright . t)
  8135. org-backward-element
  8136. org-backward-heading-same-level
  8137. org-ctrl-c-ret
  8138. org-ctrl-c-minus
  8139. org-ctrl-c-star
  8140. org-cycle
  8141. org-force-cycle-archived
  8142. org-forward-heading-same-level
  8143. org-insert-heading
  8144. org-insert-heading-respect-content
  8145. org-kill-note-or-show-branches
  8146. org-mark-subtree
  8147. org-meta-return
  8148. org-metadown
  8149. org-metaup
  8150. org-narrow-to-subtree
  8151. org-promote-subtree
  8152. org-reveal
  8153. org-shiftdown
  8154. org-shiftleft
  8155. org-shiftmetadown
  8156. org-shiftmetaup
  8157. org-shiftright
  8158. org-shifttab
  8159. org-shifttab
  8160. org-shiftup
  8161. org-show-children
  8162. org-show-subtree
  8163. org-sort
  8164. org-up-element
  8165. outline-demote
  8166. outline-next-visible-heading
  8167. outline-previous-visible-heading
  8168. outline-promote
  8169. outline-up-heading))
  8170. (let ((f (or (car-safe cell) cell))
  8171. (disable-when-heading-prefix (cdr-safe cell)))
  8172. (when (fboundp f)
  8173. (let ((new-bindings))
  8174. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8175. (where-is-internal f outline-mode-map)))
  8176. (push binding new-bindings)
  8177. ;; TODO use local-function-key-map
  8178. (dolist (rep '(("<tab>" . "TAB")
  8179. ("<return>" . "RET")
  8180. ("<escape>" . "ESC")
  8181. ("<delete>" . "DEL")))
  8182. (setq binding (read-kbd-macro
  8183. (let ((case-fold-search))
  8184. (replace-regexp-in-string
  8185. (regexp-quote (cdr rep))
  8186. (car rep)
  8187. (key-description binding)))))
  8188. (cl-pushnew binding new-bindings :test 'equal)))
  8189. (dolist (binding new-bindings)
  8190. (let ((key (lookup-key orgstruct-mode-map binding)))
  8191. (when (or (not key) (numberp key))
  8192. (ignore-errors
  8193. (org-defkey orgstruct-mode-map
  8194. binding
  8195. (orgstruct-make-binding
  8196. f binding disable-when-heading-prefix))))))))))
  8197. (run-hooks 'orgstruct-setup-hook))
  8198. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8199. "Create a function for binding in the structure minor mode.
  8200. FUN is the command to call inside a table. KEY is the key that
  8201. should be checked in for a command to execute outside of tables.
  8202. Non-nil `disable-when-heading-prefix' means to disable the command
  8203. if `orgstruct-heading-prefix-regexp' is not empty."
  8204. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8205. (let ((nname name)
  8206. (i 0))
  8207. (while (fboundp (intern nname))
  8208. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8209. (setq name (intern nname)))
  8210. (eval
  8211. (let ((bindings '((org-heading-regexp
  8212. (concat "^"
  8213. orgstruct-heading-prefix-regexp
  8214. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8215. (org-outline-regexp
  8216. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8217. (org-outline-regexp-bol
  8218. (concat "^" org-outline-regexp))
  8219. (outline-regexp org-outline-regexp)
  8220. (outline-heading-end-regexp "\n")
  8221. (outline-level 'org-outline-level)
  8222. (outline-heading-alist))))
  8223. `(defun ,name (arg)
  8224. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8225. "Outside of structure, run the binding of `"
  8226. (key-description key) "'."
  8227. (when disable-when-heading-prefix
  8228. (concat
  8229. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8230. "back to the default binding due to limitations of Org's implementation of\n"
  8231. "`" (symbol-name fun) "'.")))
  8232. (interactive "p")
  8233. (let* ((disable
  8234. ,(and disable-when-heading-prefix
  8235. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8236. (fallback
  8237. (or disable
  8238. (not
  8239. (let* ,bindings
  8240. (org-context-p 'headline 'item
  8241. ,(when (memq fun
  8242. '(org-insert-heading
  8243. org-insert-heading-respect-content
  8244. org-meta-return))
  8245. '(when orgstruct-is-++
  8246. 'item-body))))))))
  8247. (if fallback
  8248. (let* ((orgstruct-mode)
  8249. (binding
  8250. (let ((key ,key))
  8251. (catch 'exit
  8252. (dolist
  8253. (rep
  8254. '(nil
  8255. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8256. ("<\\([^>]*\\)return>" . "\\1RET")
  8257. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8258. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8259. nil)
  8260. (when rep
  8261. (setq key (read-kbd-macro
  8262. (let ((case-fold-search))
  8263. (replace-regexp-in-string
  8264. (car rep)
  8265. (cdr rep)
  8266. (key-description key))))))
  8267. (when (key-binding key)
  8268. (throw 'exit (key-binding key))))))))
  8269. (if (keymapp binding)
  8270. (org-set-transient-map binding)
  8271. (let ((func (or binding
  8272. (unless disable
  8273. 'orgstruct-error))))
  8274. (when func
  8275. (call-interactively func)))))
  8276. (org-run-like-in-org-mode
  8277. (lambda ()
  8278. (interactive)
  8279. (let* ,bindings
  8280. (call-interactively ',fun)))))))))
  8281. name))
  8282. (defun org-contextualize-keys (alist contexts)
  8283. "Return valid elements in ALIST depending on CONTEXTS.
  8284. `org-agenda-custom-commands' or `org-capture-templates' are the
  8285. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8286. or `org-capture-templates-contexts' are the associated contexts
  8287. definitions."
  8288. (let ((contexts
  8289. ;; normalize contexts
  8290. (mapcar
  8291. (lambda(c) (cond ((listp (cadr c))
  8292. (list (car c) (car c) (nth 1 c)))
  8293. ((string= "" (cadr c))
  8294. (list (car c) (car c) (nth 2 c)))
  8295. (t c)))
  8296. contexts))
  8297. (a alist) r s)
  8298. ;; loop over all commands or templates
  8299. (dolist (c a)
  8300. (let (vrules repl)
  8301. (cond
  8302. ((not (assoc (car c) contexts))
  8303. (push c r))
  8304. ((and (assoc (car c) contexts)
  8305. (setq vrules (org-contextualize-validate-key
  8306. (car c) contexts)))
  8307. (mapc (lambda (vr)
  8308. (unless (equal (car vr) (cadr vr))
  8309. (setq repl vr)))
  8310. vrules)
  8311. (if (not repl) (push c r)
  8312. (push (cadr repl) s)
  8313. (push
  8314. (cons (car c)
  8315. (cdr (or (assoc (cadr repl) alist)
  8316. (error "Undefined key `%s' as contextual replacement for `%s'"
  8317. (cadr repl) (car c)))))
  8318. r))))))
  8319. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8320. (delq
  8321. nil
  8322. (delete-dups
  8323. (mapcar (lambda (x)
  8324. (let ((tpl (car x)))
  8325. (unless (delq
  8326. nil
  8327. (mapcar (lambda (y)
  8328. (equal y tpl))
  8329. s))
  8330. x)))
  8331. (reverse r))))))
  8332. (defun org-contextualize-validate-key (key contexts)
  8333. "Check CONTEXTS for agenda or capture KEY."
  8334. (let (res)
  8335. (dolist (r contexts)
  8336. (dolist (rr (car (last r)))
  8337. (when
  8338. (and (equal key (car r))
  8339. (if (functionp rr) (funcall rr)
  8340. (or (and (eq (car rr) 'in-file)
  8341. (buffer-file-name)
  8342. (string-match (cdr rr) (buffer-file-name)))
  8343. (and (eq (car rr) 'in-mode)
  8344. (string-match (cdr rr) (symbol-name major-mode)))
  8345. (and (eq (car rr) 'in-buffer)
  8346. (string-match (cdr rr) (buffer-name)))
  8347. (when (and (eq (car rr) 'not-in-file)
  8348. (buffer-file-name))
  8349. (not (string-match (cdr rr) (buffer-file-name))))
  8350. (when (eq (car rr) 'not-in-mode)
  8351. (not (string-match (cdr rr) (symbol-name major-mode))))
  8352. (when (eq (car rr) 'not-in-buffer)
  8353. (not (string-match (cdr rr) (buffer-name)))))))
  8354. (push r res))))
  8355. (delete-dups (delq nil res))))
  8356. (defun org-context-p (&rest contexts)
  8357. "Check if local context is any of CONTEXTS.
  8358. Possible values in the list of contexts are `table', `headline', and `item'."
  8359. (let ((pos (point)))
  8360. (goto-char (point-at-bol))
  8361. (prog1 (or (and (memq 'table contexts)
  8362. (looking-at "[ \t]*|"))
  8363. (and (memq 'headline contexts)
  8364. (looking-at org-outline-regexp))
  8365. (and (memq 'item contexts)
  8366. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8367. (and (memq 'item-body contexts)
  8368. (org-in-item-p)))
  8369. (goto-char pos))))
  8370. (defconst org-unique-local-variables
  8371. '(org-element--cache
  8372. org-element--cache-objects
  8373. org-element--cache-sync-keys
  8374. org-element--cache-sync-requests
  8375. org-element--cache-sync-timer)
  8376. "List of local variables that cannot be transferred to another buffer.")
  8377. (defun org-get-local-variables ()
  8378. "Return a list of all local variables in an Org mode buffer."
  8379. (delq nil
  8380. (mapcar
  8381. (lambda (x)
  8382. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8383. (name (car binding)))
  8384. (and (not (get name 'org-state))
  8385. (not (memq name org-unique-local-variables))
  8386. (string-match-p
  8387. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8388. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8389. (symbol-name name))
  8390. binding)))
  8391. (with-temp-buffer
  8392. (org-mode)
  8393. (buffer-local-variables)))))
  8394. (defun org-clone-local-variables (from-buffer &optional regexp)
  8395. "Clone local variables from FROM-BUFFER.
  8396. Optional argument REGEXP selects variables to clone."
  8397. (dolist (pair (buffer-local-variables from-buffer))
  8398. (pcase pair
  8399. (`(,name . ,value) ;ignore unbound variables
  8400. (when (and (not (memq name org-unique-local-variables))
  8401. (or (null regexp) (string-match-p regexp (symbol-name name))))
  8402. (set (make-local-variable name) value))))))
  8403. ;;;###autoload
  8404. (defun org-run-like-in-org-mode (cmd)
  8405. "Run a command, pretending that the current buffer is in Org mode.
  8406. This will temporarily bind local variables that are typically bound in
  8407. Org mode to the values they have in Org mode, and then interactively
  8408. call CMD."
  8409. (org-load-modules-maybe)
  8410. (unless org-local-vars
  8411. (setq org-local-vars (org-get-local-variables)))
  8412. (let (binds)
  8413. (dolist (var org-local-vars)
  8414. (when (or (not (boundp (car var)))
  8415. (eq (symbol-value (car var))
  8416. (default-value (car var))))
  8417. (push (list (car var) `(quote ,(cadr var))) binds)))
  8418. (eval `(let ,binds
  8419. (call-interactively (quote ,cmd))))))
  8420. (defun org-get-category (&optional pos force-refresh)
  8421. "Get the category applying to position POS."
  8422. (save-match-data
  8423. (when force-refresh (org-refresh-category-properties))
  8424. (let ((pos (or pos (point))))
  8425. (or (get-text-property pos 'org-category)
  8426. (progn (org-refresh-category-properties)
  8427. (get-text-property pos 'org-category))))))
  8428. ;;; Refresh properties
  8429. (defun org-refresh-properties (dprop tprop)
  8430. "Refresh buffer text properties.
  8431. DPROP is the drawer property and TPROP is either the
  8432. corresponding text property to set, or an alist with each element
  8433. being a text property (as a symbol) and a function to apply to
  8434. the value of the drawer property."
  8435. (let* ((case-fold-search t)
  8436. (inhibit-read-only t)
  8437. (inherit? (org-property-inherit-p dprop))
  8438. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8439. (global (and inherit? (org--property-global-value dprop nil))))
  8440. (org-with-silent-modifications
  8441. (org-with-point-at 1
  8442. ;; Set global values (e.g., values defined through
  8443. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8444. (when global (put-text-property (point-min) (point-max) tprop global))
  8445. ;; Set local values.
  8446. (while (re-search-forward property-re nil t)
  8447. (when (org-at-property-p)
  8448. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8449. (outline-next-heading))))))
  8450. (defun org-refresh-property (tprop p &optional inherit)
  8451. "Refresh the buffer text property TPROP from the drawer property P.
  8452. The refresh happens only for the current headline, or the whole
  8453. sub-tree if optional argument INHERIT is non-nil."
  8454. (unless (org-before-first-heading-p)
  8455. (save-excursion
  8456. (org-back-to-heading t)
  8457. (let ((start (point))
  8458. (end (save-excursion
  8459. (if inherit (org-end-of-subtree t t)
  8460. (or (outline-next-heading) (point-max))))))
  8461. (if (symbolp tprop)
  8462. ;; TPROP is a text property symbol.
  8463. (put-text-property start end tprop p)
  8464. ;; TPROP is an alist with (property . function) elements.
  8465. (pcase-dolist (`(,prop . ,f) tprop)
  8466. (put-text-property start end prop (funcall f p))))))))
  8467. (defun org-refresh-category-properties ()
  8468. "Refresh category text properties in the buffer."
  8469. (let ((case-fold-search t)
  8470. (inhibit-read-only t)
  8471. (default-category
  8472. (cond ((null org-category)
  8473. (if buffer-file-name
  8474. (file-name-sans-extension
  8475. (file-name-nondirectory buffer-file-name))
  8476. "???"))
  8477. ((symbolp org-category) (symbol-name org-category))
  8478. (t org-category))))
  8479. (org-with-silent-modifications
  8480. (org-with-wide-buffer
  8481. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8482. ;; This is the default category for the buffer. If none is
  8483. ;; found, fall-back to `org-category' or buffer file name.
  8484. (put-text-property
  8485. (point-min) (point-max)
  8486. 'org-category
  8487. (catch 'buffer-category
  8488. (goto-char (point-max))
  8489. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8490. (let ((element (org-element-at-point)))
  8491. (when (eq (org-element-type element) 'keyword)
  8492. (throw 'buffer-category
  8493. (org-element-property :value element)))))
  8494. default-category))
  8495. ;; Set sub-tree specific categories.
  8496. (goto-char (point-min))
  8497. (let ((regexp (org-re-property "CATEGORY")))
  8498. (while (re-search-forward regexp nil t)
  8499. (let ((value (match-string-no-properties 3)))
  8500. (when (org-at-property-p)
  8501. (put-text-property
  8502. (save-excursion (org-back-to-heading t) (point))
  8503. (save-excursion (org-end-of-subtree t t) (point))
  8504. 'org-category
  8505. value)))))))))
  8506. (defun org-refresh-stats-properties ()
  8507. "Refresh stats text properties in the buffer."
  8508. (org-with-silent-modifications
  8509. (org-with-point-at 1
  8510. (let ((regexp (concat org-outline-regexp-bol
  8511. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8512. (while (re-search-forward regexp nil t)
  8513. (let* ((numerator (string-to-number (match-string 1)))
  8514. (denominator (and (match-end 2)
  8515. (string-to-number (match-string 2))))
  8516. (stats (cond ((not denominator) numerator) ;percent
  8517. ((= denominator 0) 0)
  8518. (t (/ (* numerator 100) denominator)))))
  8519. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8520. 'org-stats stats)))))))
  8521. (defun org-refresh-effort-properties ()
  8522. "Refresh effort properties"
  8523. (org-refresh-properties
  8524. org-effort-property
  8525. '((effort . identity)
  8526. (effort-minutes . org-duration-to-minutes))))
  8527. ;;;; Link Stuff
  8528. ;;; Link abbreviations
  8529. (defun org-link-expand-abbrev (link)
  8530. "Apply replacements as defined in `org-link-abbrev-alist'."
  8531. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8532. (let* ((key (match-string 1 link))
  8533. (as (or (assoc key org-link-abbrev-alist-local)
  8534. (assoc key org-link-abbrev-alist)))
  8535. (tag (and (match-end 2) (match-string 3 link)))
  8536. rpl)
  8537. (if (not as)
  8538. link
  8539. (setq rpl (cdr as))
  8540. (cond
  8541. ((symbolp rpl) (funcall rpl tag))
  8542. ((string-match "%(\\([^)]+\\))" rpl)
  8543. (replace-match
  8544. (save-match-data
  8545. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8546. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8547. ((string-match "%h" rpl)
  8548. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8549. (t (concat rpl tag)))))
  8550. link))
  8551. ;;; Storing and inserting links
  8552. (defvar org-insert-link-history nil
  8553. "Minibuffer history for links inserted with `org-insert-link'.")
  8554. (defvar org-stored-links nil
  8555. "Contains the links stored with `org-store-link'.")
  8556. (defvar org-store-link-plist nil
  8557. "Plist with info about the most recently link created with `org-store-link'.")
  8558. (defun org-store-link-functions ()
  8559. "Return a list of functions that are called to create and store a link.
  8560. The functions defined in the :store property of
  8561. `org-link-parameters'.
  8562. Each function will be called in turn until one returns a non-nil
  8563. value. Each function should check if it is responsible for
  8564. creating this link (for example by looking at the major mode).
  8565. If not, it must exit and return nil. If yes, it should return
  8566. a non-nil value after calling `org-store-link-props' with a list
  8567. of properties and values. Special properties are:
  8568. :type The link prefix, like \"http\". This must be given.
  8569. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8570. This is obligatory as well.
  8571. :description Optional default description for the second pair
  8572. of brackets in an Org mode link. The user can still change
  8573. this when inserting this link into an Org mode buffer.
  8574. In addition to these, any additional properties can be specified
  8575. and then used in capture templates."
  8576. (cl-loop for link in org-link-parameters
  8577. with store-func
  8578. do (setq store-func (org-link-get-parameter (car link) :store))
  8579. if store-func
  8580. collect store-func))
  8581. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8582. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8583. ;;;###autoload
  8584. (defun org-store-link (arg)
  8585. "Store an org-link to the current location.
  8586. \\<org-mode-map>
  8587. This link is added to `org-stored-links' and can later be inserted
  8588. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8589. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8590. A single
  8591. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8592. `org-gnus-prefer-web-links' for links to Usenet articles.
  8593. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8594. skipping storing functions that are not
  8595. part of Org core.
  8596. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8597. prefix ARG forces storing a link for each line in the
  8598. active region."
  8599. (interactive "P")
  8600. (org-load-modules-maybe)
  8601. (if (and (equal arg '(64)) (org-region-active-p))
  8602. (save-excursion
  8603. (let ((end (region-end)))
  8604. (goto-char (region-beginning))
  8605. (set-mark (point))
  8606. (while (< (point-at-eol) end)
  8607. (move-end-of-line 1) (activate-mark)
  8608. (let (current-prefix-arg)
  8609. (call-interactively 'org-store-link))
  8610. (move-beginning-of-line 2)
  8611. (set-mark (point)))))
  8612. (setq org-store-link-plist nil)
  8613. (let (link cpltxt desc description search
  8614. txt custom-id agenda-link sfuns sfunsn)
  8615. (cond
  8616. ;; Store a link using an external link type
  8617. ((and (not (equal arg '(16)))
  8618. (setq sfuns
  8619. (delq
  8620. nil (mapcar (lambda (f)
  8621. (let (fs) (if (funcall f) (push f fs))))
  8622. (org-store-link-functions)))
  8623. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8624. (or (and (cdr sfuns)
  8625. (funcall (intern
  8626. (completing-read
  8627. "Which function for creating the link? "
  8628. sfunsn nil t (car sfunsn)))))
  8629. (funcall (caar sfuns)))
  8630. (setq link (plist-get org-store-link-plist :link)
  8631. desc (or (plist-get org-store-link-plist
  8632. :description)
  8633. link))))
  8634. ;; Store a link from a source code buffer.
  8635. ((org-src-edit-buffer-p)
  8636. (let ((coderef-format (org-src-coderef-format)))
  8637. (cond ((save-excursion
  8638. (beginning-of-line)
  8639. (looking-at (org-src-coderef-regexp coderef-format)))
  8640. (setq link (format "(%s)" (match-string-no-properties 3))))
  8641. ((called-interactively-p 'any)
  8642. (let ((label (read-string "Code line label: ")))
  8643. (end-of-line)
  8644. (setq link (format coderef-format label))
  8645. (let ((gc (- 79 (length link))))
  8646. (if (< (current-column) gc)
  8647. (org-move-to-column gc t)
  8648. (insert " ")))
  8649. (insert link)
  8650. (setq link (concat "(" label ")"))
  8651. (setq desc nil)))
  8652. (t (setq link nil)))))
  8653. ;; We are in the agenda, link to referenced location
  8654. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8655. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8656. (get-text-property (point) 'org-marker))))
  8657. (when m
  8658. (org-with-point-at m
  8659. (setq agenda-link
  8660. (if (called-interactively-p 'any)
  8661. (call-interactively 'org-store-link)
  8662. (org-store-link nil)))))))
  8663. ((eq major-mode 'calendar-mode)
  8664. (let ((cd (calendar-cursor-to-date)))
  8665. (setq link
  8666. (format-time-string
  8667. (car org-time-stamp-formats)
  8668. (apply 'encode-time
  8669. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8670. nil nil nil))))
  8671. (org-store-link-props :type "calendar" :date cd)))
  8672. ((eq major-mode 'help-mode)
  8673. (setq link (concat "help:" (save-excursion
  8674. (goto-char (point-min))
  8675. (looking-at "^[^ ]+")
  8676. (match-string 0))))
  8677. (org-store-link-props :type "help"))
  8678. ((eq major-mode 'w3-mode)
  8679. (setq cpltxt (if (and (buffer-name)
  8680. (not (string-match "Untitled" (buffer-name))))
  8681. (buffer-name)
  8682. (url-view-url t))
  8683. link (url-view-url t))
  8684. (org-store-link-props :type "w3" :url (url-view-url t)))
  8685. ((eq major-mode 'image-mode)
  8686. (setq cpltxt (concat "file:"
  8687. (abbreviate-file-name buffer-file-name))
  8688. link cpltxt)
  8689. (org-store-link-props :type "image" :file buffer-file-name))
  8690. ;; In dired, store a link to the file of the current line
  8691. ((derived-mode-p 'dired-mode)
  8692. (let ((file (dired-get-filename nil t)))
  8693. (setq file (if file
  8694. (abbreviate-file-name
  8695. (expand-file-name (dired-get-filename nil t)))
  8696. ;; otherwise, no file so use current directory.
  8697. default-directory))
  8698. (setq cpltxt (concat "file:" file)
  8699. link cpltxt)))
  8700. ((setq search (run-hook-with-args-until-success
  8701. 'org-create-file-search-functions))
  8702. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8703. "::" search))
  8704. (setq cpltxt (or description link)))
  8705. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8706. (org-with-limited-levels
  8707. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8708. (cond
  8709. ;; Store a link using the target at point
  8710. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8711. (setq cpltxt
  8712. (concat "file:"
  8713. (abbreviate-file-name
  8714. (buffer-file-name (buffer-base-buffer)))
  8715. "::" (match-string 1))
  8716. link cpltxt))
  8717. ((and (featurep 'org-id)
  8718. (or (eq org-id-link-to-org-use-id t)
  8719. (and (called-interactively-p 'any)
  8720. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8721. (and (eq org-id-link-to-org-use-id
  8722. 'create-if-interactive-and-no-custom-id)
  8723. (not custom-id))))
  8724. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8725. ;; Store a link using the ID at point
  8726. (setq link (condition-case nil
  8727. (prog1 (org-id-store-link)
  8728. (setq desc (or (plist-get org-store-link-plist
  8729. :description)
  8730. "")))
  8731. (error
  8732. ;; Probably before first headline, link only to file
  8733. (concat "file:"
  8734. (abbreviate-file-name
  8735. (buffer-file-name (buffer-base-buffer))))))))
  8736. (t
  8737. ;; Just link to current headline
  8738. (setq cpltxt (concat "file:"
  8739. (abbreviate-file-name
  8740. (buffer-file-name (buffer-base-buffer)))))
  8741. ;; Add a context search string
  8742. (when (org-xor org-context-in-file-links
  8743. (equal arg '(4)))
  8744. (let* ((element (org-element-at-point))
  8745. (name (org-element-property :name element)))
  8746. (setq txt (cond
  8747. ((org-at-heading-p) nil)
  8748. (name)
  8749. ((org-region-active-p)
  8750. (buffer-substring (region-beginning) (region-end)))))
  8751. (when (or (null txt) (string-match "\\S-" txt))
  8752. (setq cpltxt
  8753. (concat cpltxt "::"
  8754. (condition-case nil
  8755. (org-make-org-heading-search-string txt)
  8756. (error "")))
  8757. desc (or name
  8758. (nth 4 (ignore-errors (org-heading-components)))
  8759. "NONE")))))
  8760. (when (string-match "::\\'" cpltxt)
  8761. (setq cpltxt (substring cpltxt 0 -2)))
  8762. (setq link cpltxt)))))
  8763. ((buffer-file-name (buffer-base-buffer))
  8764. ;; Just link to this file here.
  8765. (setq cpltxt (concat "file:"
  8766. (abbreviate-file-name
  8767. (buffer-file-name (buffer-base-buffer)))))
  8768. ;; Add a context string.
  8769. (when (org-xor org-context-in-file-links
  8770. (equal arg '(4)))
  8771. (setq txt (if (org-region-active-p)
  8772. (buffer-substring (region-beginning) (region-end))
  8773. (buffer-substring (point-at-bol) (point-at-eol))))
  8774. ;; Only use search option if there is some text.
  8775. (when (string-match "\\S-" txt)
  8776. (setq cpltxt
  8777. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8778. desc "NONE")))
  8779. (setq link cpltxt))
  8780. ((called-interactively-p 'interactive)
  8781. (user-error "No method for storing a link from this buffer"))
  8782. (t (setq link nil)))
  8783. ;; We're done setting link and desc, clean up
  8784. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8785. (setq link (or link cpltxt)
  8786. desc (or desc cpltxt))
  8787. (cond ((not desc))
  8788. ((equal desc "NONE") (setq desc nil))
  8789. (t (setq desc
  8790. (replace-regexp-in-string
  8791. org-bracket-link-analytic-regexp
  8792. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8793. desc))))
  8794. ;; Return the link
  8795. (if (not (and (or (called-interactively-p 'any)
  8796. executing-kbd-macro)
  8797. link))
  8798. (or agenda-link (and link (org-make-link-string link desc)))
  8799. (push (list link desc) org-stored-links)
  8800. (message "Stored: %s" (or desc link))
  8801. (when custom-id
  8802. (setq link (concat "file:" (abbreviate-file-name
  8803. (buffer-file-name)) "::#" custom-id))
  8804. (push (list link desc) org-stored-links))
  8805. (car org-stored-links)))))
  8806. (defun org-store-link-props (&rest plist)
  8807. "Store link properties, extract names, addresses and dates."
  8808. (let ((x (plist-get plist :from)))
  8809. (when x
  8810. (let ((adr (mail-extract-address-components x)))
  8811. (setq plist (plist-put plist :fromname (car adr)))
  8812. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8813. (let ((x (plist-get plist :to)))
  8814. (when x
  8815. (let ((adr (mail-extract-address-components x)))
  8816. (setq plist (plist-put plist :toname (car adr)))
  8817. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8818. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8819. (when x
  8820. (setq plist (plist-put plist :date-timestamp
  8821. (format-time-string
  8822. (org-time-stamp-format t) x)))
  8823. (setq plist (plist-put plist :date-timestamp-inactive
  8824. (format-time-string
  8825. (org-time-stamp-format t t) x)))))
  8826. (let ((from (plist-get plist :from))
  8827. (to (plist-get plist :to)))
  8828. (when (and from to org-from-is-user-regexp)
  8829. (setq plist
  8830. (plist-put plist :fromto
  8831. (if (string-match org-from-is-user-regexp from)
  8832. (concat "to %t")
  8833. (concat "from %f"))))))
  8834. (setq org-store-link-plist plist))
  8835. (defun org-add-link-props (&rest plist)
  8836. "Add these properties to the link property list."
  8837. (let (key value)
  8838. (while plist
  8839. (setq key (pop plist) value (pop plist))
  8840. (setq org-store-link-plist
  8841. (plist-put org-store-link-plist key value)))))
  8842. (defun org-email-link-description (&optional fmt)
  8843. "Return the description part of an email link.
  8844. This takes information from `org-store-link-plist' and formats it
  8845. according to FMT (default from `org-email-link-description-format')."
  8846. (setq fmt (or fmt org-email-link-description-format))
  8847. (let* ((p org-store-link-plist)
  8848. (to (plist-get p :toaddress))
  8849. (from (plist-get p :fromaddress))
  8850. (table
  8851. (list
  8852. (cons "%c" (plist-get p :fromto))
  8853. (cons "%F" (plist-get p :from))
  8854. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8855. (cons "%T" (plist-get p :to))
  8856. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8857. (cons "%s" (plist-get p :subject))
  8858. (cons "%d" (plist-get p :date))
  8859. (cons "%m" (plist-get p :message-id)))))
  8860. (when (string-match "%c" fmt)
  8861. ;; Check if the user wrote this message
  8862. (if (and org-from-is-user-regexp from to
  8863. (save-match-data (string-match org-from-is-user-regexp from)))
  8864. (setq fmt (replace-match "to %t" t t fmt))
  8865. (setq fmt (replace-match "from %f" t t fmt))))
  8866. (org-replace-escapes fmt table)))
  8867. (defun org-make-org-heading-search-string (&optional string)
  8868. "Make search string for the current headline or STRING."
  8869. (let ((s (or string
  8870. (and (derived-mode-p 'org-mode)
  8871. (save-excursion
  8872. (org-back-to-heading t)
  8873. (org-element-property :raw-value (org-element-at-point))))))
  8874. (lines org-context-in-file-links))
  8875. (or string (setq s (concat "*" s))) ; Add * for headlines
  8876. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8877. (when (and string (integerp lines) (> lines 0))
  8878. (let ((slines (org-split-string s "\n")))
  8879. (when (< lines (length slines))
  8880. (setq s (mapconcat
  8881. 'identity
  8882. (reverse (nthcdr (- (length slines) lines)
  8883. (reverse slines))) "\n")))))
  8884. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8885. (defun org-make-link-string (link &optional description)
  8886. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8887. (unless (org-string-nw-p link) (error "Empty link"))
  8888. (let ((uri (cond ((string-match org-link-types-re link)
  8889. (concat (match-string 1 link)
  8890. (org-link-escape (substring link (match-end 1)))))
  8891. ;; For readability, url-encode internal links only
  8892. ;; when absolutely needed (i.e, when they contain
  8893. ;; square brackets). File links however, are
  8894. ;; encoded since, e.g., spaces are significant.
  8895. ((or (file-name-absolute-p link)
  8896. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8897. (org-link-escape link))
  8898. (t link)))
  8899. (description
  8900. (and (org-string-nw-p description)
  8901. ;; Remove brackets from description, as they are fatal.
  8902. (replace-regexp-in-string
  8903. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8904. (org-trim description)))))
  8905. (format "[[%s]%s]"
  8906. uri
  8907. (if description (format "[%s]" description) ""))))
  8908. (defconst org-link-escape-chars
  8909. ;;%20 %5B %5D %25
  8910. '(?\s ?\[ ?\] ?%)
  8911. "List of characters that should be escaped in a link when stored to Org.
  8912. This is the list that is used for internal purposes.")
  8913. (defun org-link-escape (text &optional table merge)
  8914. "Return percent escaped representation of TEXT.
  8915. TEXT is a string with the text to escape.
  8916. Optional argument TABLE is a list with characters that should be
  8917. escaped. When nil, `org-link-escape-chars' is used.
  8918. If optional argument MERGE is set, merge TABLE into
  8919. `org-link-escape-chars'."
  8920. (let ((characters-to-encode
  8921. (cond ((null table) org-link-escape-chars)
  8922. (merge (append org-link-escape-chars table))
  8923. (t table))))
  8924. (mapconcat
  8925. (lambda (c)
  8926. (if (or (memq c characters-to-encode)
  8927. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8928. (mapconcat (lambda (e) (format "%%%.2X" e))
  8929. (or (encode-coding-char c 'utf-8)
  8930. (error "Unable to percent escape character: %c" c))
  8931. "")
  8932. (char-to-string c)))
  8933. text "")))
  8934. (defun org-link-unescape (str)
  8935. "Unhex hexified Unicode parts in string STR.
  8936. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8937. reciprocal of `org-link-escape', which see."
  8938. (if (org-string-nw-p str)
  8939. (replace-regexp-in-string
  8940. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8941. str))
  8942. (defun org-link-unescape-compound (hex)
  8943. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8944. Note: this function also decodes single byte encodings like
  8945. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8946. (save-match-data
  8947. (let* ((bytes (cdr (split-string hex "%")))
  8948. (ret "")
  8949. (eat 0)
  8950. (sum 0))
  8951. (while bytes
  8952. (let* ((val (string-to-number (pop bytes) 16))
  8953. (shift-xor
  8954. (if (= 0 eat)
  8955. (cond
  8956. ((>= val 252) (cons 6 252))
  8957. ((>= val 248) (cons 5 248))
  8958. ((>= val 240) (cons 4 240))
  8959. ((>= val 224) (cons 3 224))
  8960. ((>= val 192) (cons 2 192))
  8961. (t (cons 0 0)))
  8962. (cons 6 128))))
  8963. (when (>= val 192) (setq eat (car shift-xor)))
  8964. (setq val (logxor val (cdr shift-xor)))
  8965. (setq sum (+ (lsh sum (car shift-xor)) val))
  8966. (when (> eat 0) (setq eat (- eat 1)))
  8967. (cond
  8968. ((= 0 eat) ;multi byte
  8969. (setq ret (concat ret (char-to-string sum)))
  8970. (setq sum 0))
  8971. ((not bytes) ; single byte(s)
  8972. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8973. ret)))
  8974. (defun org-link-unescape-single-byte-sequence (hex)
  8975. "Unhexify hex-encoded single byte character sequences."
  8976. (mapconcat (lambda (byte)
  8977. (char-to-string (string-to-number byte 16)))
  8978. (cdr (split-string hex "%")) ""))
  8979. (defun org-xor (a b)
  8980. "Exclusive or."
  8981. (if a (not b) b))
  8982. (defun org-fixup-message-id-for-http (s)
  8983. "Replace special characters in a message id, so it can be used in an http query."
  8984. (when (string-match "%" s)
  8985. (setq s (mapconcat (lambda (c)
  8986. (if (eq c ?%)
  8987. "%25"
  8988. (char-to-string c)))
  8989. s "")))
  8990. (while (string-match "<" s)
  8991. (setq s (replace-match "%3C" t t s)))
  8992. (while (string-match ">" s)
  8993. (setq s (replace-match "%3E" t t s)))
  8994. (while (string-match "@" s)
  8995. (setq s (replace-match "%40" t t s)))
  8996. s)
  8997. (defun org-link-prettify (link)
  8998. "Return a human-readable representation of LINK.
  8999. The car of LINK must be a raw link.
  9000. The cdr of LINK must be either a link description or nil."
  9001. (let ((desc (or (cadr link) "<no description>")))
  9002. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9003. "<" (car link) ">")))
  9004. ;;;###autoload
  9005. (defun org-insert-link-global ()
  9006. "Insert a link like Org mode does.
  9007. This command can be called in any mode to insert a link in Org syntax."
  9008. (interactive)
  9009. (org-load-modules-maybe)
  9010. (org-run-like-in-org-mode 'org-insert-link))
  9011. (defun org-insert-all-links (arg &optional pre post)
  9012. "Insert all links in `org-stored-links'.
  9013. When a universal prefix, do not delete the links from `org-stored-links'.
  9014. When `ARG' is a number, insert the last N link(s).
  9015. `PRE' and `POST' are optional arguments to define a string to
  9016. prepend or to append."
  9017. (interactive "P")
  9018. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9019. (links (copy-sequence org-stored-links))
  9020. (pr (or pre "- "))
  9021. (po (or post "\n"))
  9022. (cnt 1) l)
  9023. (if (null org-stored-links)
  9024. (message "No link to insert")
  9025. (while (and (or (listp arg) (>= arg cnt))
  9026. (setq l (if (listp arg)
  9027. (pop links)
  9028. (pop org-stored-links))))
  9029. (setq cnt (1+ cnt))
  9030. (insert pr)
  9031. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9032. (insert po)))))
  9033. (defun org-insert-last-stored-link (arg)
  9034. "Insert the last link stored in `org-stored-links'."
  9035. (interactive "p")
  9036. (org-insert-all-links arg "" "\n"))
  9037. (defun org-link-fontify-links-to-this-file ()
  9038. "Fontify links to the current file in `org-stored-links'."
  9039. (let ((f (buffer-file-name)) a b)
  9040. (setq a (mapcar (lambda(l)
  9041. (let ((ll (car l)))
  9042. (when (and (string-match "^file:\\(.+\\)::" ll)
  9043. (equal f (expand-file-name (match-string 1 ll))))
  9044. ll)))
  9045. org-stored-links))
  9046. (when (featurep 'org-id)
  9047. (setq b (mapcar (lambda(l)
  9048. (let ((ll (car l)))
  9049. (when (and (string-match "^id:\\(.+\\)$" ll)
  9050. (equal f (expand-file-name
  9051. (or (org-id-find-id-file
  9052. (match-string 1 ll)) ""))))
  9053. ll)))
  9054. org-stored-links)))
  9055. (mapcar (lambda(l)
  9056. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9057. (delq nil (append a b)))))
  9058. (defvar org--links-history nil)
  9059. (defun org-insert-link (&optional complete-file link-location default-description)
  9060. "Insert a link. At the prompt, enter the link.
  9061. Completion can be used to insert any of the link protocol prefixes in use.
  9062. The history can be used to select a link previously stored with
  9063. `org-store-link'. When the empty string is entered (i.e. if you just
  9064. press `RET' at the prompt), the link defaults to the most recently
  9065. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9066. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9067. You will also be prompted for a description, and if one is given, it will
  9068. be displayed in the buffer instead of the link.
  9069. If there is already a link at point, this command will allow you to edit
  9070. link and description parts.
  9071. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9072. file name can be
  9073. selected using completion. The path to the file will be relative to the
  9074. current directory if the file is in the current directory or a subdirectory.
  9075. Otherwise, the link will be the absolute path as completed in the minibuffer
  9076. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9077. option `org-link-file-path-type'.
  9078. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9079. absolute path even if the file is in
  9080. the current directory or below.
  9081. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9082. prefix negates `org-keep-stored-link-after-insertion'.
  9083. If `org-make-link-description-function' is non-nil, this function will be
  9084. called with the link target, and the result will be the default
  9085. link description.
  9086. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9087. the link location instead of reading one interactively.
  9088. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9089. as the default description."
  9090. (interactive "P")
  9091. (let* ((wcf (current-window-configuration))
  9092. (origbuf (current-buffer))
  9093. (region (when (org-region-active-p)
  9094. (buffer-substring (region-beginning) (region-end))))
  9095. (remove (and region (list (region-beginning) (region-end))))
  9096. (desc region)
  9097. (link link-location)
  9098. (abbrevs org-link-abbrev-alist-local)
  9099. entry all-prefixes auto-desc)
  9100. (cond
  9101. (link-location) ; specified by arg, just use it.
  9102. ((org-in-regexp org-bracket-link-regexp 1)
  9103. ;; We do have a link at point, and we are going to edit it.
  9104. (setq remove (list (match-beginning 0) (match-end 0)))
  9105. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9106. (setq link (read-string "Link: "
  9107. (org-link-unescape
  9108. (match-string-no-properties 1)))))
  9109. ((or (org-in-regexp org-angle-link-re)
  9110. (org-in-regexp org-plain-link-re))
  9111. ;; Convert to bracket link
  9112. (setq remove (list (match-beginning 0) (match-end 0))
  9113. link (read-string "Link: "
  9114. (org-unbracket-string "<" ">" (match-string 0)))))
  9115. ((member complete-file '((4) (16)))
  9116. ;; Completing read for file names.
  9117. (setq link (org-file-complete-link complete-file)))
  9118. (t
  9119. ;; Read link, with completion for stored links.
  9120. (org-link-fontify-links-to-this-file)
  9121. (org-switch-to-buffer-other-window "*Org Links*")
  9122. (with-current-buffer "*Org Links*"
  9123. (erase-buffer)
  9124. (insert "Insert a link.
  9125. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9126. (when org-stored-links
  9127. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9128. (insert (mapconcat 'org-link-prettify
  9129. (reverse org-stored-links) "\n")))
  9130. (goto-char (point-min)))
  9131. (let ((cw (selected-window)))
  9132. (select-window (get-buffer-window "*Org Links*" 'visible))
  9133. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9134. (unless (pos-visible-in-window-p (point-max))
  9135. (org-fit-window-to-buffer))
  9136. (and (window-live-p cw) (select-window cw)))
  9137. (setq all-prefixes (append (mapcar 'car abbrevs)
  9138. (mapcar 'car org-link-abbrev-alist)
  9139. (org-link-types)))
  9140. (unwind-protect
  9141. ;; Fake a link history, containing the stored links.
  9142. (let ((org--links-history
  9143. (append (mapcar #'car org-stored-links)
  9144. org-insert-link-history)))
  9145. (setq link
  9146. (org-completing-read
  9147. "Link: "
  9148. (append
  9149. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9150. (mapcar #'car org-stored-links))
  9151. nil nil nil
  9152. 'org--links-history
  9153. (caar org-stored-links)))
  9154. (unless (org-string-nw-p link) (user-error "No link selected"))
  9155. (dolist (l org-stored-links)
  9156. (when (equal link (cadr l))
  9157. (setq link (car l))
  9158. (setq auto-desc t)))
  9159. (when (or (member link all-prefixes)
  9160. (and (equal ":" (substring link -1))
  9161. (member (substring link 0 -1) all-prefixes)
  9162. (setq link (substring link 0 -1))))
  9163. (setq link (with-current-buffer origbuf
  9164. (org-link-try-special-completion link)))))
  9165. (set-window-configuration wcf)
  9166. (kill-buffer "*Org Links*"))
  9167. (setq entry (assoc link org-stored-links))
  9168. (or entry (push link org-insert-link-history))
  9169. (setq desc (or desc (nth 1 entry)))))
  9170. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9171. (not org-keep-stored-link-after-insertion))
  9172. (setq org-stored-links (delq (assoc link org-stored-links)
  9173. org-stored-links)))
  9174. (when (and (string-match org-plain-link-re link)
  9175. (not (string-match org-ts-regexp link)))
  9176. ;; URL-like link, normalize the use of angular brackets.
  9177. (setq link (org-unbracket-string "<" ">" link)))
  9178. ;; Check if we are linking to the current file with a search
  9179. ;; option If yes, simplify the link by using only the search
  9180. ;; option.
  9181. (when (and buffer-file-name
  9182. (let ((case-fold-search nil))
  9183. (string-match "\\`file:\\(.+?\\)::" link)))
  9184. (let ((path (match-string-no-properties 1 link))
  9185. (search (substring-no-properties link (match-end 0))))
  9186. (save-match-data
  9187. (when (equal (file-truename buffer-file-name) (file-truename path))
  9188. ;; We are linking to this same file, with a search option
  9189. (setq link search)))))
  9190. ;; Check if we can/should use a relative path. If yes, simplify the link
  9191. (let ((case-fold-search nil))
  9192. (when (string-match "\\`\\(file\\|docview\\):" link)
  9193. (let* ((type (match-string-no-properties 0 link))
  9194. (path (substring-no-properties link (match-end 0)))
  9195. (origpath path))
  9196. (cond
  9197. ((or (eq org-link-file-path-type 'absolute)
  9198. (equal complete-file '(16)))
  9199. (setq path (abbreviate-file-name (expand-file-name path))))
  9200. ((eq org-link-file-path-type 'noabbrev)
  9201. (setq path (expand-file-name path)))
  9202. ((eq org-link-file-path-type 'relative)
  9203. (setq path (file-relative-name path)))
  9204. (t
  9205. (save-match-data
  9206. (if (string-match (concat "^" (regexp-quote
  9207. (expand-file-name
  9208. (file-name-as-directory
  9209. default-directory))))
  9210. (expand-file-name path))
  9211. ;; We are linking a file with relative path name.
  9212. (setq path (substring (expand-file-name path)
  9213. (match-end 0)))
  9214. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9215. (setq link (concat type path))
  9216. (when (equal desc origpath)
  9217. (setq desc path)))))
  9218. (if org-make-link-description-function
  9219. (setq desc
  9220. (or (condition-case nil
  9221. (funcall org-make-link-description-function link desc)
  9222. (error (progn (message "Can't get link description from `%s'"
  9223. (symbol-name org-make-link-description-function))
  9224. (sit-for 2) nil)))
  9225. (read-string "Description: " default-description)))
  9226. (if default-description (setq desc default-description)
  9227. (setq desc (or (and auto-desc desc)
  9228. (read-string "Description: " desc)))))
  9229. (unless (string-match "\\S-" desc) (setq desc nil))
  9230. (when remove (apply 'delete-region remove))
  9231. (insert (org-make-link-string link desc))
  9232. ;; Redisplay so as the new link has proper invisible characters.
  9233. (sit-for 0)))
  9234. (defun org-link-try-special-completion (type)
  9235. "If there is completion support for link type TYPE, offer it."
  9236. (let ((fun (org-link-get-parameter type :complete)))
  9237. (if (functionp fun)
  9238. (funcall fun)
  9239. (read-string "Link (no completion support): " (concat type ":")))))
  9240. (defun org-file-complete-link (&optional arg)
  9241. "Create a file link using completion."
  9242. (let ((file (read-file-name "File: "))
  9243. (pwd (file-name-as-directory (expand-file-name ".")))
  9244. (pwd1 (file-name-as-directory (abbreviate-file-name
  9245. (expand-file-name ".")))))
  9246. (cond ((equal arg '(16))
  9247. (concat "file:"
  9248. (abbreviate-file-name (expand-file-name file))))
  9249. ((string-match
  9250. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9251. (concat "file:" (match-string 1 file)))
  9252. ((string-match
  9253. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9254. (expand-file-name file))
  9255. (concat "file:"
  9256. (match-string 1 (expand-file-name file))))
  9257. (t (concat "file:" file)))))
  9258. (defun org-completing-read (&rest args)
  9259. "Completing-read with SPACE being a normal character."
  9260. (let ((enable-recursive-minibuffers t)
  9261. (minibuffer-local-completion-map
  9262. (copy-keymap minibuffer-local-completion-map)))
  9263. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9264. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9265. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9266. 'org-time-stamp-inactive)
  9267. (apply #'completing-read args)))
  9268. ;;; Opening/following a link
  9269. (defvar org-link-search-failed nil)
  9270. (defvar org-open-link-functions nil
  9271. "Hook for functions finding a plain text link.
  9272. These functions must take a single argument, the link content.
  9273. They will be called for links that look like [[link text][description]]
  9274. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9275. like a filename (e.g. \"./blue.png\").
  9276. These functions will be called *before* Org attempts to resolve the
  9277. link by doing text searches in the current buffer - so if you want a
  9278. link \"[[target]]\" to still find \"<<target>>\", your function should
  9279. handle this as a special case.
  9280. When the function does handle the link, it must return a non-nil value.
  9281. If it decides that it is not responsible for this link, it must return
  9282. nil to indicate that that Org can continue with other options like
  9283. exact and fuzzy text search.")
  9284. (defun org-next-link (&optional search-backward)
  9285. "Move forward to the next link.
  9286. If the link is in hidden text, expose it."
  9287. (interactive "P")
  9288. (when (and org-link-search-failed (eq this-command last-command))
  9289. (goto-char (point-min))
  9290. (message "Link search wrapped back to beginning of buffer"))
  9291. (setq org-link-search-failed nil)
  9292. (let* ((pos (point))
  9293. (ct (org-context))
  9294. (a (assq :link ct))
  9295. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9296. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9297. ((looking-at org-any-link-re)
  9298. ;; Don't stay stuck at link without an org-link face
  9299. (forward-char (if search-backward -1 1))))
  9300. (if (funcall srch-fun org-any-link-re nil t)
  9301. (progn
  9302. (goto-char (match-beginning 0))
  9303. (when (outline-invisible-p) (org-show-context)))
  9304. (goto-char pos)
  9305. (setq org-link-search-failed t)
  9306. (message "No further link found"))))
  9307. (defun org-previous-link ()
  9308. "Move backward to the previous link.
  9309. If the link is in hidden text, expose it."
  9310. (interactive)
  9311. (funcall 'org-next-link t))
  9312. (defun org-translate-link (s)
  9313. "Translate a link string if a translation function has been defined."
  9314. (with-temp-buffer
  9315. (insert (org-trim s))
  9316. (org-trim (org-element-interpret-data (org-element-context)))))
  9317. (defun org-translate-link-from-planner (type path)
  9318. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9319. This is still an experimental function, your mileage may vary."
  9320. (cond
  9321. ((member type '("http" "https" "news" "ftp"))
  9322. ;; standard Internet links are the same.
  9323. nil)
  9324. ((and (equal type "irc") (string-match "^//" path))
  9325. ;; Planner has two / at the beginning of an irc link, we have 1.
  9326. ;; We should have zero, actually....
  9327. (setq path (substring path 1)))
  9328. ((and (equal type "lisp") (string-match "^/" path))
  9329. ;; Planner has a slash, we do not.
  9330. (setq type "elisp" path (substring path 1)))
  9331. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9332. ;; A typical message link. Planner has the id after the final slash,
  9333. ;; we separate it with a hash mark
  9334. (setq path (concat (match-string 1 path) "#"
  9335. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9336. (cons type path))
  9337. (defun org-find-file-at-mouse (ev)
  9338. "Open file link or URL at mouse."
  9339. (interactive "e")
  9340. (mouse-set-point ev)
  9341. (org-open-at-point 'in-emacs))
  9342. (defun org-open-at-mouse (ev)
  9343. "Open file link or URL at mouse.
  9344. See the docstring of `org-open-file' for details."
  9345. (interactive "e")
  9346. (mouse-set-point ev)
  9347. (when (eq major-mode 'org-agenda-mode)
  9348. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9349. (org-open-at-point))
  9350. (defvar org-window-config-before-follow-link nil
  9351. "The window configuration before following a link.
  9352. This is saved in case the need arises to restore it.")
  9353. ;;;###autoload
  9354. (defun org-open-at-point-global ()
  9355. "Follow a link or time-stamp like Org mode does.
  9356. This command can be called in any mode to follow an external link
  9357. or a time-stamp that has Org mode syntax. Its behavior is
  9358. undefined when called on internal links (e.g., fuzzy links).
  9359. Raise an error when there is nothing to follow. "
  9360. (interactive)
  9361. (cond ((org-in-regexp org-any-link-re)
  9362. (org-open-link-from-string (match-string-no-properties 0)))
  9363. ((or (org-in-regexp org-ts-regexp-both nil t)
  9364. (org-in-regexp org-tsr-regexp-both nil t))
  9365. (org-follow-timestamp-link))
  9366. (t (user-error "No link found"))))
  9367. ;;;###autoload
  9368. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9369. "Open a link in the string S, as if it was in Org mode."
  9370. (interactive "sLink: \nP")
  9371. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9372. (with-temp-buffer
  9373. (let ((org-inhibit-startup (not reference-buffer)))
  9374. (org-mode)
  9375. (insert s)
  9376. (goto-char (point-min))
  9377. (when reference-buffer
  9378. (setq org-link-abbrev-alist-local
  9379. (with-current-buffer reference-buffer
  9380. org-link-abbrev-alist-local)))
  9381. (org-open-at-point arg reference-buffer)))))
  9382. (defvar org-open-at-point-functions nil
  9383. "Hook that is run when following a link at point.
  9384. Functions in this hook must return t if they identify and follow
  9385. a link at point. If they don't find anything interesting at point,
  9386. they must return nil.")
  9387. (defvar org-link-search-inhibit-query nil)
  9388. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9389. (defun org--open-doi-link (path)
  9390. "Open a \"doi\" type link.
  9391. PATH is a the path to search for, as a string."
  9392. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9393. (defun org--open-elisp-link (path)
  9394. "Open a \"elisp\" type link.
  9395. PATH is the sexp to evaluate, as a string."
  9396. (let ((cmd path))
  9397. (if (or (and (org-string-nw-p
  9398. org-confirm-elisp-link-not-regexp)
  9399. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9400. (not org-confirm-elisp-link-function)
  9401. (funcall org-confirm-elisp-link-function
  9402. (format "Execute \"%s\" as elisp? "
  9403. (org-add-props cmd nil 'face 'org-warning))))
  9404. (message "%s => %s" cmd
  9405. (if (eq (string-to-char cmd) ?\()
  9406. (eval (read cmd))
  9407. (call-interactively (read cmd))))
  9408. (user-error "Abort"))))
  9409. (defun org--open-help-link (path)
  9410. "Open a \"help\" type link.
  9411. PATH is a symbol name, as a string."
  9412. (pcase (intern path)
  9413. ((and (pred fboundp) variable) (describe-function variable))
  9414. ((and (pred boundp) function) (describe-variable function))
  9415. (name (user-error "Unknown function or variable: %s" name))))
  9416. (defun org--open-shell-link (path)
  9417. "Open a \"shell\" type link.
  9418. PATH is the command to execute, as a string."
  9419. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9420. (cmd path))
  9421. (if (or (and (org-string-nw-p
  9422. org-confirm-shell-link-not-regexp)
  9423. (string-match
  9424. org-confirm-shell-link-not-regexp cmd))
  9425. (not org-confirm-shell-link-function)
  9426. (funcall org-confirm-shell-link-function
  9427. (format "Execute \"%s\" in shell? "
  9428. (org-add-props cmd nil
  9429. 'face 'org-warning))))
  9430. (progn
  9431. (message "Executing %s" cmd)
  9432. (shell-command cmd buf)
  9433. (when (featurep 'midnight)
  9434. (setq clean-buffer-list-kill-buffer-names
  9435. (cons (buffer-name buf)
  9436. clean-buffer-list-kill-buffer-names))))
  9437. (user-error "Abort"))))
  9438. (defun org-open-at-point (&optional arg reference-buffer)
  9439. "Open link, timestamp, footnote or tags at point.
  9440. When point is on a link, follow it. Normally, files will be
  9441. opened by an appropriate application. If the optional prefix
  9442. argument ARG is non-nil, Emacs will visit the file. With
  9443. a double prefix argument, try to open outside of Emacs, in the
  9444. application the system uses for this file type.
  9445. When point is on a timestamp, open the agenda at the day
  9446. specified.
  9447. When point is a footnote definition, move to the first reference
  9448. found. If it is on a reference, move to the associated
  9449. definition.
  9450. When point is on a headline, display a list of every link in the
  9451. entry, so it is possible to pick one, or all, of them. If point
  9452. is on a tag, call `org-tags-view' instead.
  9453. When optional argument REFERENCE-BUFFER is non-nil, it should
  9454. specify a buffer from where the link search should happen. This
  9455. is used internally by `org-open-link-from-string'.
  9456. On top of syntactically correct links, this function will open
  9457. the link at point in comments or comment blocks and the first
  9458. link in a property drawer line."
  9459. (interactive "P")
  9460. ;; On a code block, open block's results.
  9461. (unless (call-interactively 'org-babel-open-src-block-result)
  9462. (org-load-modules-maybe)
  9463. (setq org-window-config-before-follow-link (current-window-configuration))
  9464. (org-remove-occur-highlights nil nil t)
  9465. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9466. (let* ((context
  9467. ;; Only consider supported types, even if they are not
  9468. ;; the closest one.
  9469. (org-element-lineage
  9470. (org-element-context)
  9471. '(clock comment comment-block footnote-definition
  9472. footnote-reference headline inlinetask keyword link
  9473. node-property timestamp)
  9474. t))
  9475. (type (org-element-type context))
  9476. (value (org-element-property :value context)))
  9477. (cond
  9478. ((not context) (user-error "No link found"))
  9479. ;; Exception: open timestamps and links in properties
  9480. ;; drawers, keywords and comments.
  9481. ((memq type '(comment comment-block keyword node-property))
  9482. (call-interactively #'org-open-at-point-global))
  9483. ;; On a headline or an inlinetask, but not on a timestamp,
  9484. ;; a link, a footnote reference or on tags.
  9485. ((and (memq type '(headline inlinetask))
  9486. ;; Not on tags.
  9487. (let ((case-fold-search nil))
  9488. (save-excursion
  9489. (beginning-of-line)
  9490. (looking-at org-complex-heading-regexp))
  9491. (or (not (match-beginning 5))
  9492. (< (point) (match-beginning 5)))))
  9493. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9494. (links (car data))
  9495. (links-end (cdr data)))
  9496. (if links
  9497. (dolist (link (if (stringp links) (list links) links))
  9498. (search-forward link nil links-end)
  9499. (goto-char (match-beginning 0))
  9500. (org-open-at-point))
  9501. (require 'org-attach)
  9502. (org-attach-reveal 'if-exists))))
  9503. ;; On a clock line, make sure point is on the timestamp
  9504. ;; before opening it.
  9505. ((and (eq type 'clock)
  9506. value
  9507. (>= (point) (org-element-property :begin value))
  9508. (<= (point) (org-element-property :end value)))
  9509. (org-follow-timestamp-link))
  9510. ;; Do nothing on white spaces after an object.
  9511. ((>= (point)
  9512. (save-excursion
  9513. (goto-char (org-element-property :end context))
  9514. (skip-chars-backward " \t")
  9515. (point)))
  9516. (user-error "No link found"))
  9517. ((eq type 'timestamp) (org-follow-timestamp-link))
  9518. ;; On tags within a headline or an inlinetask.
  9519. ((and (memq type '(headline inlinetask))
  9520. (let ((case-fold-search nil))
  9521. (save-excursion (beginning-of-line)
  9522. (looking-at org-complex-heading-regexp))
  9523. (and (match-beginning 5)
  9524. (>= (point) (match-beginning 5)))))
  9525. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9526. ((eq type 'link)
  9527. (let ((type (org-element-property :type context))
  9528. (path (org-link-unescape (org-element-property :path context))))
  9529. ;; Switch back to REFERENCE-BUFFER needed when called in
  9530. ;; a temporary buffer through `org-open-link-from-string'.
  9531. (with-current-buffer (or reference-buffer (current-buffer))
  9532. (cond
  9533. ((equal type "file")
  9534. (if (string-match "[*?{]" (file-name-nondirectory path))
  9535. (dired path)
  9536. ;; Look into `org-link-parameters' in order to find
  9537. ;; a DEDICATED-FUNCTION to open file. The function
  9538. ;; will be applied on raw link instead of parsed
  9539. ;; link due to the limitation in `org-add-link-type'
  9540. ;; ("open" function called with a single argument).
  9541. ;; If no such function is found, fallback to
  9542. ;; `org-open-file'.
  9543. (let* ((option (org-element-property :search-option context))
  9544. (app (org-element-property :application context))
  9545. (dedicated-function
  9546. (org-link-get-parameter
  9547. (if app (concat type "+" app) type)
  9548. :follow)))
  9549. (if dedicated-function
  9550. (funcall dedicated-function
  9551. (concat path
  9552. (and option (concat "::" option))))
  9553. (apply #'org-open-file
  9554. path
  9555. (cond (arg)
  9556. ((equal app "emacs") 'emacs)
  9557. ((equal app "sys") 'system))
  9558. (cond ((not option) nil)
  9559. ((string-match-p "\\`[0-9]+\\'" option)
  9560. (list (string-to-number option)))
  9561. (t (list nil
  9562. (org-link-unescape option)))))))))
  9563. ((functionp (org-link-get-parameter type :follow))
  9564. (funcall (org-link-get-parameter type :follow) path))
  9565. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9566. (unless (run-hook-with-args-until-success
  9567. 'org-open-link-functions path)
  9568. (if (not arg) (org-mark-ring-push)
  9569. (switch-to-buffer-other-window
  9570. (org-get-buffer-for-internal-link (current-buffer))))
  9571. (let ((destination
  9572. (org-with-wide-buffer
  9573. (if (equal type "radio")
  9574. (org-search-radio-target
  9575. (org-element-property :path context))
  9576. (org-link-search
  9577. (if (member type '("custom-id" "coderef"))
  9578. (org-element-property :raw-link context)
  9579. path)
  9580. ;; Prevent fuzzy links from matching
  9581. ;; themselves.
  9582. (and (equal type "fuzzy")
  9583. (+ 2 (org-element-property :begin context)))))
  9584. (point))))
  9585. (unless (and (<= (point-min) destination)
  9586. (>= (point-max) destination))
  9587. (widen))
  9588. (goto-char destination))))
  9589. (t (browse-url-at-point))))))
  9590. ;; On a footnote reference or at a footnote definition's label.
  9591. ((or (eq type 'footnote-reference)
  9592. (and (eq type 'footnote-definition)
  9593. (save-excursion
  9594. ;; Do not validate action when point is on the
  9595. ;; spaces right after the footnote label, in
  9596. ;; order to be on par with behaviour on links.
  9597. (skip-chars-forward " \t")
  9598. (let ((begin
  9599. (org-element-property :contents-begin context)))
  9600. (if begin (< (point) begin)
  9601. (= (org-element-property :post-affiliated context)
  9602. (line-beginning-position)))))))
  9603. (org-footnote-action))
  9604. (t (user-error "No link found")))))
  9605. (run-hook-with-args 'org-follow-link-hook)))
  9606. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9607. "Offer links in the current entry and return the selected link.
  9608. If there is only one link, return it.
  9609. If NTH is an integer, return the NTH link found.
  9610. If ZERO is a string, check also this string for a link, and if
  9611. there is one, return it."
  9612. (with-current-buffer buffer
  9613. (org-with-wide-buffer
  9614. (goto-char marker)
  9615. (let ((cnt ?0)
  9616. have-zero end links link c)
  9617. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9618. (push (match-string 0 zero) links)
  9619. (setq cnt (1- cnt) have-zero t))
  9620. (save-excursion
  9621. (org-back-to-heading t)
  9622. (setq end (save-excursion (outline-next-heading) (point)))
  9623. (while (re-search-forward org-any-link-re end t)
  9624. (push (match-string 0) links))
  9625. (setq links (org-uniquify (reverse links))))
  9626. (cond
  9627. ((null links)
  9628. (message "No links"))
  9629. ((equal (length links) 1)
  9630. (setq link (car links)))
  9631. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9632. (setq link (nth (if have-zero nth (1- nth)) links)))
  9633. (t ; we have to select a link
  9634. (save-excursion
  9635. (save-window-excursion
  9636. (delete-other-windows)
  9637. (with-output-to-temp-buffer "*Select Link*"
  9638. (dolist (l links)
  9639. (cond
  9640. ((not (string-match org-bracket-link-regexp l))
  9641. (princ (format "[%c] %s\n" (cl-incf cnt)
  9642. (org-unbracket-string "<" ">" l))))
  9643. ((match-end 3)
  9644. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9645. (match-string 3 l) (match-string 1 l))))
  9646. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9647. (match-string 1 l)))))))
  9648. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9649. (message "Select link to open, RET to open all:")
  9650. (setq c (read-char-exclusive))
  9651. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9652. (when (equal c ?q) (user-error "Abort"))
  9653. (if (equal c ?\C-m)
  9654. (setq link links)
  9655. (setq nth (- c ?0))
  9656. (when have-zero (setq nth (1+ nth)))
  9657. (unless (and (integerp nth) (>= (length links) nth))
  9658. (user-error "Invalid link selection"))
  9659. (setq link (nth (1- nth) links)))))
  9660. (cons link end)))))
  9661. ;; TODO: These functions are deprecated since `org-open-at-point'
  9662. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9663. (defun org-open-file-with-system (path)
  9664. "Open file at PATH using the system way of opening it."
  9665. (org-open-file path 'system))
  9666. (defun org-open-file-with-emacs (path)
  9667. "Open file at PATH in Emacs."
  9668. (org-open-file path 'emacs))
  9669. ;;; File search
  9670. (defvar org-create-file-search-functions nil
  9671. "List of functions to construct the right search string for a file link.
  9672. These functions are called in turn with point at the location to
  9673. which the link should point.
  9674. A function in the hook should first test if it would like to
  9675. handle this file type, for example by checking the `major-mode'
  9676. or the file extension. If it decides not to handle this file, it
  9677. should just return nil to give other functions a chance. If it
  9678. does handle the file, it must return the search string to be used
  9679. when following the link. The search string will be part of the
  9680. file link, given after a double colon, and `org-open-at-point'
  9681. will automatically search for it. If special measures must be
  9682. taken to make the search successful, another function should be
  9683. added to the companion hook `org-execute-file-search-functions',
  9684. which see.
  9685. A function in this hook may also use `setq' to set the variable
  9686. `description' to provide a suggestion for the descriptive text to
  9687. be used for this link when it gets inserted into an Org buffer
  9688. with \\[org-insert-link].")
  9689. (defvar org-execute-file-search-functions nil
  9690. "List of functions to execute a file search triggered by a link.
  9691. Functions added to this hook must accept a single argument, the
  9692. search string that was part of the file link, the part after the
  9693. double colon. The function must first check if it would like to
  9694. handle this search, for example by checking the `major-mode' or
  9695. the file extension. If it decides not to handle this search, it
  9696. should just return nil to give other functions a chance. If it
  9697. does handle the search, it must return a non-nil value to keep
  9698. other functions from trying.
  9699. Each function can access the current prefix argument through the
  9700. variable `current-prefix-arg'. Note that a single prefix is used
  9701. to force opening a link in Emacs, so it may be good to only use a
  9702. numeric or double prefix to guide the search function.
  9703. In case this is needed, a function in this hook can also restore
  9704. the window configuration before `org-open-at-point' was called using:
  9705. (set-window-configuration org-window-config-before-follow-link)")
  9706. (defun org-search-radio-target (target)
  9707. "Search a radio target matching TARGET in current buffer.
  9708. White spaces are not significant."
  9709. (let ((re (format "<<<%s>>>"
  9710. (mapconcat #'regexp-quote
  9711. (org-split-string target "[ \t\n]+")
  9712. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9713. (origin (point)))
  9714. (goto-char (point-min))
  9715. (catch :radio-match
  9716. (while (re-search-forward re nil t)
  9717. (backward-char)
  9718. (let ((object (org-element-context)))
  9719. (when (eq (org-element-type object) 'radio-target)
  9720. (goto-char (org-element-property :begin object))
  9721. (org-show-context 'link-search)
  9722. (throw :radio-match nil))))
  9723. (goto-char origin)
  9724. (user-error "No match for radio target: %s" target))))
  9725. (defun org-link-search (s &optional avoid-pos stealth)
  9726. "Search for a search string S.
  9727. If S starts with \"#\", it triggers a custom ID search.
  9728. If S is enclosed within parenthesis, it initiates a coderef
  9729. search.
  9730. If S is surrounded by forward slashes, it is interpreted as
  9731. a regular expression. In Org mode files, this will create an
  9732. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9733. to list matches. If the current buffer is in `dired-mode', grep
  9734. will be used to search in all files.
  9735. When AVOID-POS is given, ignore matches near that position.
  9736. When optional argument STEALTH is non-nil, do not modify
  9737. visibility around point, thus ignoring `org-show-context-detail'
  9738. variable.
  9739. Search is case-insensitive and ignores white spaces. Return type
  9740. of matched result, which is either `dedicated' or `fuzzy'."
  9741. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9742. (let* ((case-fold-search t)
  9743. (origin (point))
  9744. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9745. (starred (eq (string-to-char normalized) ?*))
  9746. (words (split-string (if starred (substring s 1) s)))
  9747. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9748. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9749. type)
  9750. (cond
  9751. ;; Check if there are any special search functions.
  9752. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9753. ((eq (string-to-char s) ?#)
  9754. ;; Look for a custom ID S if S starts with "#".
  9755. (let* ((id (substring normalized 1))
  9756. (match (org-find-property "CUSTOM_ID" id)))
  9757. (if match (progn (goto-char match) (setf type 'dedicated))
  9758. (error "No match for custom ID: %s" id))))
  9759. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9760. ;; Look for coderef targets if S is enclosed within parenthesis.
  9761. (let ((coderef (match-string-no-properties 1 normalized))
  9762. (re (substring s-single-re 1 -1)))
  9763. (goto-char (point-min))
  9764. (catch :coderef-match
  9765. (while (re-search-forward re nil t)
  9766. (let ((element (org-element-at-point)))
  9767. (when (and (memq (org-element-type element)
  9768. '(example-block src-block))
  9769. ;; Build proper regexp according to current
  9770. ;; block's label format.
  9771. (let ((label-fmt
  9772. (regexp-quote
  9773. (or (org-element-property :label-fmt element)
  9774. org-coderef-label-format))))
  9775. (save-excursion
  9776. (beginning-of-line)
  9777. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9778. (format label-fmt coderef))))))
  9779. (setq type 'dedicated)
  9780. (goto-char (match-beginning 1))
  9781. (throw :coderef-match nil))))
  9782. (goto-char origin)
  9783. (error "No match for coderef: %s" coderef))))
  9784. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9785. ;; Look for a regular expression.
  9786. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9787. (match-string 1 s)))
  9788. ;; From here, we handle fuzzy links.
  9789. ;;
  9790. ;; Look for targets, only if not in a headline search.
  9791. ((and (not starred)
  9792. (let ((target (format "<<%s>>" s-multi-re)))
  9793. (catch :target-match
  9794. (goto-char (point-min))
  9795. (while (re-search-forward target nil t)
  9796. (backward-char)
  9797. (let ((context (org-element-context)))
  9798. (when (eq (org-element-type context) 'target)
  9799. (setq type 'dedicated)
  9800. (goto-char (org-element-property :begin context))
  9801. (throw :target-match t))))
  9802. nil))))
  9803. ;; Look for elements named after S, only if not in a headline
  9804. ;; search.
  9805. ((and (not starred)
  9806. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9807. (catch :name-match
  9808. (goto-char (point-min))
  9809. (while (re-search-forward name nil t)
  9810. (let ((element (org-element-at-point)))
  9811. (when (equal words
  9812. (split-string
  9813. (org-element-property :name element)))
  9814. (setq type 'dedicated)
  9815. (beginning-of-line)
  9816. (throw :name-match t))))
  9817. nil))))
  9818. ;; Regular text search. Prefer headlines in Org mode buffers.
  9819. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9820. ;; statistics cookies and tags.
  9821. ((and (derived-mode-p 'org-mode)
  9822. (let ((title-re
  9823. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9824. org-outline-regexp-bol
  9825. org-comment-string
  9826. (mapconcat #'regexp-quote words ".+")))
  9827. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9828. (comment-re (eval-when-compile
  9829. (format "\\`%s[ \t]+" org-comment-string))))
  9830. (goto-char (point-min))
  9831. (catch :found
  9832. (while (re-search-forward title-re nil t)
  9833. (when (equal words
  9834. (split-string
  9835. (replace-regexp-in-string
  9836. cookie-re ""
  9837. (replace-regexp-in-string
  9838. comment-re "" (org-get-heading t t t)))))
  9839. (throw :found t)))
  9840. nil)))
  9841. (beginning-of-line)
  9842. (setq type 'dedicated))
  9843. ;; Offer to create non-existent headline depending on
  9844. ;; `org-link-search-must-match-exact-headline'.
  9845. ((and (derived-mode-p 'org-mode)
  9846. (not org-link-search-inhibit-query)
  9847. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9848. (yes-or-no-p "No match - create this as a new heading? "))
  9849. (goto-char (point-max))
  9850. (unless (bolp) (newline))
  9851. (org-insert-heading nil t t)
  9852. (insert s "\n")
  9853. (beginning-of-line 0))
  9854. ;; Only headlines are looked after. No need to process
  9855. ;; further: throw an error.
  9856. ((and (derived-mode-p 'org-mode)
  9857. (or starred org-link-search-must-match-exact-headline))
  9858. (goto-char origin)
  9859. (error "No match for fuzzy expression: %s" normalized))
  9860. ;; Regular text search.
  9861. ((catch :fuzzy-match
  9862. (goto-char (point-min))
  9863. (while (re-search-forward s-multi-re nil t)
  9864. ;; Skip match if it contains AVOID-POS or it is included in
  9865. ;; a link with a description but outside the description.
  9866. (unless (or (and avoid-pos
  9867. (<= (match-beginning 0) avoid-pos)
  9868. (> (match-end 0) avoid-pos))
  9869. (and (save-match-data
  9870. (org-in-regexp org-bracket-link-regexp))
  9871. (match-beginning 3)
  9872. (or (> (match-beginning 3) (point))
  9873. (<= (match-end 3) (point)))
  9874. (org-element-lineage
  9875. (save-match-data (org-element-context))
  9876. '(link) t)))
  9877. (goto-char (match-beginning 0))
  9878. (setq type 'fuzzy)
  9879. (throw :fuzzy-match t)))
  9880. nil))
  9881. ;; All failed. Throw an error.
  9882. (t (goto-char origin)
  9883. (error "No match for fuzzy expression: %s" normalized)))
  9884. ;; Disclose surroundings of match, if appropriate.
  9885. (when (and (derived-mode-p 'org-mode) (not stealth))
  9886. (org-show-context 'link-search))
  9887. type))
  9888. (defun org-get-buffer-for-internal-link (buffer)
  9889. "Return a buffer to be used for displaying the link target of internal links."
  9890. (cond
  9891. ((not org-display-internal-link-with-indirect-buffer)
  9892. buffer)
  9893. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9894. (message "Buffer is already a clone, not making another one")
  9895. ;; we also do not modify visibility in this case
  9896. buffer)
  9897. (t ; make a new indirect buffer for displaying the link
  9898. (let* ((bn (buffer-name buffer))
  9899. (ibn (concat bn "(Clone)"))
  9900. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9901. (with-current-buffer ib (org-overview))
  9902. ib))))
  9903. (defun org-do-occur (regexp &optional cleanup)
  9904. "Call the Emacs command `occur'.
  9905. If CLEANUP is non-nil, remove the printout of the regular expression
  9906. in the *Occur* buffer. This is useful if the regex is long and not useful
  9907. to read."
  9908. (occur regexp)
  9909. (when cleanup
  9910. (let ((cwin (selected-window)) win beg end)
  9911. (when (setq win (get-buffer-window "*Occur*"))
  9912. (select-window win))
  9913. (goto-char (point-min))
  9914. (when (re-search-forward "match[a-z]+" nil t)
  9915. (setq beg (match-end 0))
  9916. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9917. (setq end (1- (match-beginning 0)))))
  9918. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9919. (goto-char (point-min))
  9920. (select-window cwin))))
  9921. ;;; The mark ring for links jumps
  9922. (defvar org-mark-ring nil
  9923. "Mark ring for positions before jumps in Org mode.")
  9924. (defvar org-mark-ring-last-goto nil
  9925. "Last position in the mark ring used to go back.")
  9926. ;; Fill and close the ring
  9927. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9928. (dotimes (_ org-mark-ring-length)
  9929. (push (make-marker) org-mark-ring))
  9930. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9931. org-mark-ring)
  9932. (defun org-mark-ring-push (&optional pos buffer)
  9933. "Put the current position or POS into the mark ring and rotate it."
  9934. (interactive)
  9935. (setq pos (or pos (point)))
  9936. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9937. (move-marker (car org-mark-ring)
  9938. (or pos (point))
  9939. (or buffer (current-buffer)))
  9940. (message "%s"
  9941. (substitute-command-keys
  9942. "Position saved to mark ring, go back with \
  9943. `\\[org-mark-ring-goto]'.")))
  9944. (defun org-mark-ring-goto (&optional n)
  9945. "Jump to the previous position in the mark ring.
  9946. With prefix arg N, jump back that many stored positions. When
  9947. called several times in succession, walk through the entire ring.
  9948. Org mode commands jumping to a different position in the current file,
  9949. or to another Org file, automatically push the old position onto the ring."
  9950. (interactive "p")
  9951. (let (p m)
  9952. (if (eq last-command this-command)
  9953. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9954. (setq p org-mark-ring))
  9955. (setq org-mark-ring-last-goto p)
  9956. (setq m (car p))
  9957. (pop-to-buffer-same-window (marker-buffer m))
  9958. (goto-char m)
  9959. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9960. (defun org-add-angle-brackets (s)
  9961. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9962. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9963. s)
  9964. ;;; Following specific links
  9965. (defvar org-agenda-buffer-tmp-name)
  9966. (defvar org-agenda-start-on-weekday)
  9967. (defun org-follow-timestamp-link ()
  9968. "Open an agenda view for the time-stamp date/range at point."
  9969. (cond
  9970. ((org-at-date-range-p t)
  9971. (let ((org-agenda-start-on-weekday)
  9972. (t1 (match-string 1))
  9973. (t2 (match-string 2)) tt1 tt2)
  9974. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9975. tt2 (time-to-days (org-time-string-to-time t2)))
  9976. (let ((org-agenda-buffer-tmp-name
  9977. (format "*Org Agenda(a:%s)"
  9978. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9979. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9980. ((org-at-timestamp-p 'lax)
  9981. (let ((org-agenda-buffer-tmp-name
  9982. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9983. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9984. (substring (match-string 1) 0 10)))
  9985. 1)))
  9986. (t (error "This should not happen"))))
  9987. ;;; Following file links
  9988. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9989. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9990. (declare-function mailcap-mime-info
  9991. "mailcap" (string &optional request no-decode))
  9992. (defvar org-wait nil)
  9993. (defun org-open-file (path &optional in-emacs line search)
  9994. "Open the file at PATH.
  9995. First, this expands any special file name abbreviations. Then the
  9996. configuration variable `org-file-apps' is checked if it contains an
  9997. entry for this file type, and if yes, the corresponding command is launched.
  9998. If no application is found, Emacs simply visits the file.
  9999. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10000. With a double \\[universal-argument] \\[universal-argument] \
  10001. prefix arg, Org tries to avoid opening in Emacs
  10002. and to use an external application to visit the file.
  10003. Optional LINE specifies a line to go to, optional SEARCH a string
  10004. to search for. If LINE or SEARCH is given, the file will be
  10005. opened in Emacs, unless an entry from org-file-apps that makes
  10006. use of groups in a regexp matches.
  10007. If you want to change the way frames are used when following a
  10008. link, please customize `org-link-frame-setup'.
  10009. If the file does not exist, an error is thrown."
  10010. (let* ((file (if (equal path "")
  10011. buffer-file-name
  10012. (substitute-in-file-name (expand-file-name path))))
  10013. (file-apps (append org-file-apps (org-default-apps)))
  10014. (apps (cl-remove-if
  10015. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10016. (apps-dlink (cl-remove-if-not
  10017. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10018. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10019. (dirp (unless remp (file-directory-p file)))
  10020. (file (if (and dirp org-open-directory-means-index-dot-org)
  10021. (concat (file-name-as-directory file) "index.org")
  10022. file))
  10023. (a-m-a-p (assq 'auto-mode apps))
  10024. (dfile (downcase file))
  10025. ;; Reconstruct the original link from the PATH, LINE and
  10026. ;; SEARCH args.
  10027. (link (cond (line (concat file "::" (number-to-string line)))
  10028. (search (concat file "::" search))
  10029. (t file)))
  10030. (dlink (downcase link))
  10031. (ext
  10032. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10033. (match-string 1 dfile)))
  10034. (save-position-maybe
  10035. (let ((old-buffer (current-buffer))
  10036. (old-pos (point))
  10037. (old-mode major-mode))
  10038. (lambda ()
  10039. (and (derived-mode-p 'org-mode)
  10040. (eq old-mode 'org-mode)
  10041. (or (not (eq old-buffer (current-buffer)))
  10042. (not (eq old-pos (point))))
  10043. (org-mark-ring-push old-pos old-buffer)))))
  10044. cmd link-match-data)
  10045. (cond
  10046. ((member in-emacs '((16) system))
  10047. (setq cmd (cdr (assq 'system apps))))
  10048. (in-emacs (setq cmd 'emacs))
  10049. (t
  10050. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10051. (and dirp (cdr (assq 'directory apps)))
  10052. ;; First, try matching against apps-dlink if we
  10053. ;; get a match here, store the match data for
  10054. ;; later.
  10055. (let ((match (assoc-default dlink apps-dlink
  10056. 'string-match)))
  10057. (if match
  10058. (progn (setq link-match-data (match-data))
  10059. match)
  10060. (progn (setq in-emacs (or in-emacs line search))
  10061. nil))) ; if we have no match in apps-dlink,
  10062. ; always open the file in emacs if line or search
  10063. ; is given (for backwards compatibility)
  10064. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10065. 'string-match)
  10066. (cdr (assoc ext apps))
  10067. (cdr (assq t apps))))))
  10068. (when (eq cmd 'system)
  10069. (setq cmd (cdr (assq 'system apps))))
  10070. (when (eq cmd 'default)
  10071. (setq cmd (cdr (assoc t apps))))
  10072. (when (eq cmd 'mailcap)
  10073. (require 'mailcap)
  10074. (mailcap-parse-mailcaps)
  10075. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10076. (command (mailcap-mime-info mime-type)))
  10077. (if (stringp command)
  10078. (setq cmd command)
  10079. (setq cmd 'emacs))))
  10080. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10081. (not (file-exists-p file))
  10082. (not org-open-non-existing-files))
  10083. (user-error "No such file: %s" file))
  10084. (cond
  10085. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10086. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10087. (while (string-match "['\"]%s['\"]" cmd)
  10088. (setq cmd (replace-match "%s" t t cmd)))
  10089. (setq cmd (replace-regexp-in-string
  10090. "%s"
  10091. (shell-quote-argument (convert-standard-filename file))
  10092. cmd
  10093. nil t))
  10094. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10095. (save-match-data
  10096. (let ((match-index 1)
  10097. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10098. (set-match-data link-match-data)
  10099. (while (<= match-index number-of-groups)
  10100. (let ((regex (concat "%" (number-to-string match-index)))
  10101. (replace-with (match-string match-index dlink)))
  10102. (while (string-match regex cmd)
  10103. (setq cmd (replace-match replace-with t t cmd))))
  10104. (setq match-index (+ match-index 1)))))
  10105. (save-window-excursion
  10106. (message "Running %s...done" cmd)
  10107. (start-process-shell-command cmd nil cmd)
  10108. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10109. ((or (stringp cmd)
  10110. (eq cmd 'emacs))
  10111. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10112. (widen)
  10113. (cond (line (org-goto-line line)
  10114. (when (derived-mode-p 'org-mode) (org-reveal)))
  10115. (search (condition-case err
  10116. (org-link-search search)
  10117. ;; Save position before error-ing out so user
  10118. ;; can easily move back to the original buffer.
  10119. (error (funcall save-position-maybe)
  10120. (error (nth 1 err)))))))
  10121. ((functionp cmd)
  10122. (save-match-data
  10123. (set-match-data link-match-data)
  10124. (condition-case nil
  10125. (funcall cmd file link)
  10126. ;; FIXME: Remove this check when most default installations
  10127. ;; of Emacs have at least Org 9.0.
  10128. ((debug wrong-number-of-arguments wrong-type-argument
  10129. invalid-function)
  10130. (user-error "Please see Org News for version 9.0 about \
  10131. `org-file-apps'--Lisp error: %S" cmd)))))
  10132. ((consp cmd)
  10133. ;; FIXME: Remove this check when most default installations of
  10134. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10135. ;; fall back to `org-link-frame-setup' for an old usage of
  10136. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10137. (user-error "Please see Org News for version 9.0 about \
  10138. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10139. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10140. (funcall save-position-maybe)))
  10141. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10142. "This function returns non-nil if `entry' uses a regular
  10143. expression which should be matched against the whole link by
  10144. org-open-file.
  10145. It assumes that is the case when the entry uses a regular
  10146. expression which has at least one grouping construct and the
  10147. action is either a lisp form or a command string containing
  10148. `%1', i.e. using at least one subexpression match as a
  10149. parameter."
  10150. (let ((selector (car entry))
  10151. (action (cdr entry)))
  10152. (if (stringp selector)
  10153. (and (> (regexp-opt-depth selector) 0)
  10154. (or (and (stringp action)
  10155. (string-match "%[0-9]" action))
  10156. (consp action)))
  10157. nil)))
  10158. (defun org-default-apps ()
  10159. "Return the default applications for this operating system."
  10160. (cond
  10161. ((eq system-type 'darwin)
  10162. org-file-apps-defaults-macosx)
  10163. ((eq system-type 'windows-nt)
  10164. org-file-apps-defaults-windowsnt)
  10165. (t org-file-apps-defaults-gnu)))
  10166. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10167. "Convert extensions to regular expressions in the cars of LIST.
  10168. Also, weed out any non-string entries, because the return value is used
  10169. only for regexp matching.
  10170. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10171. point to the symbol `emacs', indicating that the file should
  10172. be opened in Emacs."
  10173. (append
  10174. (delq nil
  10175. (mapcar (lambda (x)
  10176. (unless (not (stringp (car x)))
  10177. (if (string-match "\\W" (car x))
  10178. x
  10179. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10180. list))
  10181. (when add-auto-mode
  10182. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10183. (defvar ange-ftp-name-format)
  10184. (defun org-file-remote-p (file)
  10185. "Test whether FILE specifies a location on a remote system.
  10186. Return non-nil if the location is indeed remote.
  10187. For example, the filename \"/user@host:/foo\" specifies a location
  10188. on the system \"/user@host:\"."
  10189. (cond ((fboundp 'file-remote-p)
  10190. (file-remote-p file))
  10191. ((fboundp 'tramp-handle-file-remote-p)
  10192. (tramp-handle-file-remote-p file))
  10193. ((and (boundp 'ange-ftp-name-format)
  10194. (string-match (car ange-ftp-name-format) file))
  10195. t)))
  10196. ;;;; Refiling
  10197. (defun org-get-org-file ()
  10198. "Read a filename, with default directory `org-directory'."
  10199. (let ((default (or org-default-notes-file remember-data-file)))
  10200. (read-file-name (format "File name [%s]: " default)
  10201. (file-name-as-directory org-directory)
  10202. default)))
  10203. (defun org-notes-order-reversed-p ()
  10204. "Check if the current file should receive notes in reversed order."
  10205. (cond
  10206. ((not org-reverse-note-order) nil)
  10207. ((eq t org-reverse-note-order) t)
  10208. ((not (listp org-reverse-note-order)) nil)
  10209. (t (catch 'exit
  10210. (dolist (entry org-reverse-note-order)
  10211. (when (string-match (car entry) buffer-file-name)
  10212. (throw 'exit (cdr entry))))))))
  10213. (defvar org-refile-target-table nil
  10214. "The list of refile targets, created by `org-refile'.")
  10215. (defvar org-agenda-new-buffers nil
  10216. "Buffers created to visit agenda files.")
  10217. (defvar org-refile-cache nil
  10218. "Cache for refile targets.")
  10219. (defvar org-refile-markers nil
  10220. "All the markers used for caching refile locations.")
  10221. (defun org-refile-marker (pos)
  10222. "Get a new refile marker, but only if caching is in use."
  10223. (if (not org-refile-use-cache)
  10224. pos
  10225. (let ((m (make-marker)))
  10226. (move-marker m pos)
  10227. (push m org-refile-markers)
  10228. m)))
  10229. (defun org-refile-cache-clear ()
  10230. "Clear the refile cache and disable all the markers."
  10231. (dolist (m org-refile-markers) (move-marker m nil))
  10232. (setq org-refile-markers nil)
  10233. (setq org-refile-cache nil)
  10234. (message "Refile cache has been cleared"))
  10235. (defun org-refile-cache-check-set (set)
  10236. "Check if all the markers in the cache still have live buffers."
  10237. (let (marker)
  10238. (catch 'exit
  10239. (while (and set (setq marker (nth 3 (pop set))))
  10240. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10241. (when (and marker (null (marker-buffer marker)))
  10242. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10243. (sit-for 3)
  10244. (throw 'exit nil)))
  10245. t)))
  10246. (defun org-refile-cache-put (set &rest identifiers)
  10247. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10248. (let* ((key (sha1 (prin1-to-string identifiers)))
  10249. (entry (assoc key org-refile-cache)))
  10250. (if entry
  10251. (setcdr entry set)
  10252. (push (cons key set) org-refile-cache))))
  10253. (defun org-refile-cache-get (&rest identifiers)
  10254. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10255. (cond
  10256. ((not org-refile-cache) nil)
  10257. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10258. (t
  10259. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10260. org-refile-cache))))
  10261. (and set (org-refile-cache-check-set set) set)))))
  10262. (defvar org-outline-path-cache nil
  10263. "Alist between buffer positions and outline paths.
  10264. It value is an alist (POSITION . PATH) where POSITION is the
  10265. buffer position at the beginning of an entry and PATH is a list
  10266. of strings describing the outline path for that entry, in reverse
  10267. order.")
  10268. (defun org-refile-get-targets (&optional default-buffer)
  10269. "Produce a table with refile targets."
  10270. (let ((case-fold-search nil)
  10271. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10272. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10273. targets tgs files desc descre)
  10274. (message "Getting targets...")
  10275. (with-current-buffer (or default-buffer (current-buffer))
  10276. (dolist (entry entries)
  10277. (setq files (car entry) desc (cdr entry))
  10278. (cond
  10279. ((null files) (setq files (list (current-buffer))))
  10280. ((eq files 'org-agenda-files)
  10281. (setq files (org-agenda-files 'unrestricted)))
  10282. ((and (symbolp files) (fboundp files))
  10283. (setq files (funcall files)))
  10284. ((and (symbolp files) (boundp files))
  10285. (setq files (symbol-value files))))
  10286. (when (stringp files) (setq files (list files)))
  10287. (cond
  10288. ((eq (car desc) :tag)
  10289. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10290. ((eq (car desc) :todo)
  10291. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10292. ((eq (car desc) :regexp)
  10293. (setq descre (cdr desc)))
  10294. ((eq (car desc) :level)
  10295. (setq descre (concat "^\\*\\{" (number-to-string
  10296. (if org-odd-levels-only
  10297. (1- (* 2 (cdr desc)))
  10298. (cdr desc)))
  10299. "\\}[ \t]")))
  10300. ((eq (car desc) :maxlevel)
  10301. (setq descre (concat "^\\*\\{1," (number-to-string
  10302. (if org-odd-levels-only
  10303. (1- (* 2 (cdr desc)))
  10304. (cdr desc)))
  10305. "\\}[ \t]")))
  10306. (t (error "Bad refiling target description %s" desc)))
  10307. (dolist (f files)
  10308. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10309. (or
  10310. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10311. (progn
  10312. (when (bufferp f)
  10313. (setq f (buffer-file-name (buffer-base-buffer f))))
  10314. (setq f (and f (expand-file-name f)))
  10315. (when (eq org-refile-use-outline-path 'file)
  10316. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10317. (when (eq org-refile-use-outline-path 'buffer-name)
  10318. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10319. (when (eq org-refile-use-outline-path 'full-file-path)
  10320. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10321. (org-with-wide-buffer
  10322. (goto-char (point-min))
  10323. (setq org-outline-path-cache nil)
  10324. (while (re-search-forward descre nil t)
  10325. (beginning-of-line)
  10326. (let ((case-fold-search nil))
  10327. (looking-at org-complex-heading-regexp))
  10328. (let ((begin (point))
  10329. (heading (match-string-no-properties 4)))
  10330. (unless (or (and
  10331. org-refile-target-verify-function
  10332. (not
  10333. (funcall org-refile-target-verify-function)))
  10334. (not heading))
  10335. (let ((re (format org-complex-heading-regexp-format
  10336. (regexp-quote heading)))
  10337. (target
  10338. (if (not org-refile-use-outline-path) heading
  10339. (mapconcat
  10340. #'identity
  10341. (append
  10342. (pcase org-refile-use-outline-path
  10343. (`file (list (file-name-nondirectory
  10344. (buffer-file-name
  10345. (buffer-base-buffer)))))
  10346. (`full-file-path
  10347. (list (buffer-file-name
  10348. (buffer-base-buffer))))
  10349. (`buffer-name
  10350. (list (buffer-name
  10351. (buffer-base-buffer))))
  10352. (_ nil))
  10353. (mapcar (lambda (s) (replace-regexp-in-string
  10354. "/" "\\/" s nil t))
  10355. (org-get-outline-path t t)))
  10356. "/"))))
  10357. (push (list target f re (org-refile-marker (point)))
  10358. tgs)))
  10359. (when (= (point) begin)
  10360. ;; Verification function has not moved point.
  10361. (end-of-line)))))))
  10362. (when org-refile-use-cache
  10363. (org-refile-cache-put tgs (buffer-file-name) descre))
  10364. (setq targets (append tgs targets))))))
  10365. (message "Getting targets...done")
  10366. (delete-dups (nreverse targets))))
  10367. (defun org--get-outline-path-1 (&optional use-cache)
  10368. "Return outline path to current headline.
  10369. Outline path is a list of strings, in reverse order. When
  10370. optional argument USE-CACHE is non-nil, make use of a cache. See
  10371. `org-get-outline-path' for details.
  10372. Assume buffer is widened and point is on a headline."
  10373. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10374. (let ((p (point))
  10375. (heading (let ((case-fold-search nil))
  10376. (looking-at org-complex-heading-regexp)
  10377. (if (not (match-end 4)) ""
  10378. ;; Remove statistics cookies.
  10379. (org-trim
  10380. (org-link-display-format
  10381. (replace-regexp-in-string
  10382. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10383. (match-string-no-properties 4))))))))
  10384. (if (org-up-heading-safe)
  10385. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10386. (when use-cache
  10387. (push (cons p path) org-outline-path-cache))
  10388. path)
  10389. ;; This is a new root node. Since we assume we are moving
  10390. ;; forward, we can drop previous cache so as to limit number
  10391. ;; of associations there.
  10392. (let ((path (list heading)))
  10393. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10394. path)))))
  10395. (defun org-get-outline-path (&optional with-self use-cache)
  10396. "Return the outline path to the current entry.
  10397. An outline path is a list of ancestors for current headline, as
  10398. a list of strings. Statistics cookies are removed and links are
  10399. replaced with their description, if any, or their path otherwise.
  10400. When optional argument WITH-SELF is non-nil, the path also
  10401. includes the current headline.
  10402. When optional argument USE-CACHE is non-nil, cache outline paths
  10403. between calls to this function so as to avoid backtracking. This
  10404. argument is useful when planning to find more than one outline
  10405. path in the same document. In that case, there are two
  10406. conditions to satisfy:
  10407. - `org-outline-path-cache' is set to nil before starting the
  10408. process;
  10409. - outline paths are computed by increasing buffer positions."
  10410. (org-with-wide-buffer
  10411. (and (or (and with-self (org-back-to-heading t))
  10412. (org-up-heading-safe))
  10413. (reverse (org--get-outline-path-1 use-cache)))))
  10414. (defun org-format-outline-path (path &optional width prefix separator)
  10415. "Format the outline path PATH for display.
  10416. WIDTH is the maximum number of characters that is available.
  10417. PREFIX is a prefix to be included in the returned string,
  10418. such as the file name.
  10419. SEPARATOR is inserted between the different parts of the path,
  10420. the default is \"/\"."
  10421. (setq width (or width 79))
  10422. (setq path (delq nil path))
  10423. (unless (> width 0)
  10424. (user-error "Argument `width' must be positive"))
  10425. (setq separator (or separator "/"))
  10426. (let* ((org-odd-levels-only nil)
  10427. (fpath (concat
  10428. prefix (and prefix path separator)
  10429. (mapconcat
  10430. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10431. (cl-loop for head in path
  10432. for n from 0
  10433. collect (org-add-props
  10434. head nil 'face
  10435. (nth (% n org-n-level-faces) org-level-faces)))
  10436. separator))))
  10437. (when (> (length fpath) width)
  10438. (if (< width 7)
  10439. ;; It's unlikely that `width' will be this small, but don't
  10440. ;; waste characters by adding ".." if it is.
  10441. (setq fpath (substring fpath 0 width))
  10442. (setf (substring fpath (- width 2)) "..")))
  10443. fpath))
  10444. (defun org-display-outline-path (&optional file current separator just-return-string)
  10445. "Display the current outline path in the echo area.
  10446. If FILE is non-nil, prepend the output with the file name.
  10447. If CURRENT is non-nil, append the current heading to the output.
  10448. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10449. the different parts of the path and defaults to \"/\".
  10450. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10451. (interactive "P")
  10452. (let* (case-fold-search
  10453. (bfn (buffer-file-name (buffer-base-buffer)))
  10454. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10455. res)
  10456. (when current (setq path (append path
  10457. (save-excursion
  10458. (org-back-to-heading t)
  10459. (when (looking-at org-complex-heading-regexp)
  10460. (list (match-string 4)))))))
  10461. (setq res
  10462. (org-format-outline-path
  10463. path
  10464. (1- (frame-width))
  10465. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10466. separator))
  10467. (if just-return-string
  10468. (org-no-properties res)
  10469. (org-unlogged-message "%s" res))))
  10470. (defvar org-refile-history nil
  10471. "History for refiling operations.")
  10472. (defvar org-after-refile-insert-hook nil
  10473. "Hook run after `org-refile' has inserted its stuff at the new location.
  10474. Note that this is still *before* the stuff will be removed from
  10475. the *old* location.")
  10476. (defvar org-capture-last-stored-marker)
  10477. (defvar org-refile-keep nil
  10478. "Non-nil means `org-refile' will copy instead of refile.")
  10479. (defun org-copy ()
  10480. "Like `org-refile', but copy."
  10481. (interactive)
  10482. (let ((org-refile-keep t))
  10483. (funcall 'org-refile nil nil nil "Copy")))
  10484. (defun org-refile (&optional arg default-buffer rfloc msg)
  10485. "Move the entry or entries at point to another heading.
  10486. The list of target headings is compiled using the information in
  10487. `org-refile-targets', which see.
  10488. At the target location, the entry is filed as a subitem of the
  10489. target heading. Depending on `org-reverse-note-order', the new
  10490. subitem will either be the first or the last subitem.
  10491. If there is an active region, all entries in that region will be
  10492. refiled. However, the region must fulfill the requirement that
  10493. the first heading sets the top-level of the moved text.
  10494. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10495. location
  10496. and not actually move anything.
  10497. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10498. location where the last
  10499. refiling operation has put the subtree.
  10500. With a numeric prefix argument of `2', refile to the running clock.
  10501. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10502. being set to t and copy to the target location, don't move it.
  10503. Beware that keeping refiled entries may result in duplicated ID
  10504. properties.
  10505. RFLOC can be a refile location obtained in a different way.
  10506. MSG is a string to replace \"Refile\" in the default prompt with
  10507. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10508. See also `org-refile-use-outline-path'.
  10509. If you are using target caching (see `org-refile-use-cache'), you
  10510. have to clear the target cache in order to find new targets.
  10511. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10512. prefix argument (`C-u C-u C-u C-c C-w')."
  10513. (interactive "P")
  10514. (if (member arg '(0 (64)))
  10515. (org-refile-cache-clear)
  10516. (let* ((actionmsg (cond (msg msg)
  10517. ((equal arg 3) "Refile (and keep)")
  10518. (t "Refile")))
  10519. (regionp (org-region-active-p))
  10520. (region-start (and regionp (region-beginning)))
  10521. (region-end (and regionp (region-end)))
  10522. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10523. pos it nbuf file level reversed)
  10524. (setq last-command nil)
  10525. (when regionp
  10526. (goto-char region-start)
  10527. (or (bolp) (goto-char (point-at-bol)))
  10528. (setq region-start (point))
  10529. (unless (or (org-kill-is-subtree-p
  10530. (buffer-substring region-start region-end))
  10531. (prog1 org-refile-active-region-within-subtree
  10532. (let ((s (point-at-eol)))
  10533. (org-toggle-heading)
  10534. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10535. (user-error "The region is not a (sequence of) subtree(s)")))
  10536. (if (equal arg '(16))
  10537. (org-refile-goto-last-stored)
  10538. (when (or
  10539. (and (equal arg 2)
  10540. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10541. (prog1
  10542. (setq it (list (or org-clock-heading "running clock")
  10543. (buffer-file-name
  10544. (marker-buffer org-clock-hd-marker))
  10545. ""
  10546. (marker-position org-clock-hd-marker)))
  10547. (setq arg nil)))
  10548. (setq it
  10549. (or rfloc
  10550. (let (heading-text)
  10551. (save-excursion
  10552. (unless (and arg (listp arg))
  10553. (org-back-to-heading t)
  10554. (setq heading-text
  10555. (replace-regexp-in-string
  10556. org-bracket-link-regexp
  10557. "\\3"
  10558. (or (nth 4 (org-heading-components))
  10559. ""))))
  10560. (org-refile-get-location
  10561. (cond ((and arg (listp arg)) "Goto")
  10562. (regionp (concat actionmsg " region to"))
  10563. (t (concat actionmsg " subtree \""
  10564. heading-text "\" to")))
  10565. default-buffer
  10566. (and (not (equal '(4) arg))
  10567. org-refile-allow-creating-parent-nodes)))))))
  10568. (setq file (nth 1 it)
  10569. pos (nth 3 it))
  10570. (when (and (not arg)
  10571. pos
  10572. (equal (buffer-file-name) file)
  10573. (if regionp
  10574. (and (>= pos region-start)
  10575. (<= pos region-end))
  10576. (and (>= pos (point))
  10577. (< pos (save-excursion
  10578. (org-end-of-subtree t t))))))
  10579. (error "Cannot refile to position inside the tree or region"))
  10580. (setq nbuf (or (find-buffer-visiting file)
  10581. (find-file-noselect file)))
  10582. (if (and arg (not (equal arg 3)))
  10583. (progn
  10584. (pop-to-buffer-same-window nbuf)
  10585. (goto-char pos)
  10586. (org-show-context 'org-goto))
  10587. (if regionp
  10588. (progn
  10589. (org-kill-new (buffer-substring region-start region-end))
  10590. (org-save-markers-in-region region-start region-end))
  10591. (org-copy-subtree 1 nil t))
  10592. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10593. (find-file-noselect file)))
  10594. (setq reversed (org-notes-order-reversed-p))
  10595. (org-with-wide-buffer
  10596. (if pos
  10597. (progn
  10598. (goto-char pos)
  10599. (setq level (org-get-valid-level (funcall outline-level) 1))
  10600. (goto-char
  10601. (if reversed
  10602. (or (outline-next-heading) (point-max))
  10603. (or (save-excursion (org-get-next-sibling))
  10604. (org-end-of-subtree t t)
  10605. (point-max)))))
  10606. (setq level 1)
  10607. (if (not reversed)
  10608. (goto-char (point-max))
  10609. (goto-char (point-min))
  10610. (or (outline-next-heading) (goto-char (point-max)))))
  10611. (unless (bolp) (newline))
  10612. (org-paste-subtree level nil nil t)
  10613. (when org-log-refile
  10614. (org-add-log-setup 'refile nil nil org-log-refile)
  10615. (unless (eq org-log-refile 'note)
  10616. (save-excursion (org-add-log-note))))
  10617. (and org-auto-align-tags
  10618. (let ((org-loop-over-headlines-in-active-region nil))
  10619. (org-set-tags nil t)))
  10620. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10621. :last-refile)))
  10622. (when bookmark-name
  10623. (with-demoted-errors
  10624. (bookmark-set bookmark-name))))
  10625. ;; If we are refiling for capture, make sure that the
  10626. ;; last-capture pointers point here
  10627. (when (bound-and-true-p org-capture-is-refiling)
  10628. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10629. :last-capture-marker)))
  10630. (when bookmark-name
  10631. (with-demoted-errors
  10632. (bookmark-set bookmark-name))))
  10633. (move-marker org-capture-last-stored-marker (point)))
  10634. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10635. (run-hooks 'org-after-refile-insert-hook)))
  10636. (unless org-refile-keep
  10637. (if regionp
  10638. (delete-region (point) (+ (point) (- region-end region-start)))
  10639. (delete-region
  10640. (and (org-back-to-heading t) (point))
  10641. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10642. (when (featurep 'org-inlinetask)
  10643. (org-inlinetask-remove-END-maybe))
  10644. (setq org-markers-to-move nil)
  10645. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10646. (defun org-refile-goto-last-stored ()
  10647. "Go to the location where the last refile was stored."
  10648. (interactive)
  10649. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10650. (message "This is the location of the last refile"))
  10651. (defun org-refile--get-location (refloc tbl)
  10652. "When user refile to REFLOC, find the associated target in TBL.
  10653. Also check `org-refile-target-table'."
  10654. (car (delq
  10655. nil
  10656. (mapcar
  10657. (lambda (r) (or (assoc r tbl)
  10658. (assoc r org-refile-target-table)))
  10659. (list (replace-regexp-in-string "/$" "" refloc)
  10660. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10661. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10662. "Prompt the user for a refile location, using PROMPT.
  10663. PROMPT should not be suffixed with a colon and a space, because
  10664. this function appends the default value from
  10665. `org-refile-history' automatically, if that is not empty."
  10666. (let ((org-refile-targets org-refile-targets)
  10667. (org-refile-use-outline-path org-refile-use-outline-path))
  10668. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10669. (unless org-refile-target-table
  10670. (user-error "No refile targets"))
  10671. (let* ((cbuf (current-buffer))
  10672. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10673. (cfunc (if (and org-refile-use-outline-path
  10674. org-outline-path-complete-in-steps)
  10675. #'org-olpath-completing-read
  10676. #'completing-read))
  10677. (extra (if org-refile-use-outline-path "/" ""))
  10678. (cbnex (concat (buffer-name) extra))
  10679. (filename (and cfn (expand-file-name cfn)))
  10680. (tbl (mapcar
  10681. (lambda (x)
  10682. (if (and (not (member org-refile-use-outline-path
  10683. '(file full-file-path)))
  10684. (not (equal filename (nth 1 x))))
  10685. (cons (concat (car x) extra " ("
  10686. (file-name-nondirectory (nth 1 x)) ")")
  10687. (cdr x))
  10688. (cons (concat (car x) extra) (cdr x))))
  10689. org-refile-target-table))
  10690. (completion-ignore-case t)
  10691. cdef
  10692. (prompt (concat prompt
  10693. (or (and (car org-refile-history)
  10694. (concat " (default " (car org-refile-history) ")"))
  10695. (and (assoc cbnex tbl) (setq cdef cbnex)
  10696. (concat " (default " cbnex ")"))) ": "))
  10697. pa answ parent-target child parent old-hist)
  10698. (setq old-hist org-refile-history)
  10699. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10700. nil 'org-refile-history (or cdef (car org-refile-history))))
  10701. (if (setq pa (org-refile--get-location answ tbl))
  10702. (progn
  10703. (org-refile-check-position pa)
  10704. (when (or (not org-refile-history)
  10705. (not (eq old-hist org-refile-history))
  10706. (not (equal (car pa) (car org-refile-history))))
  10707. (setq org-refile-history
  10708. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10709. org-refile-history
  10710. (cdr org-refile-history))))
  10711. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10712. (pop org-refile-history)))
  10713. pa)
  10714. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10715. (progn
  10716. (setq parent (match-string 1 answ)
  10717. child (match-string 2 answ))
  10718. (setq parent-target (org-refile--get-location parent tbl))
  10719. (when (and parent-target
  10720. (or (eq new-nodes t)
  10721. (and (eq new-nodes 'confirm)
  10722. (y-or-n-p (format "Create new node \"%s\"? "
  10723. child)))))
  10724. (org-refile-new-child parent-target child)))
  10725. (user-error "Invalid target location")))))
  10726. (declare-function org-string-nw-p "org-macs" (s))
  10727. (defun org-refile-check-position (refile-pointer)
  10728. "Check if the refile pointer matches the headline to which it points."
  10729. (let* ((file (nth 1 refile-pointer))
  10730. (re (nth 2 refile-pointer))
  10731. (pos (nth 3 refile-pointer))
  10732. buffer)
  10733. (if (and (not (markerp pos)) (not file))
  10734. (user-error "Please indicate a target file in the refile path")
  10735. (when (org-string-nw-p re)
  10736. (setq buffer (if (markerp pos)
  10737. (marker-buffer pos)
  10738. (or (find-buffer-visiting file)
  10739. (find-file-noselect file))))
  10740. (with-current-buffer buffer
  10741. (org-with-wide-buffer
  10742. (goto-char pos)
  10743. (beginning-of-line 1)
  10744. (unless (looking-at-p re)
  10745. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10746. (defun org-refile-new-child (parent-target child)
  10747. "Use refile target PARENT-TARGET to add new CHILD below it."
  10748. (unless parent-target
  10749. (error "Cannot find parent for new node"))
  10750. (let ((file (nth 1 parent-target))
  10751. (pos (nth 3 parent-target))
  10752. level)
  10753. (with-current-buffer (or (find-buffer-visiting file)
  10754. (find-file-noselect file))
  10755. (org-with-wide-buffer
  10756. (if pos
  10757. (goto-char pos)
  10758. (goto-char (point-max))
  10759. (unless (bolp) (newline)))
  10760. (when (looking-at org-outline-regexp)
  10761. (setq level (funcall outline-level))
  10762. (org-end-of-subtree t t))
  10763. (org-back-over-empty-lines)
  10764. (insert "\n" (make-string
  10765. (if pos (org-get-valid-level level 1) 1) ?*)
  10766. " " child "\n")
  10767. (beginning-of-line 0)
  10768. (list (concat (car parent-target) "/" child) file "" (point))))))
  10769. (defun org-olpath-completing-read (prompt collection &rest args)
  10770. "Read an outline path like a file name."
  10771. (let ((thetable collection))
  10772. (apply #'completing-read
  10773. prompt
  10774. (lambda (string predicate &optional flag)
  10775. (cond
  10776. ((eq flag nil) (try-completion string thetable))
  10777. ((eq flag t)
  10778. (let ((l (length string)))
  10779. (mapcar (lambda (x)
  10780. (let ((r (substring x l))
  10781. (f (if (string-match " ([^)]*)$" x)
  10782. (match-string 0 x)
  10783. "")))
  10784. (if (string-match "/" r)
  10785. (concat string (substring r 0 (match-end 0)) f)
  10786. x)))
  10787. (all-completions string thetable predicate))))
  10788. ;; Exact match?
  10789. ((eq flag 'lambda) (assoc string thetable))))
  10790. args)))
  10791. ;;;; Dynamic blocks
  10792. (defun org-find-dblock (name)
  10793. "Find the first dynamic block with name NAME in the buffer.
  10794. If not found, stay at current position and return nil."
  10795. (let ((case-fold-search t) pos)
  10796. (save-excursion
  10797. (goto-char (point-min))
  10798. (setq pos (and (re-search-forward
  10799. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10800. (match-beginning 0))))
  10801. (when pos (goto-char pos))
  10802. pos))
  10803. (defun org-create-dblock (plist)
  10804. "Create a dynamic block section, with parameters taken from PLIST.
  10805. PLIST must contain a :name entry which is used as the name of the block."
  10806. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10807. (end-of-line 1)
  10808. (newline))
  10809. (let ((col (current-column))
  10810. (name (plist-get plist :name)))
  10811. (insert "#+BEGIN: " name)
  10812. (while plist
  10813. (if (eq (car plist) :name)
  10814. (setq plist (cddr plist))
  10815. (insert " " (prin1-to-string (pop plist)))))
  10816. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10817. (beginning-of-line -2)))
  10818. (defun org-prepare-dblock ()
  10819. "Prepare dynamic block for refresh.
  10820. This empties the block, puts the cursor at the insert position and returns
  10821. the property list including an extra property :name with the block name."
  10822. (unless (looking-at org-dblock-start-re)
  10823. (user-error "Not at a dynamic block"))
  10824. (let* ((begdel (1+ (match-end 0)))
  10825. (name (org-no-properties (match-string 1)))
  10826. (params (append (list :name name)
  10827. (read (concat "(" (match-string 3) ")")))))
  10828. (save-excursion
  10829. (beginning-of-line 1)
  10830. (skip-chars-forward " \t")
  10831. (setq params (plist-put params :indentation-column (current-column))))
  10832. (unless (re-search-forward org-dblock-end-re nil t)
  10833. (error "Dynamic block not terminated"))
  10834. (setq params
  10835. (append params
  10836. (list :content (buffer-substring
  10837. begdel (match-beginning 0)))))
  10838. (delete-region begdel (match-beginning 0))
  10839. (goto-char begdel)
  10840. (open-line 1)
  10841. params))
  10842. (defun org-map-dblocks (&optional command)
  10843. "Apply COMMAND to all dynamic blocks in the current buffer.
  10844. If COMMAND is not given, use `org-update-dblock'."
  10845. (let ((cmd (or command 'org-update-dblock)))
  10846. (save-excursion
  10847. (goto-char (point-min))
  10848. (while (re-search-forward org-dblock-start-re nil t)
  10849. (goto-char (match-beginning 0))
  10850. (save-excursion
  10851. (condition-case nil
  10852. (funcall cmd)
  10853. (error (message "Error during update of dynamic block"))))
  10854. (unless (re-search-forward org-dblock-end-re nil t)
  10855. (error "Dynamic block not terminated"))))))
  10856. (defun org-dblock-update (&optional arg)
  10857. "User command for updating dynamic blocks.
  10858. Update the dynamic block at point. With prefix ARG, update all dynamic
  10859. blocks in the buffer."
  10860. (interactive "P")
  10861. (if arg
  10862. (org-update-all-dblocks)
  10863. (or (looking-at org-dblock-start-re)
  10864. (org-beginning-of-dblock))
  10865. (org-update-dblock)))
  10866. (defun org-update-dblock ()
  10867. "Update the dynamic block at point.
  10868. This means to empty the block, parse for parameters and then call
  10869. the correct writing function."
  10870. (interactive)
  10871. (save-excursion
  10872. (let* ((win (selected-window))
  10873. (pos (point))
  10874. (line (org-current-line))
  10875. (params (org-prepare-dblock))
  10876. (name (plist-get params :name))
  10877. (indent (plist-get params :indentation-column))
  10878. (cmd (intern (concat "org-dblock-write:" name))))
  10879. (message "Updating dynamic block `%s' at line %d..." name line)
  10880. (funcall cmd params)
  10881. (message "Updating dynamic block `%s' at line %d...done" name line)
  10882. (goto-char pos)
  10883. (when (and indent (> indent 0))
  10884. (setq indent (make-string indent ?\ ))
  10885. (save-excursion
  10886. (select-window win)
  10887. (org-beginning-of-dblock)
  10888. (forward-line 1)
  10889. (while (not (looking-at org-dblock-end-re))
  10890. (insert indent)
  10891. (beginning-of-line 2))
  10892. (when (looking-at org-dblock-end-re)
  10893. (and (looking-at "[ \t]+")
  10894. (replace-match ""))
  10895. (insert indent)))))))
  10896. (defun org-beginning-of-dblock ()
  10897. "Find the beginning of the dynamic block at point.
  10898. Error if there is no such block at point."
  10899. (let ((pos (point))
  10900. beg)
  10901. (end-of-line 1)
  10902. (if (and (re-search-backward org-dblock-start-re nil t)
  10903. (setq beg (match-beginning 0))
  10904. (re-search-forward org-dblock-end-re nil t)
  10905. (> (match-end 0) pos))
  10906. (goto-char beg)
  10907. (goto-char pos)
  10908. (error "Not in a dynamic block"))))
  10909. (defun org-update-all-dblocks ()
  10910. "Update all dynamic blocks in the buffer.
  10911. This function can be used in a hook."
  10912. (interactive)
  10913. (when (derived-mode-p 'org-mode)
  10914. (org-map-dblocks 'org-update-dblock)))
  10915. ;;;; Completion
  10916. (declare-function org-export-backend-options "ox" (cl-x) t)
  10917. (defun org-get-export-keywords ()
  10918. "Return a list of all currently understood export keywords.
  10919. Export keywords include options, block names, attributes and
  10920. keywords relative to each registered export back-end."
  10921. (let (keywords)
  10922. (dolist (backend
  10923. (bound-and-true-p org-export-registered-backends)
  10924. (delq nil keywords))
  10925. ;; Back-end name (for keywords, like #+LATEX:)
  10926. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10927. (dolist (option-entry (org-export-backend-options backend))
  10928. ;; Back-end options.
  10929. (push (nth 1 option-entry) keywords)))))
  10930. (defconst org-options-keywords
  10931. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10932. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10933. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10934. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10935. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10936. (defcustom org-structure-template-alist
  10937. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10938. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10939. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10940. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10941. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10942. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10943. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10944. ("L" "#+LaTeX: ")
  10945. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10946. ("H" "#+HTML: ")
  10947. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10948. ("A" "#+ASCII: ")
  10949. ("i" "#+INDEX: ?")
  10950. ("I" "#+INCLUDE: %file ?"))
  10951. "Structure completion elements.
  10952. This is a list of abbreviation keys and values. The value gets inserted
  10953. if you type `<' followed by the key and then press the completion key,
  10954. usually `TAB'. %file will be replaced by a file name after prompting
  10955. for the file using completion. The cursor will be placed at the position
  10956. of the `?' in the template.
  10957. There are two templates for each key, the first uses the original Org syntax,
  10958. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10959. the default when the /org-mtags.el/ module has been loaded. See also the
  10960. variable `org-mtags-prefer-muse-templates'."
  10961. :group 'org-completion
  10962. :type '(repeat
  10963. (list
  10964. (string :tag "Key")
  10965. (string :tag "Template")))
  10966. :version "26.1"
  10967. :package-version '(Org . "8.3"))
  10968. (defun org-try-structure-completion ()
  10969. "Try to complete a structure template before point.
  10970. This looks for strings like \"<e\" on an otherwise empty line and
  10971. expands them."
  10972. (let ((l (buffer-substring (point-at-bol) (point)))
  10973. a)
  10974. (when (and (looking-at "[ \t]*$")
  10975. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  10976. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  10977. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  10978. (match-beginning 1)) a)
  10979. t)))
  10980. (defun org-complete-expand-structure-template (start cell)
  10981. "Expand a structure template."
  10982. (let ((rpl (nth 1 cell))
  10983. (ind ""))
  10984. (delete-region start (point))
  10985. (when (string-match "\\`[ \t]*#\\+" rpl)
  10986. (cond
  10987. ((bolp))
  10988. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  10989. (setq ind (buffer-substring (point-at-bol) (point))))
  10990. (t (newline))))
  10991. (setq start (point))
  10992. (when (string-match "%file" rpl)
  10993. (setq rpl (replace-match
  10994. (concat
  10995. "\""
  10996. (save-match-data
  10997. (abbreviate-file-name (read-file-name "Include file: ")))
  10998. "\"")
  10999. t t rpl)))
  11000. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11001. (concat "\n" ind)))
  11002. (insert rpl)
  11003. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11004. ;;;; TODO, DEADLINE, Comments
  11005. (defun org-toggle-comment ()
  11006. "Change the COMMENT state of an entry."
  11007. (interactive)
  11008. (save-excursion
  11009. (org-back-to-heading)
  11010. (let ((case-fold-search nil))
  11011. (looking-at org-complex-heading-regexp))
  11012. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11013. (skip-chars-forward " \t")
  11014. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11015. (if (org-in-commented-heading-p t)
  11016. (delete-region (point)
  11017. (progn (search-forward " " (line-end-position) 'move)
  11018. (skip-chars-forward " \t")
  11019. (point)))
  11020. (insert org-comment-string)
  11021. (unless (eolp) (insert " ")))))
  11022. (defvar org-last-todo-state-is-todo nil
  11023. "This is non-nil when the last TODO state change led to a TODO state.
  11024. If the last change removed the TODO tag or switched to DONE, then
  11025. this is nil.")
  11026. (defvar org-setting-tags nil) ; dynamically skipped
  11027. (defvar org-todo-setup-filter-hook nil
  11028. "Hook for functions that pre-filter todo specs.
  11029. Each function takes a todo spec and returns either nil or the spec
  11030. transformed into canonical form." )
  11031. (defvar org-todo-get-default-hook nil
  11032. "Hook for functions that get a default item for todo.
  11033. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11034. nil or a string to be used for the todo mark." )
  11035. (defvar org-agenda-headline-snapshot-before-repeat)
  11036. (defun org-current-effective-time ()
  11037. "Return current time adjusted for `org-extend-today-until' variable."
  11038. (let* ((ct (org-current-time))
  11039. (dct (decode-time ct))
  11040. (ct1
  11041. (cond
  11042. (org-use-last-clock-out-time-as-effective-time
  11043. (or (org-clock-get-last-clock-out-time) ct))
  11044. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11045. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11046. (t ct))))
  11047. ct1))
  11048. (defun org-todo-yesterday (&optional arg)
  11049. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11050. (interactive "P")
  11051. (if (eq major-mode 'org-agenda-mode)
  11052. (apply 'org-agenda-todo-yesterday arg)
  11053. (let* ((org-use-effective-time t)
  11054. (hour (nth 2 (decode-time (org-current-time))))
  11055. (org-extend-today-until (1+ hour)))
  11056. (org-todo arg))))
  11057. (defvar org-block-entry-blocking ""
  11058. "First entry preventing the TODO state change.")
  11059. (defun org-cancel-repeater ()
  11060. "Cancel a repeater by setting its numeric value to zero."
  11061. (interactive)
  11062. (save-excursion
  11063. (org-back-to-heading t)
  11064. (let ((bound1 (point))
  11065. (bound0 (save-excursion (outline-next-heading) (point))))
  11066. (when (and (re-search-forward
  11067. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11068. org-deadline-time-regexp "\\)\\|\\("
  11069. org-ts-regexp "\\)")
  11070. bound0 t)
  11071. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11072. bound1 t))
  11073. (replace-match "0" t nil nil 1)))))
  11074. (defvar org-state)
  11075. (defvar org-blocked-by-checkboxes)
  11076. (defun org-todo (&optional arg)
  11077. "Change the TODO state of an item.
  11078. The state of an item is given by a keyword at the start of the heading,
  11079. like
  11080. *** TODO Write paper
  11081. *** DONE Call mom
  11082. The different keywords are specified in the variable `org-todo-keywords'.
  11083. By default the available states are \"TODO\" and \"DONE\". So, for this
  11084. example: when the item starts with TODO, it is changed to DONE.
  11085. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11086. DONE are present, add TODO at the beginning of the heading.
  11087. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11088. state.
  11089. With numeric prefix ARG, switch to that state.
  11090. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11091. next set of TODO \
  11092. keywords (nextset).
  11093. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11094. prefix, circumvent any state blocking.
  11095. With a numeric prefix arg of 0, inhibit note taking for the change.
  11096. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11097. When called through ELisp, arg is also interpreted in the following way:
  11098. `none' -> empty state
  11099. \"\" -> switch to empty state
  11100. `done' -> switch to DONE
  11101. `nextset' -> switch to the next set of keywords
  11102. `previousset' -> switch to the previous set of keywords
  11103. \"WAITING\" -> switch to the specified keyword, but only if it
  11104. really is a member of `org-todo-keywords'."
  11105. (interactive "P")
  11106. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11107. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11108. 'region-start-level 'region))
  11109. org-loop-over-headlines-in-active-region)
  11110. (org-map-entries
  11111. `(org-todo ,arg)
  11112. org-loop-over-headlines-in-active-region
  11113. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11114. (when (equal arg '(16)) (setq arg 'nextset))
  11115. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11116. (let ((org-blocker-hook org-blocker-hook)
  11117. commentp
  11118. case-fold-search)
  11119. (when (equal arg '(64))
  11120. (setq arg nil org-blocker-hook nil))
  11121. (when (and org-blocker-hook
  11122. (or org-inhibit-blocking
  11123. (org-entry-get nil "NOBLOCKING")))
  11124. (setq org-blocker-hook nil))
  11125. (save-excursion
  11126. (catch 'exit
  11127. (org-back-to-heading t)
  11128. (when (org-in-commented-heading-p t)
  11129. (org-toggle-comment)
  11130. (setq commentp t))
  11131. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11132. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11133. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11134. (let* ((match-data (match-data))
  11135. (startpos (point-at-bol))
  11136. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11137. (org-log-done org-log-done)
  11138. (org-log-repeat org-log-repeat)
  11139. (org-todo-log-states org-todo-log-states)
  11140. (org-inhibit-logging
  11141. (if (equal arg 0)
  11142. (progn (setq arg nil) 'note) org-inhibit-logging))
  11143. (this (match-string 1))
  11144. (hl-pos (match-beginning 0))
  11145. (head (org-get-todo-sequence-head this))
  11146. (ass (assoc head org-todo-kwd-alist))
  11147. (interpret (nth 1 ass))
  11148. (done-word (nth 3 ass))
  11149. (final-done-word (nth 4 ass))
  11150. (org-last-state (or this ""))
  11151. (completion-ignore-case t)
  11152. (member (member this org-todo-keywords-1))
  11153. (tail (cdr member))
  11154. (org-state (cond
  11155. ((and org-todo-key-trigger
  11156. (or (and (equal arg '(4))
  11157. (eq org-use-fast-todo-selection 'prefix))
  11158. (and (not arg) org-use-fast-todo-selection
  11159. (not (eq org-use-fast-todo-selection
  11160. 'prefix)))))
  11161. ;; Use fast selection.
  11162. (org-fast-todo-selection))
  11163. ((and (equal arg '(4))
  11164. (or (not org-use-fast-todo-selection)
  11165. (not org-todo-key-trigger)))
  11166. ;; Read a state with completion.
  11167. (completing-read
  11168. "State: " (mapcar #'list org-todo-keywords-1)
  11169. nil t))
  11170. ((eq arg 'right)
  11171. (if this
  11172. (if tail (car tail) nil)
  11173. (car org-todo-keywords-1)))
  11174. ((eq arg 'left)
  11175. (unless (equal member org-todo-keywords-1)
  11176. (if this
  11177. (nth (- (length org-todo-keywords-1)
  11178. (length tail) 2)
  11179. org-todo-keywords-1)
  11180. (org-last org-todo-keywords-1))))
  11181. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11182. (setq arg nil))) ;hack to fall back to cycling
  11183. (arg
  11184. ;; User or caller requests a specific state.
  11185. (cond
  11186. ((equal arg "") nil)
  11187. ((eq arg 'none) nil)
  11188. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11189. ((eq arg 'nextset)
  11190. (or (car (cdr (member head org-todo-heads)))
  11191. (car org-todo-heads)))
  11192. ((eq arg 'previousset)
  11193. (let ((org-todo-heads (reverse org-todo-heads)))
  11194. (or (car (cdr (member head org-todo-heads)))
  11195. (car org-todo-heads))))
  11196. ((car (member arg org-todo-keywords-1)))
  11197. ((stringp arg)
  11198. (user-error "State `%s' not valid in this file" arg))
  11199. ((nth (1- (prefix-numeric-value arg))
  11200. org-todo-keywords-1))))
  11201. ((null member) (or head (car org-todo-keywords-1)))
  11202. ((equal this final-done-word) nil) ;-> make empty
  11203. ((null tail) nil) ;-> first entry
  11204. ((memq interpret '(type priority))
  11205. (if (eq this-command last-command)
  11206. (car tail)
  11207. (if (> (length tail) 0)
  11208. (or done-word (car org-done-keywords))
  11209. nil)))
  11210. (t
  11211. (car tail))))
  11212. (org-state (or
  11213. (run-hook-with-args-until-success
  11214. 'org-todo-get-default-hook org-state org-last-state)
  11215. org-state))
  11216. (next (if org-state (concat " " org-state " ") " "))
  11217. (change-plist (list :type 'todo-state-change :from this :to org-state
  11218. :position startpos))
  11219. dolog now-done-p)
  11220. (when org-blocker-hook
  11221. (let (org-blocked-by-checkboxes block-reason)
  11222. (setq org-last-todo-state-is-todo
  11223. (not (member this org-done-keywords)))
  11224. (unless (save-excursion
  11225. (save-match-data
  11226. (org-with-wide-buffer
  11227. (run-hook-with-args-until-failure
  11228. 'org-blocker-hook change-plist))))
  11229. (setq block-reason (if org-blocked-by-checkboxes
  11230. "contained checkboxes"
  11231. (format "\"%s\"" org-block-entry-blocking)))
  11232. (if (called-interactively-p 'interactive)
  11233. (user-error "TODO state change from %s to %s blocked (by %s)"
  11234. this org-state block-reason)
  11235. ;; Fail silently.
  11236. (message "TODO state change from %s to %s blocked (by %s)"
  11237. this org-state block-reason)
  11238. (throw 'exit nil)))))
  11239. (store-match-data match-data)
  11240. (replace-match next t t)
  11241. (cond ((equal this org-state)
  11242. (message "TODO state was already %s" (org-trim next)))
  11243. ((pos-visible-in-window-p hl-pos)
  11244. (message "TODO state changed to %s" (org-trim next))))
  11245. (unless head
  11246. (setq head (org-get-todo-sequence-head org-state)
  11247. ass (assoc head org-todo-kwd-alist)
  11248. interpret (nth 1 ass)
  11249. done-word (nth 3 ass)
  11250. final-done-word (nth 4 ass)))
  11251. (when (memq arg '(nextset previousset))
  11252. (message "Keyword-Set %d/%d: %s"
  11253. (- (length org-todo-sets) -1
  11254. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11255. (length org-todo-sets)
  11256. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11257. (setq org-last-todo-state-is-todo
  11258. (not (member org-state org-done-keywords)))
  11259. (setq now-done-p (and (member org-state org-done-keywords)
  11260. (not (member this org-done-keywords))))
  11261. (and logging (org-local-logging logging))
  11262. (when (and (or org-todo-log-states org-log-done)
  11263. (not (eq org-inhibit-logging t))
  11264. (not (memq arg '(nextset previousset))))
  11265. ;; We need to look at recording a time and note.
  11266. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11267. (nth 2 (assoc this org-todo-log-states))))
  11268. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11269. (setq dolog 'time))
  11270. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11271. (and org-state
  11272. (member org-state org-not-done-keywords)
  11273. (not (member this org-not-done-keywords))))
  11274. ;; This is now a todo state and was not one before
  11275. ;; If there was a CLOSED time stamp, get rid of it.
  11276. (org-add-planning-info nil nil 'closed))
  11277. (when (and now-done-p org-log-done)
  11278. ;; It is now done, and it was not done before.
  11279. (org-add-planning-info 'closed (org-current-effective-time))
  11280. (when (and (not dolog) (eq 'note org-log-done))
  11281. (org-add-log-setup 'done org-state this 'note)))
  11282. (when (and org-state dolog)
  11283. ;; This is a non-nil state, and we need to log it.
  11284. (org-add-log-setup 'state org-state this dolog)))
  11285. ;; Fixup tag positioning.
  11286. (org-todo-trigger-tag-changes org-state)
  11287. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11288. (when org-provide-todo-statistics
  11289. (org-update-parent-todo-statistics))
  11290. (run-hooks 'org-after-todo-state-change-hook)
  11291. (when (and arg (not (member org-state org-done-keywords)))
  11292. (setq head (org-get-todo-sequence-head org-state)))
  11293. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11294. ;; Do we need to trigger a repeat?
  11295. (when now-done-p
  11296. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11297. ;; This is for the agenda, take a snapshot of the headline.
  11298. (save-match-data
  11299. (setq org-agenda-headline-snapshot-before-repeat
  11300. (org-get-heading))))
  11301. (org-auto-repeat-maybe org-state))
  11302. ;; Fixup cursor location if close to the keyword.
  11303. (when (and (outline-on-heading-p)
  11304. (not (bolp))
  11305. (save-excursion (beginning-of-line 1)
  11306. (looking-at org-todo-line-regexp))
  11307. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11308. (goto-char (or (match-end 2) (match-end 1)))
  11309. (and (looking-at " ") (just-one-space)))
  11310. (when org-trigger-hook
  11311. (save-excursion
  11312. (run-hook-with-args 'org-trigger-hook change-plist)))
  11313. (when commentp (org-toggle-comment))))))))
  11314. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11315. "Block turning an entry into a TODO, using the hierarchy.
  11316. This checks whether the current task should be blocked from state
  11317. changes. Such blocking occurs when:
  11318. 1. The task has children which are not all in a completed state.
  11319. 2. A task has a parent with the property :ORDERED:, and there
  11320. are siblings prior to the current task with incomplete
  11321. status.
  11322. 3. The parent of the task is blocked because it has siblings that should
  11323. be done first, or is child of a block grandparent TODO entry."
  11324. (if (not org-enforce-todo-dependencies)
  11325. t ; if locally turned off don't block
  11326. (catch 'dont-block
  11327. ;; If this is not a todo state change, or if this entry is already DONE,
  11328. ;; do not block
  11329. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11330. (member (plist-get change-plist :from)
  11331. (cons 'done org-done-keywords))
  11332. (member (plist-get change-plist :to)
  11333. (cons 'todo org-not-done-keywords))
  11334. (not (plist-get change-plist :to)))
  11335. (throw 'dont-block t))
  11336. ;; If this task has children, and any are undone, it's blocked
  11337. (save-excursion
  11338. (org-back-to-heading t)
  11339. (let ((this-level (funcall outline-level)))
  11340. (outline-next-heading)
  11341. (let ((child-level (funcall outline-level)))
  11342. (while (and (not (eobp))
  11343. (> child-level this-level))
  11344. ;; this todo has children, check whether they are all
  11345. ;; completed
  11346. (when (and (not (org-entry-is-done-p))
  11347. (org-entry-is-todo-p))
  11348. (setq org-block-entry-blocking (org-get-heading))
  11349. (throw 'dont-block nil))
  11350. (outline-next-heading)
  11351. (setq child-level (funcall outline-level))))))
  11352. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11353. ;; any previous siblings are undone, it's blocked
  11354. (save-excursion
  11355. (org-back-to-heading t)
  11356. (let* ((pos (point))
  11357. (parent-pos (and (org-up-heading-safe) (point)))
  11358. (case-fold-search nil))
  11359. (unless parent-pos (throw 'dont-block t)) ; no parent
  11360. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11361. (forward-line 1)
  11362. (re-search-forward org-not-done-heading-regexp pos t))
  11363. (setq org-block-entry-blocking (match-string 0))
  11364. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11365. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11366. (while t
  11367. (goto-char parent-pos)
  11368. (unless (looking-at org-not-done-heading-regexp)
  11369. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11370. (setq pos (point))
  11371. (setq parent-pos (and (org-up-heading-safe) (point)))
  11372. (unless parent-pos (throw 'dont-block t)) ; no parent
  11373. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11374. (forward-line 1)
  11375. (re-search-forward org-not-done-heading-regexp pos t)
  11376. (setq org-block-entry-blocking (org-get-heading)))
  11377. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11378. (defcustom org-track-ordered-property-with-tag nil
  11379. "Should the ORDERED property also be shown as a tag?
  11380. The ORDERED property decides if an entry should require subtasks to be
  11381. completed in sequence. Since a property is not very visible, setting
  11382. this option means that toggling the ORDERED property with the command
  11383. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11384. not relevant for the behavior, but it makes things more visible.
  11385. Note that toggling the tag with tags commands will not change the property
  11386. and therefore not influence behavior!
  11387. This can be t, meaning the tag ORDERED should be used, It can also be a
  11388. string to select a different tag for this task."
  11389. :group 'org-todo
  11390. :type '(choice
  11391. (const :tag "No tracking" nil)
  11392. (const :tag "Track with ORDERED tag" t)
  11393. (string :tag "Use other tag")))
  11394. (defun org-toggle-ordered-property ()
  11395. "Toggle the ORDERED property of the current entry.
  11396. For better visibility, you can track the value of this property with a tag.
  11397. See variable `org-track-ordered-property-with-tag'."
  11398. (interactive)
  11399. (let* ((t1 org-track-ordered-property-with-tag)
  11400. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11401. (save-excursion
  11402. (org-back-to-heading)
  11403. (if (org-entry-get nil "ORDERED")
  11404. (progn
  11405. (org-delete-property "ORDERED")
  11406. (and tag (org-toggle-tag tag 'off))
  11407. (message "Subtasks can be completed in arbitrary order"))
  11408. (org-entry-put nil "ORDERED" "t")
  11409. (and tag (org-toggle-tag tag 'on))
  11410. (message "Subtasks must be completed in sequence")))))
  11411. (defun org-block-todo-from-checkboxes (change-plist)
  11412. "Block turning an entry into a TODO, using checkboxes.
  11413. This checks whether the current task should be blocked from state
  11414. changes because there are unchecked boxes in this entry."
  11415. (if (not org-enforce-todo-checkbox-dependencies)
  11416. t ; if locally turned off don't block
  11417. (catch 'dont-block
  11418. ;; If this is not a todo state change, or if this entry is already DONE,
  11419. ;; do not block
  11420. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11421. (member (plist-get change-plist :from)
  11422. (cons 'done org-done-keywords))
  11423. (member (plist-get change-plist :to)
  11424. (cons 'todo org-not-done-keywords))
  11425. (not (plist-get change-plist :to)))
  11426. (throw 'dont-block t))
  11427. ;; If this task has checkboxes that are not checked, it's blocked
  11428. (save-excursion
  11429. (org-back-to-heading t)
  11430. (let ((beg (point)) end)
  11431. (outline-next-heading)
  11432. (setq end (point))
  11433. (goto-char beg)
  11434. (when (org-list-search-forward
  11435. (concat (org-item-beginning-re)
  11436. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11437. "\\[[- ]\\]")
  11438. end t)
  11439. (when (boundp 'org-blocked-by-checkboxes)
  11440. (setq org-blocked-by-checkboxes t))
  11441. (throw 'dont-block nil))))
  11442. t))) ; do not block
  11443. (defun org-entry-blocked-p ()
  11444. "Non-nil if entry at point is blocked."
  11445. (and (not (org-entry-get nil "NOBLOCKING"))
  11446. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11447. (not (run-hook-with-args-until-failure
  11448. 'org-blocker-hook
  11449. (list :type 'todo-state-change
  11450. :position (point)
  11451. :from 'todo
  11452. :to 'done)))))
  11453. (defun org-update-statistics-cookies (all)
  11454. "Update the statistics cookie, either from TODO or from checkboxes.
  11455. This should be called with the cursor in a line with a statistics
  11456. cookie. When called with a \\[universal-argument] prefix, update
  11457. all statistics cookies in the buffer."
  11458. (interactive "P")
  11459. (if all
  11460. (progn
  11461. (org-update-checkbox-count 'all)
  11462. (org-map-entries 'org-update-parent-todo-statistics))
  11463. (if (not (org-at-heading-p))
  11464. (org-update-checkbox-count)
  11465. (let ((pos (point-marker))
  11466. end l1 l2)
  11467. (ignore-errors (org-back-to-heading t))
  11468. (if (not (org-at-heading-p))
  11469. (org-update-checkbox-count)
  11470. (setq l1 (org-outline-level))
  11471. (setq end (save-excursion
  11472. (outline-next-heading)
  11473. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11474. (point)))
  11475. (if (and (save-excursion
  11476. (re-search-forward
  11477. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11478. (not (save-excursion (re-search-forward
  11479. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11480. (org-update-checkbox-count)
  11481. (if (and l2 (> l2 l1))
  11482. (progn
  11483. (goto-char end)
  11484. (org-update-parent-todo-statistics))
  11485. (goto-char pos)
  11486. (beginning-of-line 1)
  11487. (while (re-search-forward
  11488. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11489. (point-at-eol) t)
  11490. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11491. (goto-char pos)
  11492. (move-marker pos nil)))))
  11493. (defvar org-entry-property-inherited-from) ;; defined below
  11494. (defun org-update-parent-todo-statistics ()
  11495. "Update any statistics cookie in the parent of the current headline.
  11496. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11497. the entire subtree and this will travel up the hierarchy and update
  11498. statistics everywhere."
  11499. (let* ((prop (save-excursion (org-up-heading-safe)
  11500. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11501. (recursive (or (not org-hierarchical-todo-statistics)
  11502. (and prop (string-match "\\<recursive\\>" prop))))
  11503. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11504. 0))
  11505. (first t)
  11506. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11507. level ltoggle l1 new ndel
  11508. (cnt-all 0) (cnt-done 0) is-percent kwd
  11509. checkbox-beg cookie-present)
  11510. (catch 'exit
  11511. (save-excursion
  11512. (beginning-of-line 1)
  11513. (setq ltoggle (funcall outline-level))
  11514. ;; Three situations are to consider:
  11515. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11516. ;; to the top-level ancestor on the headline;
  11517. ;; 2. If parent has "recursive" property, repeat up to the
  11518. ;; headline setting that property, taking inheritance into
  11519. ;; account;
  11520. ;; 3. Else, move up to direct parent and proceed only once.
  11521. (while (and (setq level (org-up-heading-safe))
  11522. (or recursive first)
  11523. (>= (point) lim))
  11524. (setq first nil cookie-present nil)
  11525. (unless (and level
  11526. (not (string-match
  11527. "\\<checkbox\\>"
  11528. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11529. "")))))
  11530. (throw 'exit nil))
  11531. (while (re-search-forward box-re (point-at-eol) t)
  11532. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11533. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11534. (save-match-data
  11535. (unless (outline-next-heading) (throw 'exit nil))
  11536. (while (and (looking-at org-complex-heading-regexp)
  11537. (> (setq l1 (length (match-string 1))) level))
  11538. (setq kwd (and (or recursive (= l1 ltoggle))
  11539. (match-string 2)))
  11540. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11541. (and (eq org-provide-todo-statistics t)
  11542. (or (member kwd org-done-keywords)))
  11543. (and (listp org-provide-todo-statistics)
  11544. (stringp (car org-provide-todo-statistics))
  11545. (or (member kwd org-provide-todo-statistics)
  11546. (member kwd org-done-keywords)))
  11547. (and (listp org-provide-todo-statistics)
  11548. (listp (car org-provide-todo-statistics))
  11549. (or (member kwd (car org-provide-todo-statistics))
  11550. (and (member kwd org-done-keywords)
  11551. (member kwd (cadr org-provide-todo-statistics))))))
  11552. (setq cnt-all (1+ cnt-all))
  11553. (and (eq org-provide-todo-statistics t)
  11554. kwd
  11555. (setq cnt-all (1+ cnt-all))))
  11556. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11557. (member kwd org-done-keywords))
  11558. (and (listp org-provide-todo-statistics)
  11559. (listp (car org-provide-todo-statistics))
  11560. (member kwd org-done-keywords)
  11561. (member kwd (cadr org-provide-todo-statistics)))
  11562. (and (listp org-provide-todo-statistics)
  11563. (stringp (car org-provide-todo-statistics))
  11564. (member kwd org-done-keywords)))
  11565. (setq cnt-done (1+ cnt-done)))
  11566. (outline-next-heading)))
  11567. (setq new
  11568. (if is-percent
  11569. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11570. (max 1 cnt-all)))
  11571. (format "[%d/%d]" cnt-done cnt-all))
  11572. ndel (- (match-end 0) checkbox-beg))
  11573. (goto-char checkbox-beg)
  11574. (insert new)
  11575. (delete-region (point) (+ (point) ndel))
  11576. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11577. (when cookie-present
  11578. (run-hook-with-args 'org-after-todo-statistics-hook
  11579. cnt-done (- cnt-all cnt-done))))))
  11580. (run-hooks 'org-todo-statistics-hook)))
  11581. (defvar org-after-todo-statistics-hook nil
  11582. "Hook that is called after a TODO statistics cookie has been updated.
  11583. Each function is called with two arguments: the number of not-done entries
  11584. and the number of done entries.
  11585. For example, the following function, when added to this hook, will switch
  11586. an entry to DONE when all children are done, and back to TODO when new
  11587. entries are set to a TODO status. Note that this hook is only called
  11588. when there is a statistics cookie in the headline!
  11589. (defun org-summary-todo (n-done n-not-done)
  11590. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11591. (let (org-log-done org-log-states) ; turn off logging
  11592. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11593. ")
  11594. (defvar org-todo-statistics-hook nil
  11595. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11596. This hook runs even if there is no statistics cookie present, in which case
  11597. `org-after-todo-statistics-hook' would not run.")
  11598. (defun org-todo-trigger-tag-changes (state)
  11599. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11600. (let ((l org-todo-state-tags-triggers)
  11601. changes)
  11602. (when (or (not state) (equal state ""))
  11603. (setq changes (append changes (cdr (assoc "" l)))))
  11604. (when (and (stringp state) (> (length state) 0))
  11605. (setq changes (append changes (cdr (assoc state l)))))
  11606. (when (member state org-not-done-keywords)
  11607. (setq changes (append changes (cdr (assq 'todo l)))))
  11608. (when (member state org-done-keywords)
  11609. (setq changes (append changes (cdr (assq 'done l)))))
  11610. (dolist (c changes)
  11611. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11612. (defun org-local-logging (value)
  11613. "Get logging settings from a property VALUE."
  11614. ;; Directly set the variables, they are already local.
  11615. (setq org-log-done nil
  11616. org-log-repeat nil
  11617. org-todo-log-states nil)
  11618. (dolist (w (org-split-string value))
  11619. (let (a)
  11620. (cond
  11621. ((setq a (assoc w org-startup-options))
  11622. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11623. (set (nth 1 a) (nth 2 a))))
  11624. ((setq a (org-extract-log-state-settings w))
  11625. (and (member (car a) org-todo-keywords-1)
  11626. (push a org-todo-log-states)))))))
  11627. (defun org-get-todo-sequence-head (kwd)
  11628. "Return the head of the TODO sequence to which KWD belongs.
  11629. If KWD is not set, check if there is a text property remembering the
  11630. right sequence."
  11631. (let (p)
  11632. (cond
  11633. ((not kwd)
  11634. (or (get-text-property (point-at-bol) 'org-todo-head)
  11635. (progn
  11636. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11637. nil (point-at-eol)))
  11638. (get-text-property p 'org-todo-head))))
  11639. ((not (member kwd org-todo-keywords-1))
  11640. (car org-todo-keywords-1))
  11641. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11642. (defun org-fast-todo-selection ()
  11643. "Fast TODO keyword selection with single keys.
  11644. Returns the new TODO keyword, or nil if no state change should occur."
  11645. (let* ((fulltable org-todo-key-alist)
  11646. (done-keywords org-done-keywords) ;; needed for the faces.
  11647. (maxlen (apply 'max (mapcar
  11648. (lambda (x)
  11649. (if (stringp (car x)) (string-width (car x)) 0))
  11650. fulltable)))
  11651. (expert nil)
  11652. (fwidth (+ maxlen 3 1 3))
  11653. (ncol (/ (- (window-width) 4) fwidth))
  11654. tg cnt e c tbl
  11655. groups ingroup)
  11656. (save-excursion
  11657. (save-window-excursion
  11658. (if expert
  11659. (set-buffer (get-buffer-create " *Org todo*"))
  11660. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11661. (erase-buffer)
  11662. (setq-local org-done-keywords done-keywords)
  11663. (setq tbl fulltable cnt 0)
  11664. (while (setq e (pop tbl))
  11665. (cond
  11666. ((equal e '(:startgroup))
  11667. (push '() groups) (setq ingroup t)
  11668. (unless (= cnt 0)
  11669. (setq cnt 0)
  11670. (insert "\n"))
  11671. (insert "{ "))
  11672. ((equal e '(:endgroup))
  11673. (setq ingroup nil cnt 0)
  11674. (insert "}\n"))
  11675. ((equal e '(:newline))
  11676. (unless (= cnt 0)
  11677. (setq cnt 0)
  11678. (insert "\n")
  11679. (setq e (car tbl))
  11680. (while (equal (car tbl) '(:newline))
  11681. (insert "\n")
  11682. (setq tbl (cdr tbl)))))
  11683. (t
  11684. (setq tg (car e) c (cdr e))
  11685. (when ingroup (push tg (car groups)))
  11686. (setq tg (org-add-props tg nil 'face
  11687. (org-get-todo-face tg)))
  11688. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11689. (insert "[" c "] " tg (make-string
  11690. (- fwidth 4 (length tg)) ?\ ))
  11691. (when (= (setq cnt (1+ cnt)) ncol)
  11692. (insert "\n")
  11693. (when ingroup (insert " "))
  11694. (setq cnt 0)))))
  11695. (insert "\n")
  11696. (goto-char (point-min))
  11697. (unless expert (org-fit-window-to-buffer))
  11698. (message "[a-z..]:Set [SPC]:clear")
  11699. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11700. (cond
  11701. ((or (= c ?\C-g)
  11702. (and (= c ?q) (not (rassoc c fulltable))))
  11703. (setq quit-flag t))
  11704. ((= c ?\ ) nil)
  11705. ((setq e (rassoc c fulltable) tg (car e))
  11706. tg)
  11707. (t (setq quit-flag t)))))))
  11708. (defun org-entry-is-todo-p ()
  11709. (member (org-get-todo-state) org-not-done-keywords))
  11710. (defun org-entry-is-done-p ()
  11711. (member (org-get-todo-state) org-done-keywords))
  11712. (defun org-get-todo-state ()
  11713. "Return the TODO keyword of the current subtree."
  11714. (save-excursion
  11715. (org-back-to-heading t)
  11716. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11717. (match-end 2)
  11718. (match-string 2))))
  11719. (defun org-at-date-range-p (&optional inactive-ok)
  11720. "Non-nil if point is inside a date range.
  11721. When optional argument INACTIVE-OK is non-nil, also consider
  11722. inactive time ranges.
  11723. When this function returns a non-nil value, match data is set
  11724. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11725. on INACTIVE-OK."
  11726. (interactive)
  11727. (save-excursion
  11728. (catch 'exit
  11729. (let ((pos (point)))
  11730. (skip-chars-backward "^[<\r\n")
  11731. (skip-chars-backward "<[")
  11732. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11733. (>= (match-end 0) pos)
  11734. (throw 'exit t))
  11735. (skip-chars-backward "^<[\r\n")
  11736. (skip-chars-backward "<[")
  11737. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11738. (>= (match-end 0) pos)
  11739. (throw 'exit t)))
  11740. nil)))
  11741. (defun org-get-repeat (&optional timestamp)
  11742. "Check if there is a time-stamp with repeater in this entry.
  11743. Return the repeater, as a string, or nil. Also return nil when
  11744. this function is called before first heading.
  11745. When optional argument TIMESTAMP is a string, extract the
  11746. repeater from there instead."
  11747. (save-match-data
  11748. (cond (timestamp
  11749. (and (string-match org-repeat-re timestamp)
  11750. (match-string-no-properties 1 timestamp)))
  11751. ((org-before-first-heading-p) nil)
  11752. (t
  11753. (save-excursion
  11754. (org-back-to-heading t)
  11755. (let ((end (org-entry-end-position)))
  11756. (catch :repeat
  11757. (while (re-search-forward org-repeat-re end t)
  11758. (when (save-match-data (org-at-timestamp-p 'agenda))
  11759. (throw :repeat (match-string-no-properties 1)))))))))))
  11760. (defvar org-last-changed-timestamp)
  11761. (defvar org-last-inserted-timestamp)
  11762. (defvar org-log-post-message)
  11763. (defvar org-log-note-purpose)
  11764. (defvar org-log-note-how nil)
  11765. (defvar org-log-note-extra)
  11766. (defun org-auto-repeat-maybe (done-word)
  11767. "Check if the current headline contains a repeated time-stamp.
  11768. If yes, set TODO state back to what it was and change the base date
  11769. of repeating deadline/scheduled time stamps to new date.
  11770. This function is run automatically after each state change to a DONE state."
  11771. (let* ((repeat (org-get-repeat))
  11772. (aa (assoc org-last-state org-todo-kwd-alist))
  11773. (interpret (nth 1 aa))
  11774. (head (nth 2 aa))
  11775. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11776. (msg "Entry repeats: ")
  11777. (org-log-done nil)
  11778. (org-todo-log-states nil)
  11779. (end (copy-marker (org-entry-end-position))))
  11780. (unwind-protect
  11781. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11782. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11783. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11784. org-todo-repeat-to-state)))
  11785. (org-todo (cond
  11786. ((and to-state (member to-state org-todo-keywords-1))
  11787. to-state)
  11788. ((eq interpret 'type) org-last-state)
  11789. (head)
  11790. (t 'none))))
  11791. (org-back-to-heading t)
  11792. (org-add-planning-info nil nil 'closed)
  11793. ;; When `org-log-repeat' is non-nil or entry contains
  11794. ;; a clock, set LAST_REPEAT property.
  11795. (when (or org-log-repeat
  11796. (catch :clock
  11797. (while (re-search-forward org-clock-line-re end t)
  11798. (when (org-at-clock-log-p) (throw :clock t)))))
  11799. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11800. (org-time-stamp-format t t)
  11801. (current-time))))
  11802. (when org-log-repeat
  11803. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11804. (memq 'org-add-log-note post-command-hook))
  11805. ;; We are already setup for some record.
  11806. (when (eq org-log-repeat 'note)
  11807. ;; Make sure we take a note, not only a time stamp.
  11808. (setq org-log-note-how 'note))
  11809. ;; Set up for taking a record.
  11810. (org-add-log-setup 'state
  11811. (or done-word (car org-done-keywords))
  11812. org-last-state
  11813. org-log-repeat)))
  11814. (let ((planning-re (regexp-opt
  11815. (list org-scheduled-string org-deadline-string))))
  11816. (while (re-search-forward org-ts-regexp end t)
  11817. (let* ((ts (match-string 0))
  11818. (planning? (org-at-planning-p))
  11819. (type (if (not planning?) "Plain:"
  11820. (save-excursion
  11821. (re-search-backward
  11822. planning-re (line-beginning-position) t)
  11823. (match-string 0)))))
  11824. (cond
  11825. ;; Ignore fake time-stamps (e.g., within comments).
  11826. ((not (org-at-timestamp-p 'agenda)))
  11827. ;; Time-stamps without a repeater are usually
  11828. ;; skipped. However, a SCHEDULED time-stamp without
  11829. ;; one is removed, as they are no longer relevant.
  11830. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11831. ts))
  11832. (when (equal type org-scheduled-string)
  11833. (org-remove-timestamp-with-keyword type)))
  11834. (t
  11835. (let ((n (string-to-number (match-string 2 ts)))
  11836. (what (match-string 3 ts)))
  11837. (when (equal what "w") (setq n (* n 7) what "d"))
  11838. (when (and (equal what "h")
  11839. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11840. ts)))
  11841. (user-error
  11842. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11843. has been set"
  11844. n))
  11845. ;; Preparation, see if we need to modify the start
  11846. ;; date for the change.
  11847. (when (match-end 1)
  11848. (let ((time (save-match-data
  11849. (org-time-string-to-time ts))))
  11850. (cond
  11851. ((equal (match-string 1 ts) ".")
  11852. ;; Shift starting date to today
  11853. (org-timestamp-change
  11854. (- (org-today) (time-to-days time))
  11855. 'day))
  11856. ((equal (match-string 1 ts) "+")
  11857. (let ((nshiftmax 10)
  11858. (nshift 0))
  11859. (while (or (= nshift 0)
  11860. (not (time-less-p (current-time) time)))
  11861. (when (= (cl-incf nshift) nshiftmax)
  11862. (or (y-or-n-p
  11863. (format "%d repeater intervals were not \
  11864. enough to shift date past today. Continue? "
  11865. nshift))
  11866. (user-error "Abort")))
  11867. (org-timestamp-change n (cdr (assoc what whata)))
  11868. (org-in-regexp org-ts-regexp3)
  11869. (setq ts (match-string 1))
  11870. (setq time
  11871. (save-match-data
  11872. (org-time-string-to-time ts)))))
  11873. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11874. ;; Rematch, so that we have everything in place
  11875. ;; for the real shift.
  11876. (org-in-regexp org-ts-regexp3)
  11877. (setq ts (match-string 1))
  11878. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11879. ts)))))
  11880. (save-excursion
  11881. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11882. (setq msg
  11883. (concat
  11884. msg type " " org-last-changed-timestamp " "))))))))
  11885. (setq org-log-post-message msg)
  11886. (message "%s" msg))
  11887. (set-marker end nil))))
  11888. (defun org-show-todo-tree (arg)
  11889. "Make a compact tree which shows all headlines marked with TODO.
  11890. The tree will show the lines where the regexp matches, and all higher
  11891. headlines above the match.
  11892. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11893. With a numeric prefix N, construct a sparse tree for the Nth element
  11894. of `org-todo-keywords-1'."
  11895. (interactive "P")
  11896. (let ((case-fold-search nil)
  11897. (kwd-re
  11898. (cond ((null arg) org-not-done-regexp)
  11899. ((equal arg '(4))
  11900. (let ((kwd
  11901. (completing-read "Keyword (or KWD1|KWD2|...): "
  11902. (mapcar #'list org-todo-keywords-1))))
  11903. (concat "\\("
  11904. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11905. "\\)\\>")))
  11906. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11907. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11908. org-todo-keywords-1)))
  11909. (t (user-error "Invalid prefix argument: %s" arg)))))
  11910. (message "%d TODO entries found"
  11911. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11912. (defun org--deadline-or-schedule (arg type time)
  11913. "Insert DEADLINE or SCHEDULE information in current entry.
  11914. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11915. `org-schedule' for information about ARG and TIME arguments."
  11916. (let* ((deadline? (eq type 'deadline))
  11917. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11918. (log (if deadline? org-log-redeadline org-log-reschedule))
  11919. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11920. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11921. ;; Save repeater cookie from either TIME or current scheduled
  11922. ;; time stamp. We are going to insert it back at the end of
  11923. ;; the process.
  11924. (repeater (or (and (org-string-nw-p time)
  11925. ;; We use `org-repeat-re' because we need
  11926. ;; to tell the difference between a real
  11927. ;; repeater and a time delta, e.g. "+2d".
  11928. (string-match org-repeat-re time)
  11929. (match-string 1 time))
  11930. (and (org-string-nw-p old-date)
  11931. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11932. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11933. old-date)
  11934. (match-string 1 old-date)))))
  11935. (pcase arg
  11936. (`(4)
  11937. (when (and old-date log)
  11938. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11939. nil old-date log))
  11940. (org-remove-timestamp-with-keyword keyword)
  11941. (message (if deadline? "Item no longer has a deadline."
  11942. "Item is no longer scheduled.")))
  11943. (`(16)
  11944. (save-excursion
  11945. (org-back-to-heading t)
  11946. (let ((regexp (if deadline? org-deadline-time-regexp
  11947. org-scheduled-time-regexp)))
  11948. (if (not (re-search-forward regexp (line-end-position 2) t))
  11949. (user-error (if deadline? "No deadline information to update"
  11950. "No scheduled information to update"))
  11951. (let* ((rpl0 (match-string 1))
  11952. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11953. (msg (if deadline? "Warn starting from" "Delay until")))
  11954. (replace-match
  11955. (concat keyword
  11956. " <" rpl
  11957. (format " -%dd"
  11958. (abs (- (time-to-days
  11959. (save-match-data
  11960. (org-read-date
  11961. nil t nil msg old-date-time)))
  11962. (time-to-days old-date-time))))
  11963. ">") t t))))))
  11964. (_
  11965. (org-add-planning-info type time 'closed)
  11966. (when (and old-date
  11967. log
  11968. (not (equal old-date org-last-inserted-timestamp)))
  11969. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11970. org-last-inserted-timestamp
  11971. old-date
  11972. log))
  11973. (when repeater
  11974. (save-excursion
  11975. (org-back-to-heading t)
  11976. (when (re-search-forward
  11977. (concat keyword " " org-last-inserted-timestamp)
  11978. (line-end-position 2)
  11979. t)
  11980. (goto-char (1- (match-end 0)))
  11981. (insert " " repeater)
  11982. (setq org-last-inserted-timestamp
  11983. (concat (substring org-last-inserted-timestamp 0 -1)
  11984. " " repeater
  11985. (substring org-last-inserted-timestamp -1))))))
  11986. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11987. org-last-inserted-timestamp)))))
  11988. (defun org-deadline (arg &optional time)
  11989. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11990. With one universal prefix argument, remove any deadline from the item.
  11991. With two universal prefix arguments, prompt for a warning delay.
  11992. With argument TIME, set the deadline at the corresponding date. TIME
  11993. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11994. (interactive "P")
  11995. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11996. (org-map-entries
  11997. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11998. nil
  11999. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12000. 'region-start-level
  12001. 'region)
  12002. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12003. (org--deadline-or-schedule arg 'deadline time)))
  12004. (defun org-schedule (arg &optional time)
  12005. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12006. With one universal prefix argument, remove any scheduling date from the item.
  12007. With two universal prefix arguments, prompt for a delay cookie.
  12008. With argument TIME, scheduled at the corresponding date. TIME can
  12009. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12010. (interactive "P")
  12011. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12012. (org-map-entries
  12013. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12014. nil
  12015. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12016. 'region-start-level
  12017. 'region)
  12018. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12019. (org--deadline-or-schedule arg 'scheduled time)))
  12020. (defun org-get-scheduled-time (pom &optional inherit)
  12021. "Get the scheduled time as a time tuple, of a format suitable
  12022. for calling org-schedule with, or if there is no scheduling,
  12023. returns nil."
  12024. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12025. (when time
  12026. (apply 'encode-time (org-parse-time-string time)))))
  12027. (defun org-get-deadline-time (pom &optional inherit)
  12028. "Get the deadline as a time tuple, of a format suitable for
  12029. calling org-deadline with, or if there is no scheduling, returns
  12030. nil."
  12031. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12032. (when time
  12033. (apply 'encode-time (org-parse-time-string time)))))
  12034. (defun org-remove-timestamp-with-keyword (keyword)
  12035. "Remove all time stamps with KEYWORD in the current entry."
  12036. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12037. beg)
  12038. (save-excursion
  12039. (org-back-to-heading t)
  12040. (setq beg (point))
  12041. (outline-next-heading)
  12042. (while (re-search-backward re beg t)
  12043. (replace-match "")
  12044. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12045. (equal (char-before) ?\ ))
  12046. (backward-delete-char 1)
  12047. (when (string-match "^[ \t]*$" (buffer-substring
  12048. (point-at-bol) (point-at-eol)))
  12049. (delete-region (point-at-bol)
  12050. (min (point-max) (1+ (point-at-eol))))))))))
  12051. (defvar org-time-was-given) ; dynamically scoped parameter
  12052. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12053. (defun org-at-planning-p ()
  12054. "Non-nil when point is on a planning info line."
  12055. ;; This is as accurate and faster than `org-element-at-point' since
  12056. ;; planning info location is fixed in the section.
  12057. (org-with-wide-buffer
  12058. (beginning-of-line)
  12059. (and (looking-at-p org-planning-line-re)
  12060. (eq (point)
  12061. (ignore-errors
  12062. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12063. (org-back-to-heading t)
  12064. (org-with-limited-levels (org-back-to-heading t)))
  12065. (line-beginning-position 2))))))
  12066. (defun org-add-planning-info (what &optional time &rest remove)
  12067. "Insert new timestamp with keyword in the planning line.
  12068. WHAT indicates what kind of time stamp to add. It is a symbol
  12069. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12070. the time to use. If none is given, the user is prompted for
  12071. a date. REMOVE indicates what kind of entries to remove. An old
  12072. WHAT entry will also be removed."
  12073. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12074. (catch 'exit
  12075. (when (and (memq what '(scheduled deadline))
  12076. (or (not time)
  12077. (and (stringp time)
  12078. (string-match "^[-+]+[0-9]" time))))
  12079. ;; Try to get a default date/time from existing timestamp
  12080. (save-excursion
  12081. (org-back-to-heading t)
  12082. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12083. (when (re-search-forward (if (eq what 'scheduled)
  12084. org-scheduled-time-regexp
  12085. org-deadline-time-regexp)
  12086. end t)
  12087. (setq ts (match-string 1)
  12088. default-time (apply 'encode-time (org-parse-time-string ts))
  12089. default-input (and ts (org-get-compact-tod ts)))))))
  12090. (when what
  12091. (setq time
  12092. (if (stringp time)
  12093. ;; This is a string (relative or absolute), set
  12094. ;; proper date.
  12095. (apply #'encode-time
  12096. (org-read-date-analyze
  12097. time default-time (decode-time default-time)))
  12098. ;; If necessary, get the time from the user
  12099. (or time (org-read-date nil 'to-time nil nil
  12100. default-time default-input)))))
  12101. (org-with-wide-buffer
  12102. (org-back-to-heading t)
  12103. (forward-line)
  12104. (unless (bolp) (insert "\n"))
  12105. (cond ((looking-at-p org-planning-line-re)
  12106. ;; Move to current indentation.
  12107. (skip-chars-forward " \t")
  12108. ;; Check if we have to remove something.
  12109. (dolist (type (if what (cons what remove) remove))
  12110. (save-excursion
  12111. (when (re-search-forward
  12112. (cl-case type
  12113. (closed org-closed-time-regexp)
  12114. (deadline org-deadline-time-regexp)
  12115. (scheduled org-scheduled-time-regexp)
  12116. (otherwise
  12117. (error "Invalid planning type: %s" type)))
  12118. (line-end-position) t)
  12119. ;; Delete until next keyword or end of line.
  12120. (delete-region
  12121. (match-beginning 0)
  12122. (if (re-search-forward org-keyword-time-not-clock-regexp
  12123. (line-end-position)
  12124. t)
  12125. (match-beginning 0)
  12126. (line-end-position))))))
  12127. ;; If there is nothing more to add and no more keyword
  12128. ;; is left, remove the line completely.
  12129. (if (and (looking-at-p "[ \t]*$") (not what))
  12130. (delete-region (line-beginning-position)
  12131. (line-beginning-position 2))
  12132. ;; If we removed last keyword, do not leave trailing
  12133. ;; white space at the end of line.
  12134. (let ((p (point)))
  12135. (save-excursion
  12136. (end-of-line)
  12137. (unless (= (skip-chars-backward " \t" p) 0)
  12138. (delete-region (point) (line-end-position)))))))
  12139. ((not what) (throw 'exit nil)) ; Nothing to do.
  12140. (t (insert-before-markers "\n")
  12141. (backward-char 1)
  12142. (when org-adapt-indentation
  12143. (indent-to-column (1+ (org-outline-level))))))
  12144. (when what
  12145. ;; Insert planning keyword.
  12146. (insert (cl-case what
  12147. (closed org-closed-string)
  12148. (deadline org-deadline-string)
  12149. (scheduled org-scheduled-string)
  12150. (otherwise (error "Invalid planning type: %s" what)))
  12151. " ")
  12152. ;; Insert associated timestamp.
  12153. (let ((ts (org-insert-time-stamp
  12154. time
  12155. (or org-time-was-given
  12156. (and (eq what 'closed) org-log-done-with-time))
  12157. (eq what 'closed)
  12158. nil nil (list org-end-time-was-given))))
  12159. (unless (eolp) (insert " "))
  12160. ts))))))
  12161. (defvar org-log-note-marker (make-marker)
  12162. "Marker pointing at the entry where the note is to be inserted.")
  12163. (defvar org-log-note-purpose nil)
  12164. (defvar org-log-note-state nil)
  12165. (defvar org-log-note-previous-state nil)
  12166. (defvar org-log-note-extra nil)
  12167. (defvar org-log-note-window-configuration nil)
  12168. (defvar org-log-note-return-to (make-marker))
  12169. (defvar org-log-note-effective-time nil
  12170. "Remembered current time so that dynamically scoped
  12171. `org-extend-today-until' affects timestamps in state change log")
  12172. (defvar org-log-post-message nil
  12173. "Message to be displayed after a log note has been stored.
  12174. The auto-repeater uses this.")
  12175. (defun org-add-note ()
  12176. "Add a note to the current entry.
  12177. This is done in the same way as adding a state change note."
  12178. (interactive)
  12179. (org-add-log-setup 'note))
  12180. (defun org-log-beginning (&optional create)
  12181. "Return expected start of log notes in current entry.
  12182. When optional argument CREATE is non-nil, the function creates
  12183. a drawer to store notes, if necessary. Returned position ignores
  12184. narrowing."
  12185. (org-with-wide-buffer
  12186. (let ((drawer (org-log-into-drawer)))
  12187. (cond
  12188. (drawer
  12189. (org-end-of-meta-data)
  12190. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12191. (end (if (org-at-heading-p) (point)
  12192. (save-excursion (outline-next-heading) (point))))
  12193. (case-fold-search t))
  12194. (catch 'exit
  12195. ;; Try to find existing drawer.
  12196. (while (re-search-forward regexp end t)
  12197. (let ((element (org-element-at-point)))
  12198. (when (eq (org-element-type element) 'drawer)
  12199. (let ((cend (org-element-property :contents-end element)))
  12200. (when (and (not org-log-states-order-reversed) cend)
  12201. (goto-char cend)))
  12202. (throw 'exit nil))))
  12203. ;; No drawer found. Create one, if permitted.
  12204. (when create
  12205. (unless (bolp) (insert "\n"))
  12206. (let ((beg (point)))
  12207. (insert ":" drawer ":\n:END:\n")
  12208. (org-indent-region beg (point)))
  12209. (end-of-line -1)))))
  12210. (t
  12211. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12212. (skip-chars-forward " \t\n")
  12213. (beginning-of-line)
  12214. (unless org-log-states-order-reversed
  12215. (org-skip-over-state-notes)
  12216. (skip-chars-backward " \t\n")
  12217. (forward-line)))))
  12218. (if (bolp) (point) (line-beginning-position 2))))
  12219. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12220. "Set up the post command hook to take a note.
  12221. If this is about to TODO state change, the new state is expected in STATE.
  12222. HOW is an indicator what kind of note should be created.
  12223. EXTRA is additional text that will be inserted into the notes buffer."
  12224. (move-marker org-log-note-marker (point))
  12225. (setq org-log-note-purpose purpose
  12226. org-log-note-state state
  12227. org-log-note-previous-state prev-state
  12228. org-log-note-how how
  12229. org-log-note-extra extra
  12230. org-log-note-effective-time (org-current-effective-time))
  12231. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12232. (defun org-skip-over-state-notes ()
  12233. "Skip past the list of State notes in an entry."
  12234. (when (ignore-errors (goto-char (org-in-item-p)))
  12235. (let* ((struct (org-list-struct))
  12236. (prevs (org-list-prevs-alist struct))
  12237. (regexp
  12238. (concat "[ \t]*- +"
  12239. (replace-regexp-in-string
  12240. " +" " +"
  12241. (org-replace-escapes
  12242. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12243. `(("%d" . ,org-ts-regexp-inactive)
  12244. ("%D" . ,org-ts-regexp)
  12245. ("%s" . "\"\\S-+\"")
  12246. ("%S" . "\"\\S-+\"")
  12247. ("%t" . ,org-ts-regexp-inactive)
  12248. ("%T" . ,org-ts-regexp)
  12249. ("%u" . ".*?")
  12250. ("%U" . ".*?")))))))
  12251. (while (looking-at-p regexp)
  12252. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12253. (org-list-get-item-end (point) struct)))))))
  12254. (defun org-add-log-note (&optional _purpose)
  12255. "Pop up a window for taking a note, and add this note later."
  12256. (remove-hook 'post-command-hook 'org-add-log-note)
  12257. (setq org-log-note-window-configuration (current-window-configuration))
  12258. (delete-other-windows)
  12259. (move-marker org-log-note-return-to (point))
  12260. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12261. (goto-char org-log-note-marker)
  12262. (org-switch-to-buffer-other-window "*Org Note*")
  12263. (erase-buffer)
  12264. (if (memq org-log-note-how '(time state))
  12265. (let (current-prefix-arg) (org-store-log-note))
  12266. (let ((org-inhibit-startup t)) (org-mode))
  12267. (insert (format "# Insert note for %s.
  12268. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12269. (cond
  12270. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12271. ((eq org-log-note-purpose 'done) "closed todo item")
  12272. ((eq org-log-note-purpose 'state)
  12273. (format "state change from \"%s\" to \"%s\""
  12274. (or org-log-note-previous-state "")
  12275. (or org-log-note-state "")))
  12276. ((eq org-log-note-purpose 'reschedule)
  12277. "rescheduling")
  12278. ((eq org-log-note-purpose 'delschedule)
  12279. "no longer scheduled")
  12280. ((eq org-log-note-purpose 'redeadline)
  12281. "changing deadline")
  12282. ((eq org-log-note-purpose 'deldeadline)
  12283. "removing deadline")
  12284. ((eq org-log-note-purpose 'refile)
  12285. "refiling")
  12286. ((eq org-log-note-purpose 'note)
  12287. "this entry")
  12288. (t (error "This should not happen")))))
  12289. (when org-log-note-extra (insert org-log-note-extra))
  12290. (setq-local org-finish-function 'org-store-log-note)
  12291. (run-hooks 'org-log-buffer-setup-hook)))
  12292. (defvar org-note-abort nil) ; dynamically scoped
  12293. (defun org-store-log-note ()
  12294. "Finish taking a log note, and insert it to where it belongs."
  12295. (let ((txt (prog1 (buffer-string)
  12296. (kill-buffer)))
  12297. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12298. lines)
  12299. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12300. (setq txt (replace-match "" t t txt)))
  12301. (when (string-match "\\s-+\\'" txt)
  12302. (setq txt (replace-match "" t t txt)))
  12303. (setq lines (org-split-string txt "\n"))
  12304. (when (org-string-nw-p note)
  12305. (setq note
  12306. (org-replace-escapes
  12307. note
  12308. (list (cons "%u" (user-login-name))
  12309. (cons "%U" user-full-name)
  12310. (cons "%t" (format-time-string
  12311. (org-time-stamp-format 'long 'inactive)
  12312. org-log-note-effective-time))
  12313. (cons "%T" (format-time-string
  12314. (org-time-stamp-format 'long nil)
  12315. org-log-note-effective-time))
  12316. (cons "%d" (format-time-string
  12317. (org-time-stamp-format nil 'inactive)
  12318. org-log-note-effective-time))
  12319. (cons "%D" (format-time-string
  12320. (org-time-stamp-format nil nil)
  12321. org-log-note-effective-time))
  12322. (cons "%s" (cond
  12323. ((not org-log-note-state) "")
  12324. ((string-match-p org-ts-regexp
  12325. org-log-note-state)
  12326. (format "\"[%s]\""
  12327. (substring org-log-note-state 1 -1)))
  12328. (t (format "\"%s\"" org-log-note-state))))
  12329. (cons "%S"
  12330. (cond
  12331. ((not org-log-note-previous-state) "")
  12332. ((string-match-p org-ts-regexp
  12333. org-log-note-previous-state)
  12334. (format "\"[%s]\""
  12335. (substring
  12336. org-log-note-previous-state 1 -1)))
  12337. (t (format "\"%s\""
  12338. org-log-note-previous-state)))))))
  12339. (when lines (setq note (concat note " \\\\")))
  12340. (push note lines))
  12341. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12342. (with-current-buffer (marker-buffer org-log-note-marker)
  12343. (org-with-wide-buffer
  12344. ;; Find location for the new note.
  12345. (goto-char org-log-note-marker)
  12346. (set-marker org-log-note-marker nil)
  12347. ;; Note associated to a clock is to be located right after
  12348. ;; the clock. Do not move point.
  12349. (unless (eq org-log-note-purpose 'clock-out)
  12350. (goto-char (org-log-beginning t)))
  12351. ;; Make sure point is at the beginning of an empty line.
  12352. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12353. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12354. ;; In an existing list, add a new item at the top level.
  12355. ;; Otherwise, indent line like a regular one.
  12356. (let ((itemp (org-in-item-p)))
  12357. (if itemp
  12358. (indent-line-to
  12359. (let ((struct (save-excursion
  12360. (goto-char itemp) (org-list-struct))))
  12361. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12362. (org-indent-line)))
  12363. (insert (org-list-bullet-string "-") (pop lines))
  12364. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12365. (dolist (line lines)
  12366. (insert "\n")
  12367. (indent-line-to ind)
  12368. (insert line)))
  12369. (message "Note stored")
  12370. (org-back-to-heading t)
  12371. (org-cycle-hide-drawers 'children))
  12372. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12373. ;; from within `org-add-log-note' because `buffer-undo-list'
  12374. ;; is then modified outside of `org-with-remote-undo'.
  12375. (when (eq this-command 'org-agenda-todo)
  12376. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12377. ;; Don't add undo information when called from `org-agenda-todo'.
  12378. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12379. (set-window-configuration org-log-note-window-configuration)
  12380. (with-current-buffer (marker-buffer org-log-note-return-to)
  12381. (goto-char org-log-note-return-to))
  12382. (move-marker org-log-note-return-to nil)
  12383. (when org-log-post-message (message "%s" org-log-post-message))))
  12384. (defun org-remove-empty-drawer-at (pos)
  12385. "Remove an empty drawer at position POS.
  12386. POS may also be a marker."
  12387. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12388. (org-with-wide-buffer
  12389. (goto-char pos)
  12390. (let ((drawer (org-element-at-point)))
  12391. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12392. (not (org-element-property :contents-begin drawer)))
  12393. (delete-region (org-element-property :begin drawer)
  12394. (progn (goto-char (org-element-property :end drawer))
  12395. (skip-chars-backward " \r\t\n")
  12396. (forward-line)
  12397. (point))))))))
  12398. (defvar org-ts-type nil)
  12399. (defun org-sparse-tree (&optional arg type)
  12400. "Create a sparse tree, prompt for the details.
  12401. This command can create sparse trees. You first need to select the type
  12402. of match used to create the tree:
  12403. t Show all TODO entries.
  12404. T Show entries with a specific TODO keyword.
  12405. m Show entries selected by a tags/property match.
  12406. p Enter a property name and its value (both with completion on existing
  12407. names/values) and show entries with that property.
  12408. r Show entries matching a regular expression (`/' can be used as well).
  12409. b Show deadlines and scheduled items before a date.
  12410. a Show deadlines and scheduled items after a date.
  12411. d Show deadlines due within `org-deadline-warning-days'.
  12412. D Show deadlines and scheduled items between a date range."
  12413. (interactive "P")
  12414. (setq type (or type org-sparse-tree-default-date-type))
  12415. (setq org-ts-type type)
  12416. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12417. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12418. \[c]ycle through date types: %s"
  12419. (cl-case type
  12420. (all "all timestamps")
  12421. (scheduled "only scheduled")
  12422. (deadline "only deadline")
  12423. (active "only active timestamps")
  12424. (inactive "only inactive timestamps")
  12425. (closed "with a closed time-stamp")
  12426. (otherwise "scheduled/deadline")))
  12427. (let ((answer (read-char-exclusive)))
  12428. (cl-case answer
  12429. (?c
  12430. (org-sparse-tree
  12431. arg
  12432. (cadr
  12433. (memq type '(nil all scheduled deadline active inactive closed)))))
  12434. (?d (call-interactively 'org-check-deadlines))
  12435. (?b (call-interactively 'org-check-before-date))
  12436. (?a (call-interactively 'org-check-after-date))
  12437. (?D (call-interactively 'org-check-dates-range))
  12438. (?t (call-interactively 'org-show-todo-tree))
  12439. (?T (org-show-todo-tree '(4)))
  12440. (?m (call-interactively 'org-match-sparse-tree))
  12441. ((?p ?P)
  12442. (let* ((kwd (completing-read
  12443. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12444. (value (completing-read
  12445. "Value: " (mapcar #'list (org-property-values kwd)))))
  12446. (unless (string-match "\\`{.*}\\'" value)
  12447. (setq value (concat "\"" value "\"")))
  12448. (org-match-sparse-tree arg (concat kwd "=" value))))
  12449. ((?r ?R ?/) (call-interactively 'org-occur))
  12450. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12451. (defvar-local org-occur-highlights nil
  12452. "List of overlays used for occur matches.")
  12453. (defvar-local org-occur-parameters nil
  12454. "Parameters of the active org-occur calls.
  12455. This is a list, each call to org-occur pushes as cons cell,
  12456. containing the regular expression and the callback, onto the list.
  12457. The list can contain several entries if `org-occur' has been called
  12458. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12459. will only contain one set of parameters. When the highlights are
  12460. removed (for example with `C-c C-c', or with the next edit (depending
  12461. on `org-remove-highlights-with-change'), this variable is emptied
  12462. as well.")
  12463. (defun org-occur (regexp &optional keep-previous callback)
  12464. "Make a compact tree which shows all matches of REGEXP.
  12465. The tree will show the lines where the regexp matches, and any other context
  12466. defined in `org-show-context-detail', which see.
  12467. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12468. done by a previous call to `org-occur' will be kept, to allow stacking of
  12469. calls to this command.
  12470. Optional argument CALLBACK can be a function of no argument. In this case,
  12471. it is called with point at the end of the match, match data being set
  12472. accordingly. Current match is shown only if the return value is non-nil.
  12473. The function must neither move point nor alter narrowing."
  12474. (interactive "sRegexp: \nP")
  12475. (when (equal regexp "")
  12476. (user-error "Regexp cannot be empty"))
  12477. (unless keep-previous
  12478. (org-remove-occur-highlights nil nil t))
  12479. (push (cons regexp callback) org-occur-parameters)
  12480. (let ((cnt 0))
  12481. (save-excursion
  12482. (goto-char (point-min))
  12483. (when (or (not keep-previous) ; do not want to keep
  12484. (not org-occur-highlights)) ; no previous matches
  12485. ;; hide everything
  12486. (org-overview))
  12487. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12488. (isearch-no-upper-case-p regexp t)
  12489. org-occur-case-fold-search)))
  12490. (while (re-search-forward regexp nil t)
  12491. (when (or (not callback)
  12492. (save-match-data (funcall callback)))
  12493. (setq cnt (1+ cnt))
  12494. (when org-highlight-sparse-tree-matches
  12495. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12496. (org-show-context 'occur-tree)))))
  12497. (when org-remove-highlights-with-change
  12498. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12499. nil 'local))
  12500. (unless org-sparse-tree-open-archived-trees
  12501. (org-hide-archived-subtrees (point-min) (point-max)))
  12502. (run-hooks 'org-occur-hook)
  12503. (when (called-interactively-p 'interactive)
  12504. (message "%d match(es) for regexp %s" cnt regexp))
  12505. cnt))
  12506. (defun org-occur-next-match (&optional n _reset)
  12507. "Function for `next-error-function' to find sparse tree matches.
  12508. N is the number of matches to move, when negative move backwards.
  12509. This function always goes back to the starting point when no
  12510. match is found."
  12511. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12512. (search-func (if (< n 0)
  12513. 'previous-single-char-property-change
  12514. 'next-single-char-property-change))
  12515. (n (abs n))
  12516. (pos (point))
  12517. p1)
  12518. (catch 'exit
  12519. (while (setq p1 (funcall search-func (point) 'org-type))
  12520. (when (equal p1 limit)
  12521. (goto-char pos)
  12522. (user-error "No more matches"))
  12523. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12524. (setq n (1- n))
  12525. (when (= n 0)
  12526. (goto-char p1)
  12527. (throw 'exit (point))))
  12528. (goto-char p1))
  12529. (goto-char p1)
  12530. (user-error "No more matches"))))
  12531. (defun org-show-context (&optional key)
  12532. "Make sure point and context are visible.
  12533. Optional argument KEY, when non-nil, is a symbol. See
  12534. `org-show-context-detail' for allowed values and how much is to
  12535. be shown."
  12536. (org-show-set-visibility
  12537. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12538. ((cdr (assq key org-show-context-detail)))
  12539. (t (cdr (assq 'default org-show-context-detail))))))
  12540. (defun org-show-set-visibility (detail)
  12541. "Set visibility around point according to DETAIL.
  12542. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12543. `tree', `canonical' or t. See `org-show-context-detail' for more
  12544. information."
  12545. ;; Show current heading and possibly its entry, following headline
  12546. ;; or all children.
  12547. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12548. (org-flag-heading nil)
  12549. (org-show-entry)
  12550. ;; If point is hidden within a drawer or a block, make sure to
  12551. ;; expose it.
  12552. (dolist (o (overlays-at (point)))
  12553. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12554. (delete-overlay o)))
  12555. (unless (org-before-first-heading-p)
  12556. (org-with-limited-levels
  12557. (cl-case detail
  12558. ((tree canonical t) (org-show-children))
  12559. ((nil minimal ancestors))
  12560. (t (save-excursion
  12561. (outline-next-heading)
  12562. (org-flag-heading nil)))))))
  12563. ;; Show all siblings.
  12564. (when (eq detail 'lineage) (org-show-siblings))
  12565. ;; Show ancestors, possibly with their children.
  12566. (when (memq detail '(ancestors lineage tree canonical t))
  12567. (save-excursion
  12568. (while (org-up-heading-safe)
  12569. (org-flag-heading nil)
  12570. (when (memq detail '(canonical t)) (org-show-entry))
  12571. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12572. (defvar org-reveal-start-hook nil
  12573. "Hook run before revealing a location.")
  12574. (defun org-reveal (&optional siblings)
  12575. "Show current entry, hierarchy above it, and the following headline.
  12576. This can be used to show a consistent set of context around
  12577. locations exposed with `org-show-context'.
  12578. With optional argument SIBLINGS, on each level of the hierarchy all
  12579. siblings are shown. This repairs the tree structure to what it would
  12580. look like when opened with hierarchical calls to `org-cycle'.
  12581. With a \\[universal-argument] \\[universal-argument] prefix, \
  12582. go to the parent and show the entire tree."
  12583. (interactive "P")
  12584. (run-hooks 'org-reveal-start-hook)
  12585. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12586. ((equal siblings '(16))
  12587. (save-excursion
  12588. (when (org-up-heading-safe)
  12589. (org-show-subtree)
  12590. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12591. (t (org-show-set-visibility 'lineage))))
  12592. (defun org-highlight-new-match (beg end)
  12593. "Highlight from BEG to END and mark the highlight is an occur headline."
  12594. (let ((ov (make-overlay beg end)))
  12595. (overlay-put ov 'face 'secondary-selection)
  12596. (overlay-put ov 'org-type 'org-occur)
  12597. (push ov org-occur-highlights)))
  12598. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12599. "Remove the occur highlights from the buffer.
  12600. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12601. from the `before-change-functions' in the current buffer."
  12602. (interactive)
  12603. (unless org-inhibit-highlight-removal
  12604. (mapc #'delete-overlay org-occur-highlights)
  12605. (setq org-occur-highlights nil)
  12606. (setq org-occur-parameters nil)
  12607. (unless noremove
  12608. (remove-hook 'before-change-functions
  12609. 'org-remove-occur-highlights 'local))))
  12610. ;;;; Priorities
  12611. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12612. "Regular expression matching the priority indicator.")
  12613. (defvar org-remove-priority-next-time nil)
  12614. (defun org-priority-up ()
  12615. "Increase the priority of the current item."
  12616. (interactive)
  12617. (org-priority 'up))
  12618. (defun org-priority-down ()
  12619. "Decrease the priority of the current item."
  12620. (interactive)
  12621. (org-priority 'down))
  12622. (defun org-priority (&optional action _show)
  12623. "Change the priority of an item.
  12624. ACTION can be `set', `up', `down', or a character."
  12625. (interactive "P")
  12626. (if (equal action '(4))
  12627. (org-show-priority)
  12628. (unless org-enable-priority-commands
  12629. (user-error "Priority commands are disabled"))
  12630. (setq action (or action 'set))
  12631. (let (current new news have remove)
  12632. (save-excursion
  12633. (org-back-to-heading t)
  12634. (when (looking-at org-priority-regexp)
  12635. (setq current (string-to-char (match-string 2))
  12636. have t))
  12637. (cond
  12638. ((eq action 'remove)
  12639. (setq remove t new ?\ ))
  12640. ((or (eq action 'set)
  12641. (integerp action))
  12642. (if (not (eq action 'set))
  12643. (setq new action)
  12644. (message "Priority %c-%c, SPC to remove: "
  12645. org-highest-priority org-lowest-priority)
  12646. (save-match-data
  12647. (setq new (read-char-exclusive))))
  12648. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12649. (= (upcase org-lowest-priority) org-lowest-priority))
  12650. (setq new (upcase new)))
  12651. (cond ((equal new ?\ ) (setq remove t))
  12652. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12653. (user-error "Priority must be between `%c' and `%c'"
  12654. org-highest-priority org-lowest-priority))))
  12655. ((eq action 'up)
  12656. (setq new (if have
  12657. (1- current) ; normal cycling
  12658. ;; last priority was empty
  12659. (if (eq last-command this-command)
  12660. org-lowest-priority ; wrap around empty to lowest
  12661. ;; default
  12662. (if org-priority-start-cycle-with-default
  12663. org-default-priority
  12664. (1- org-default-priority))))))
  12665. ((eq action 'down)
  12666. (setq new (if have
  12667. (1+ current) ; normal cycling
  12668. ;; last priority was empty
  12669. (if (eq last-command this-command)
  12670. org-highest-priority ; wrap around empty to highest
  12671. ;; default
  12672. (if org-priority-start-cycle-with-default
  12673. org-default-priority
  12674. (1+ org-default-priority))))))
  12675. (t (user-error "Invalid action")))
  12676. (when (or (< (upcase new) org-highest-priority)
  12677. (> (upcase new) org-lowest-priority))
  12678. (if (and (memq action '(up down))
  12679. (not have) (not (eq last-command this-command)))
  12680. ;; `new' is from default priority
  12681. (error
  12682. "The default can not be set, see `org-default-priority' why")
  12683. ;; normal cycling: `new' is beyond highest/lowest priority
  12684. ;; and is wrapped around to the empty priority
  12685. (setq remove t)))
  12686. (setq news (format "%c" new))
  12687. (if have
  12688. (if remove
  12689. (replace-match "" t t nil 1)
  12690. (replace-match news t t nil 2))
  12691. (if remove
  12692. (user-error "No priority cookie found in line")
  12693. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12694. (if (match-end 2)
  12695. (progn
  12696. (goto-char (match-end 2))
  12697. (insert " [#" news "]"))
  12698. (goto-char (match-beginning 3))
  12699. (insert "[#" news "] "))))
  12700. (org-set-tags nil 'align))
  12701. (if remove
  12702. (message "Priority removed")
  12703. (message "Priority of current item set to %s" news)))))
  12704. (defun org-show-priority ()
  12705. "Show the priority of the current item.
  12706. This priority is composed of the main priority given with the [#A] cookies,
  12707. and by additional input from the age of a schedules or deadline entry."
  12708. (interactive)
  12709. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12710. (org-get-at-bol 'priority)
  12711. (save-excursion
  12712. (save-match-data
  12713. (beginning-of-line)
  12714. (and (looking-at org-heading-regexp)
  12715. (org-get-priority (match-string 0))))))))
  12716. (message "Priority is %d" (if pri pri -1000))))
  12717. (defun org-get-priority (s)
  12718. "Find priority cookie and return priority."
  12719. (save-match-data
  12720. (if (functionp org-get-priority-function)
  12721. (funcall org-get-priority-function)
  12722. (if (not (string-match org-priority-regexp s))
  12723. (* 1000 (- org-lowest-priority org-default-priority))
  12724. (* 1000 (- org-lowest-priority
  12725. (string-to-char (match-string 2 s))))))))
  12726. ;;;; Tags
  12727. (defvar org-agenda-archives-mode)
  12728. (defvar org-map-continue-from nil
  12729. "Position from where mapping should continue.
  12730. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12731. (defvar org-scanner-tags nil
  12732. "The current tag list while the tags scanner is running.")
  12733. (defvar org-trust-scanner-tags nil
  12734. "Should `org-get-tags-at' use the tags for the scanner.
  12735. This is for internal dynamical scoping only.
  12736. When this is non-nil, the function `org-get-tags-at' will return the value
  12737. of `org-scanner-tags' instead of building the list by itself. This
  12738. can lead to large speed-ups when the tags scanner is used in a file with
  12739. many entries, and when the list of tags is retrieved, for example to
  12740. obtain a list of properties. Building the tags list for each entry in such
  12741. a file becomes an N^2 operation - but with this variable set, it scales
  12742. as N.")
  12743. (defvar org--matcher-tags-todo-only nil)
  12744. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12745. "Scan headline tags with inheritance and produce output ACTION.
  12746. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12747. or `agenda' to produce an entry list for an agenda view. It can also be
  12748. a Lisp form or a function that should be called at each matched headline, in
  12749. this case the return value is a list of all return values from these calls.
  12750. MATCHER is a function accepting three arguments, returning
  12751. a non-nil value whenever a given set of tags qualifies a headline
  12752. for inclusion. See `org-make-tags-matcher' for more information.
  12753. As a special case, it can also be set to t (respectively nil) in
  12754. order to match all (respectively none) headline.
  12755. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12756. keyword are included in the output.
  12757. START-LEVEL can be a string with asterisks, reducing the scope to
  12758. headlines matching this string."
  12759. (require 'org-agenda)
  12760. (let* ((re (concat "^"
  12761. (if start-level
  12762. ;; Get the correct level to match
  12763. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12764. org-outline-regexp)
  12765. " *\\(\\<\\("
  12766. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12767. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12768. (props (list 'face 'default
  12769. 'done-face 'org-agenda-done
  12770. 'undone-face 'default
  12771. 'mouse-face 'highlight
  12772. 'org-not-done-regexp org-not-done-regexp
  12773. 'org-todo-regexp org-todo-regexp
  12774. 'org-complex-heading-regexp org-complex-heading-regexp
  12775. 'help-echo
  12776. (format "mouse-2 or RET jump to org file %s"
  12777. (abbreviate-file-name
  12778. (or (buffer-file-name (buffer-base-buffer))
  12779. (buffer-name (buffer-base-buffer)))))))
  12780. (org-map-continue-from nil)
  12781. lspos tags tags-list
  12782. (tags-alist (list (cons 0 org-file-tags)))
  12783. (llast 0) rtn rtn1 level category i txt
  12784. todo marker entry priority
  12785. ts-date ts-date-type ts-date-pair)
  12786. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12787. (setq action (list 'lambda nil action)))
  12788. (save-excursion
  12789. (goto-char (point-min))
  12790. (when (eq action 'sparse-tree)
  12791. (org-overview)
  12792. (org-remove-occur-highlights))
  12793. (while (let (case-fold-search)
  12794. (re-search-forward re nil t))
  12795. (setq org-map-continue-from nil)
  12796. (catch :skip
  12797. (setq todo
  12798. ;; TODO: is the 1-2 difference a bug?
  12799. (when (match-end 1) (match-string-no-properties 2))
  12800. tags (when (match-end 4) (match-string-no-properties 4)))
  12801. (goto-char (setq lspos (match-beginning 0)))
  12802. (setq level (org-reduced-level (org-outline-level))
  12803. category (org-get-category))
  12804. (when (eq action 'agenda)
  12805. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12806. ts-date (car ts-date-pair)
  12807. ts-date-type (cdr ts-date-pair)))
  12808. (setq i llast llast level)
  12809. ;; remove tag lists from same and sublevels
  12810. (while (>= i level)
  12811. (when (setq entry (assoc i tags-alist))
  12812. (setq tags-alist (delete entry tags-alist)))
  12813. (setq i (1- i)))
  12814. ;; add the next tags
  12815. (when tags
  12816. (setq tags (org-split-string tags ":")
  12817. tags-alist
  12818. (cons (cons level tags) tags-alist)))
  12819. ;; compile tags for current headline
  12820. (setq tags-list
  12821. (if org-use-tag-inheritance
  12822. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12823. tags)
  12824. org-scanner-tags tags-list)
  12825. (when org-use-tag-inheritance
  12826. (setcdr (car tags-alist)
  12827. (mapcar (lambda (x)
  12828. (setq x (copy-sequence x))
  12829. (org-add-prop-inherited x))
  12830. (cdar tags-alist))))
  12831. (when (and tags org-use-tag-inheritance
  12832. (or (not (eq t org-use-tag-inheritance))
  12833. org-tags-exclude-from-inheritance))
  12834. ;; Selective inheritance, remove uninherited ones.
  12835. (setcdr (car tags-alist)
  12836. (org-remove-uninherited-tags (cdar tags-alist))))
  12837. (when (and
  12838. ;; eval matcher only when the todo condition is OK
  12839. (and (or (not todo-only) (member todo org-not-done-keywords))
  12840. (if (functionp matcher)
  12841. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12842. (funcall matcher todo tags-list level))
  12843. matcher))
  12844. ;; Call the skipper, but return t if it does not
  12845. ;; skip, so that the `and' form continues evaluating.
  12846. (progn
  12847. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12848. t)
  12849. ;; Check if timestamps are deselecting this entry
  12850. (or (not todo-only)
  12851. (and (member todo org-not-done-keywords)
  12852. (or (not org-agenda-tags-todo-honor-ignore-options)
  12853. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12854. ;; select this headline
  12855. (cond
  12856. ((eq action 'sparse-tree)
  12857. (and org-highlight-sparse-tree-matches
  12858. (org-get-heading) (match-end 0)
  12859. (org-highlight-new-match
  12860. (match-beginning 1) (match-end 1)))
  12861. (org-show-context 'tags-tree))
  12862. ((eq action 'agenda)
  12863. (setq txt (org-agenda-format-item
  12864. ""
  12865. (concat
  12866. (if (eq org-tags-match-list-sublevels 'indented)
  12867. (make-string (1- level) ?.) "")
  12868. (org-get-heading))
  12869. (make-string level ?\s)
  12870. category
  12871. tags-list)
  12872. priority (org-get-priority txt))
  12873. (goto-char lspos)
  12874. (setq marker (org-agenda-new-marker))
  12875. (org-add-props txt props
  12876. 'org-marker marker 'org-hd-marker marker 'org-category category
  12877. 'todo-state todo
  12878. 'ts-date ts-date
  12879. 'priority priority
  12880. 'type (concat "tagsmatch" ts-date-type))
  12881. (push txt rtn))
  12882. ((functionp action)
  12883. (setq org-map-continue-from nil)
  12884. (save-excursion
  12885. (setq rtn1 (funcall action))
  12886. (push rtn1 rtn)))
  12887. (t (user-error "Invalid action")))
  12888. ;; if we are to skip sublevels, jump to end of subtree
  12889. (unless org-tags-match-list-sublevels
  12890. (org-end-of-subtree t)
  12891. (backward-char 1))))
  12892. ;; Get the correct position from where to continue
  12893. (if org-map-continue-from
  12894. (goto-char org-map-continue-from)
  12895. (and (= (point) lspos) (end-of-line 1)))))
  12896. (when (and (eq action 'sparse-tree)
  12897. (not org-sparse-tree-open-archived-trees))
  12898. (org-hide-archived-subtrees (point-min) (point-max)))
  12899. (nreverse rtn)))
  12900. (defun org-remove-uninherited-tags (tags)
  12901. "Remove all tags that are not inherited from the list TAGS."
  12902. (cond
  12903. ((eq org-use-tag-inheritance t)
  12904. (if org-tags-exclude-from-inheritance
  12905. (org-delete-all org-tags-exclude-from-inheritance tags)
  12906. tags))
  12907. ((not org-use-tag-inheritance) nil)
  12908. ((stringp org-use-tag-inheritance)
  12909. (delq nil (mapcar
  12910. (lambda (x)
  12911. (if (and (string-match org-use-tag-inheritance x)
  12912. (not (member x org-tags-exclude-from-inheritance)))
  12913. x nil))
  12914. tags)))
  12915. ((listp org-use-tag-inheritance)
  12916. (delq nil (mapcar
  12917. (lambda (x)
  12918. (if (member x org-use-tag-inheritance) x nil))
  12919. tags)))))
  12920. (defun org-match-sparse-tree (&optional todo-only match)
  12921. "Create a sparse tree according to tags string MATCH.
  12922. MATCH is a string with match syntax. It can contain a selection
  12923. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12924. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12925. those. See the manual for details.
  12926. If optional argument TODO-ONLY is non-nil, only select lines that
  12927. are also TODO tasks."
  12928. (interactive "P")
  12929. (org-agenda-prepare-buffers (list (current-buffer)))
  12930. (let ((org--matcher-tags-todo-only todo-only))
  12931. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12932. org--matcher-tags-todo-only)))
  12933. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12934. (defvar org-cached-props nil)
  12935. (defun org-cached-entry-get (pom property)
  12936. (if (or (eq t org-use-property-inheritance)
  12937. (and (stringp org-use-property-inheritance)
  12938. (let ((case-fold-search t))
  12939. (string-match-p org-use-property-inheritance property)))
  12940. (and (listp org-use-property-inheritance)
  12941. (member-ignore-case property org-use-property-inheritance)))
  12942. ;; Caching is not possible, check it directly.
  12943. (org-entry-get pom property 'inherit)
  12944. ;; Get all properties, so we can do complicated checks easily.
  12945. (cdr (assoc-string property
  12946. (or org-cached-props
  12947. (setq org-cached-props (org-entry-properties pom)))
  12948. t))))
  12949. (defun org-global-tags-completion-table (&optional files)
  12950. "Return the list of all tags in all agenda buffer/files.
  12951. Optional FILES argument is a list of files which can be used
  12952. instead of the agenda files."
  12953. (save-excursion
  12954. (org-uniquify
  12955. (delq nil
  12956. (apply #'append
  12957. (mapcar
  12958. (lambda (file)
  12959. (set-buffer (find-file-noselect file))
  12960. (mapcar (lambda (x)
  12961. (and (stringp (car-safe x))
  12962. (list (car-safe x))))
  12963. (or org-current-tag-alist (org-get-buffer-tags))))
  12964. (if (car-safe files) files
  12965. (org-agenda-files))))))))
  12966. (defun org-make-tags-matcher (match)
  12967. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12968. Returns a cons of the selection string MATCH and a function
  12969. implementing the matcher.
  12970. The matcher is to be called at an Org entry, with point on the
  12971. headline, and returns non-nil if the entry matches the selection
  12972. string MATCH. It must be called with three arguments: the TODO
  12973. keyword at the entry (or nil if none), the list of all tags at
  12974. the entry including inherited ones and the reduced level of the
  12975. headline. Additionally, the category of the entry, if any, must
  12976. be specified as the text property `org-category' on the headline.
  12977. This function sets the variable `org--matcher-tags-todo-only' to
  12978. a non-nil value if the matcher restricts matching to TODO
  12979. entries, otherwise it is not touched.
  12980. See also `org-scan-tags'."
  12981. (unless match
  12982. ;; Get a new match request, with completion against the global
  12983. ;; tags table and the local tags in current buffer.
  12984. (let ((org-last-tags-completion-table
  12985. (org-uniquify
  12986. (delq nil (append (org-get-buffer-tags)
  12987. (org-global-tags-completion-table))))))
  12988. (setq match
  12989. (completing-read
  12990. "Match: "
  12991. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12992. (let ((match0 match)
  12993. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12994. (start 0)
  12995. tagsmatch todomatch tagsmatcher todomatcher)
  12996. ;; Expand group tags.
  12997. (setq match (org-tags-expand match))
  12998. ;; Check if there is a TODO part of this match, which would be the
  12999. ;; part after a "/". To make sure that this slash is not part of
  13000. ;; a property value to be matched against, we also check that
  13001. ;; there is no / after that slash. First, find the last slash.
  13002. (let ((s 0))
  13003. (while (string-match "/+" match s)
  13004. (setq start (match-beginning 0))
  13005. (setq s (match-end 0))))
  13006. (if (and (string-match "/+" match start)
  13007. (not (string-match-p "\"" match start)))
  13008. ;; Match contains also a TODO-matching request.
  13009. (progn
  13010. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13011. (setq todomatch (substring match (match-end 0)))
  13012. (when (string-prefix-p "!" todomatch)
  13013. (setq org--matcher-tags-todo-only t)
  13014. (setq todomatch (substring todomatch 1)))
  13015. (when (string-match "\\`\\s-*\\'" todomatch)
  13016. (setq todomatch nil)))
  13017. ;; Only matching tags.
  13018. (setq tagsmatch match)
  13019. (setq todomatch nil))
  13020. ;; Make the tags matcher.
  13021. (when (org-string-nw-p tagsmatch)
  13022. (let ((orlist nil)
  13023. (orterms (org-split-string tagsmatch "|"))
  13024. term)
  13025. (while (setq term (pop orterms))
  13026. (while (and (equal (substring term -1) "\\") orterms)
  13027. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13028. (while (string-match re term)
  13029. (let* ((rest (substring term (match-end 0)))
  13030. (minus (and (match-end 1)
  13031. (equal (match-string 1 term) "-")))
  13032. (tag (save-match-data
  13033. (replace-regexp-in-string
  13034. "\\\\-" "-" (match-string 2 term))))
  13035. (regexp (eq (string-to-char tag) ?{))
  13036. (levelp (match-end 4))
  13037. (propp (match-end 5))
  13038. (mm
  13039. (cond
  13040. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13041. (levelp
  13042. `(,(org-op-to-function (match-string 3 term))
  13043. level
  13044. ,(string-to-number (match-string 4 term))))
  13045. (propp
  13046. (let* ((gv (pcase (upcase (match-string 5 term))
  13047. ("CATEGORY"
  13048. '(get-text-property (point) 'org-category))
  13049. ("TODO" 'todo)
  13050. (p `(org-cached-entry-get nil ,p))))
  13051. (pv (match-string 7 term))
  13052. (regexp (eq (string-to-char pv) ?{))
  13053. (strp (eq (string-to-char pv) ?\"))
  13054. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13055. (po (org-op-to-function (match-string 6 term)
  13056. (if timep 'time strp))))
  13057. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13058. (when timep (setq pv (org-matcher-time pv)))
  13059. (cond ((and regexp (eq po 'org<>))
  13060. `(not (string-match ,pv (or ,gv ""))))
  13061. (regexp `(string-match ,pv (or ,gv "")))
  13062. (strp `(,po (or ,gv "") ,pv))
  13063. (t
  13064. `(,po
  13065. (string-to-number (or ,gv ""))
  13066. ,(string-to-number pv))))))
  13067. (t `(member ,tag tags-list)))))
  13068. (push (if minus `(not ,mm) mm) tagsmatcher)
  13069. (setq term rest)))
  13070. (push `(and ,@tagsmatcher) orlist)
  13071. (setq tagsmatcher nil))
  13072. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13073. ;; Make the TODO matcher.
  13074. (when (org-string-nw-p todomatch)
  13075. (let ((orlist nil))
  13076. (dolist (term (org-split-string todomatch "|"))
  13077. (while (string-match re term)
  13078. (let* ((minus (and (match-end 1)
  13079. (equal (match-string 1 term) "-")))
  13080. (kwd (match-string 2 term))
  13081. (regexp (eq (string-to-char kwd) ?{))
  13082. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13083. `(equal todo ,kwd))))
  13084. (push (if minus `(not ,mm) mm) todomatcher))
  13085. (setq term (substring term (match-end 0))))
  13086. (push (if (> (length todomatcher) 1)
  13087. (cons 'and todomatcher)
  13088. (car todomatcher))
  13089. orlist)
  13090. (setq todomatcher nil))
  13091. (setq todomatcher (cons 'or orlist))))
  13092. ;; Return the string and function of the matcher. If no
  13093. ;; tags-specific or todo-specific matcher exists, match
  13094. ;; everything.
  13095. (let ((matcher (if (and tagsmatcher todomatcher)
  13096. `(and ,tagsmatcher ,todomatcher)
  13097. (or tagsmatcher todomatcher t))))
  13098. (when org--matcher-tags-todo-only
  13099. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13100. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13101. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13102. "Expand group tags in MATCH.
  13103. This replaces every group tag in MATCH with a regexp tag search.
  13104. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13105. will be replaced like this:
  13106. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13107. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13108. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13109. Replacing by a regexp preserves the structure of the match.
  13110. E.g., this expansion
  13111. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13112. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13113. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13114. A group tag in MATCH can contain regular expressions of its own.
  13115. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13116. will be replaced like this:
  13117. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13118. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13119. assumed to be a single group tag, and the function will return
  13120. the list of tags in this group.
  13121. When DOWNCASE is non-nil, expand downcased TAGS."
  13122. (if org-group-tags
  13123. (let* ((case-fold-search t)
  13124. (stable org-mode-syntax-table)
  13125. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13126. (taggroups (if downcased
  13127. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13128. taggroups)
  13129. taggroups))
  13130. (taggroups-keys (mapcar #'car taggroups))
  13131. (return-match (if downcased (downcase match) match))
  13132. (count 0)
  13133. (work-already-expanded tags-already-expanded)
  13134. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13135. ;; @ and _ are allowed as word-components in tags.
  13136. (modify-syntax-entry ?@ "w" stable)
  13137. (modify-syntax-entry ?_ "w" stable)
  13138. ;; Temporarily replace regexp-expressions in the match-expression.
  13139. (while (string-match "{.+?}" return-match)
  13140. (cl-incf count)
  13141. (push (match-string 0 return-match) regexps-in-match)
  13142. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13143. (while (and taggroups-keys
  13144. (with-syntax-table stable
  13145. (string-match
  13146. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13147. (regexp-opt taggroups-keys) "\\>\\)")
  13148. return-match)))
  13149. (let* ((dir (match-string 1 return-match))
  13150. (tag (match-string 2 return-match))
  13151. (tag (if downcased (downcase tag) tag)))
  13152. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13153. (member tag work-already-expanded))
  13154. (setq tags-in-group (assoc tag taggroups))
  13155. (push tag work-already-expanded)
  13156. ;; Recursively expand each tag in the group, if the tag hasn't
  13157. ;; already been expanded. Restore the match-data after all recursive calls.
  13158. (save-match-data
  13159. (let (tags-expanded)
  13160. (dolist (x (cdr tags-in-group))
  13161. (if (and (member x taggroups-keys)
  13162. (not (member x work-already-expanded)))
  13163. (setq tags-expanded
  13164. (delete-dups
  13165. (append
  13166. (org-tags-expand x t downcased
  13167. work-already-expanded)
  13168. tags-expanded)))
  13169. (setq tags-expanded
  13170. (append (list x) tags-expanded)))
  13171. (setq work-already-expanded
  13172. (delete-dups
  13173. (append tags-expanded
  13174. work-already-expanded))))
  13175. (setq tags-in-group
  13176. (delete-dups (cons (car tags-in-group)
  13177. tags-expanded)))))
  13178. ;; Filter tag-regexps from tags.
  13179. (setq regexp-in-group-escaped
  13180. (delq nil (mapcar (lambda (x)
  13181. (if (stringp x)
  13182. (and (equal "{" (substring x 0 1))
  13183. (equal "}" (substring x -1))
  13184. x)
  13185. x))
  13186. tags-in-group))
  13187. regexp-in-group
  13188. (mapcar (lambda (x)
  13189. (substring x 1 -1))
  13190. regexp-in-group-escaped)
  13191. tags-in-group
  13192. (delq nil (mapcar (lambda (x)
  13193. (if (stringp x)
  13194. (and (not (equal "{" (substring x 0 1)))
  13195. (not (equal "}" (substring x -1)))
  13196. x)
  13197. x))
  13198. tags-in-group)))
  13199. ;; If single-as-list, do no more in the while-loop.
  13200. (if (not single-as-list)
  13201. (progn
  13202. (when regexp-in-group
  13203. (setq regexp-in-group
  13204. (concat "\\|"
  13205. (mapconcat 'identity regexp-in-group
  13206. "\\|"))))
  13207. (setq tags-in-group
  13208. (concat dir
  13209. "{\\<"
  13210. (regexp-opt tags-in-group)
  13211. "\\>"
  13212. regexp-in-group
  13213. "}"))
  13214. (when (stringp tags-in-group)
  13215. (org-add-props tags-in-group '(grouptag t)))
  13216. (setq return-match
  13217. (replace-match tags-in-group t t return-match)))
  13218. (setq tags-in-group
  13219. (append regexp-in-group-escaped tags-in-group))))
  13220. (setq taggroups-keys (delete tag taggroups-keys))))
  13221. ;; Add the regular expressions back into the match-expression again.
  13222. (while regexps-in-match
  13223. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13224. (pop regexps-in-match)
  13225. return-match t t))
  13226. (cl-decf count))
  13227. (if single-as-list
  13228. (if tags-in-group tags-in-group (list return-match))
  13229. return-match))
  13230. (if single-as-list
  13231. (list (if downcased (downcase match) match))
  13232. match)))
  13233. (defun org-op-to-function (op &optional stringp)
  13234. "Turn an operator into the appropriate function."
  13235. (setq op
  13236. (cond
  13237. ((equal op "<" ) '(< string< org-time<))
  13238. ((equal op ">" ) '(> org-string> org-time>))
  13239. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13240. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13241. ((member op '("=" "==")) '(= string= org-time=))
  13242. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13243. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13244. (defun org<> (a b) (not (= a b)))
  13245. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13246. (defun org-string>= (a b) (not (string< a b)))
  13247. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13248. (defun org-string<> (a b) (not (string= a b)))
  13249. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13250. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13251. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13252. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13253. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13254. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13255. (defun org-2ft (s)
  13256. "Convert S to a floating point time.
  13257. If S is already a number, just return it. If it is a string, parse
  13258. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13259. (cond
  13260. ((numberp s) s)
  13261. ((stringp s)
  13262. (condition-case nil
  13263. (float-time (apply 'encode-time (org-parse-time-string s)))
  13264. (error 0.)))
  13265. (t 0.)))
  13266. (defun org-time-today ()
  13267. "Time in seconds today at 0:00.
  13268. Returns the float number of seconds since the beginning of the
  13269. epoch to the beginning of today (00:00)."
  13270. (float-time (apply 'encode-time
  13271. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13272. (defun org-matcher-time (s)
  13273. "Interpret a time comparison value."
  13274. (save-match-data
  13275. (cond
  13276. ((string= s "<now>") (float-time))
  13277. ((string= s "<today>") (org-time-today))
  13278. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13279. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13280. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13281. (+ (org-time-today)
  13282. (* (string-to-number (match-string 1 s))
  13283. (cdr (assoc (match-string 2 s)
  13284. '(("d" . 86400.0) ("w" . 604800.0)
  13285. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13286. (t (org-2ft s)))))
  13287. (defun org-match-any-p (re list)
  13288. "Does re match any element of list?"
  13289. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13290. (delq nil list))
  13291. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13292. (defvar org-tags-overlay (make-overlay 1 1))
  13293. (delete-overlay org-tags-overlay)
  13294. (defun org-get-local-tags-at (&optional pos)
  13295. "Get a list of tags defined in the current headline."
  13296. (org-get-tags-at pos 'local))
  13297. (defun org-get-local-tags ()
  13298. "Get a list of tags defined in the current headline."
  13299. (org-get-tags-at nil 'local))
  13300. (defun org-get-tags-at (&optional pos local)
  13301. "Get a list of all headline tags applicable at POS.
  13302. POS defaults to point. If tags are inherited, the list contains
  13303. the targets in the same sequence as the headlines appear, i.e.
  13304. the tags of the current headline come last.
  13305. When LOCAL is non-nil, only return tags from the current headline,
  13306. ignore inherited ones."
  13307. (interactive)
  13308. (if (and org-trust-scanner-tags
  13309. (or (not pos) (equal pos (point)))
  13310. (not local))
  13311. org-scanner-tags
  13312. (let (tags ltags lastpos parent)
  13313. (save-excursion
  13314. (save-restriction
  13315. (widen)
  13316. (goto-char (or pos (point)))
  13317. (save-match-data
  13318. (catch 'done
  13319. (condition-case nil
  13320. (progn
  13321. (org-back-to-heading t)
  13322. (while (not (equal lastpos (point)))
  13323. (setq lastpos (point))
  13324. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13325. (setq ltags (org-split-string
  13326. (match-string-no-properties 1) ":"))
  13327. (when parent
  13328. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13329. (setq tags (append
  13330. (if parent
  13331. (org-remove-uninherited-tags ltags)
  13332. ltags)
  13333. tags)))
  13334. (or org-use-tag-inheritance (throw 'done t))
  13335. (when local (throw 'done t))
  13336. (or (org-up-heading-safe) (error nil))
  13337. (setq parent t)))
  13338. (error nil)))))
  13339. (if local
  13340. tags
  13341. (reverse (delete-dups
  13342. (reverse (append
  13343. (org-remove-uninherited-tags
  13344. org-file-tags)
  13345. tags)))))))))
  13346. (defun org-add-prop-inherited (s)
  13347. (add-text-properties 0 (length s) '(inherited t) s)
  13348. s)
  13349. (defun org-toggle-tag (tag &optional onoff)
  13350. "Toggle the tag TAG for the current line.
  13351. If ONOFF is `on' or `off', don't toggle but set to this state."
  13352. (let (res current)
  13353. (save-excursion
  13354. (org-back-to-heading t)
  13355. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13356. (point-at-eol) t)
  13357. (progn
  13358. (setq current (match-string 1))
  13359. (replace-match ""))
  13360. (setq current ""))
  13361. (setq current (nreverse (org-split-string current ":")))
  13362. (cond
  13363. ((eq onoff 'on)
  13364. (setq res t)
  13365. (or (member tag current) (push tag current)))
  13366. ((eq onoff 'off)
  13367. (or (not (member tag current)) (setq current (delete tag current))))
  13368. (t (if (member tag current)
  13369. (setq current (delete tag current))
  13370. (setq res t)
  13371. (push tag current))))
  13372. (end-of-line 1)
  13373. (if current
  13374. (progn
  13375. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13376. (org-set-tags nil t))
  13377. (delete-horizontal-space))
  13378. (run-hooks 'org-after-tags-change-hook))
  13379. res))
  13380. (defun org--align-tags-here (to-col)
  13381. "Align tags on the current headline to TO-COL.
  13382. Assume point is on a headline."
  13383. (let ((pos (point)))
  13384. (beginning-of-line)
  13385. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13386. (>= pos (match-beginning 2)))
  13387. ;; No tags or point within tags: do not align.
  13388. (goto-char pos)
  13389. (goto-char (match-beginning 1))
  13390. (let ((shift (max (- (if (>= to-col 0) to-col
  13391. (- (abs to-col) (string-width (match-string 2))))
  13392. (current-column))
  13393. 1)))
  13394. (replace-match (make-string shift ?\s) nil nil nil 1)
  13395. ;; Preserve initial position, if possible. In any case, stop
  13396. ;; before tags.
  13397. (when (< pos (point)) (goto-char pos))))))
  13398. (defun org-set-tags-command (&optional arg just-align)
  13399. "Call the set-tags command for the current entry."
  13400. (interactive "P")
  13401. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13402. (org-set-tags arg just-align)
  13403. (save-excursion
  13404. (unless (and (org-region-active-p)
  13405. org-loop-over-headlines-in-active-region)
  13406. (org-back-to-heading t))
  13407. (org-set-tags arg just-align))))
  13408. (defun org-set-tags-to (data)
  13409. "Set the tags of the current entry to DATA, replacing the current tags.
  13410. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13411. If DATA is nil or the empty string, any tags will be removed."
  13412. (interactive "sTags: ")
  13413. (setq data
  13414. (cond
  13415. ((eq data nil) "")
  13416. ((equal data "") "")
  13417. ((stringp data)
  13418. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13419. ":"))
  13420. ((listp data)
  13421. (concat ":" (mapconcat 'identity data ":") ":"))))
  13422. (when data
  13423. (save-excursion
  13424. (org-back-to-heading t)
  13425. (when (let ((case-fold-search nil))
  13426. (looking-at org-complex-heading-regexp))
  13427. (if (match-end 5)
  13428. (progn
  13429. (goto-char (match-beginning 5))
  13430. (insert data)
  13431. (delete-region (point) (point-at-eol))
  13432. (org-set-tags nil 'align))
  13433. (goto-char (point-at-eol))
  13434. (insert " " data)
  13435. (org-set-tags nil 'align)))
  13436. (beginning-of-line 1)
  13437. (when (looking-at ".*?\\([ \t]+\\)$")
  13438. (delete-region (match-beginning 1) (match-end 1))))))
  13439. (defun org-align-all-tags ()
  13440. "Align the tags in all headings."
  13441. (interactive)
  13442. (save-excursion
  13443. (or (ignore-errors (org-back-to-heading t))
  13444. (outline-next-heading))
  13445. (if (org-at-heading-p)
  13446. (org-set-tags t)
  13447. (message "No headings"))))
  13448. (defvar org-indent-indentation-per-level)
  13449. (defun org-set-tags (&optional arg just-align)
  13450. "Set the tags for the current headline.
  13451. With prefix ARG, realign all tags in headings in the current buffer.
  13452. When JUST-ALIGN is non-nil, only align tags."
  13453. (interactive "P")
  13454. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13455. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13456. 'region-start-level
  13457. 'region))
  13458. org-loop-over-headlines-in-active-region)
  13459. (org-map-entries
  13460. ;; We don't use ARG and JUST-ALIGN here because these args
  13461. ;; are not useful when looping over headlines.
  13462. #'org-set-tags
  13463. org-loop-over-headlines-in-active-region
  13464. cl
  13465. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13466. (let ((org-setting-tags t))
  13467. (if arg
  13468. (save-excursion
  13469. (goto-char (point-min))
  13470. (while (re-search-forward org-outline-regexp-bol nil t)
  13471. (org-set-tags nil t)
  13472. (end-of-line))
  13473. (message "All tags realigned to column %d" org-tags-column))
  13474. (let* ((current (org-get-tags-string))
  13475. (tags
  13476. (if just-align current
  13477. ;; Get a new set of tags from the user.
  13478. (save-excursion
  13479. (let* ((seen)
  13480. (table
  13481. (setq
  13482. org-last-tags-completion-table
  13483. ;; Uniquify tags in alists, yet preserve
  13484. ;; structure (i.e., keywords).
  13485. (delq nil
  13486. (mapcar
  13487. (lambda (pair)
  13488. (let ((head (car pair)))
  13489. (cond ((symbolp head) pair)
  13490. ((member head seen) nil)
  13491. (t (push head seen)
  13492. pair))))
  13493. (append
  13494. (or org-current-tag-alist
  13495. (org-get-buffer-tags))
  13496. (and
  13497. org-complete-tags-always-offer-all-agenda-tags
  13498. (org-global-tags-completion-table
  13499. (org-agenda-files))))))))
  13500. (current-tags (org-split-string current ":"))
  13501. (inherited-tags
  13502. (nreverse (nthcdr (length current-tags)
  13503. (nreverse (org-get-tags-at))))))
  13504. (replace-regexp-in-string
  13505. "\\([-+&]+\\|,\\)"
  13506. ":"
  13507. (if (or (eq t org-use-fast-tag-selection)
  13508. (and org-use-fast-tag-selection
  13509. (delq nil (mapcar #'cdr table))))
  13510. (org-fast-tag-selection
  13511. current-tags inherited-tags table
  13512. (and org-fast-tag-selection-include-todo
  13513. org-todo-key-alist))
  13514. (let ((org-add-colon-after-tag-completion
  13515. (< 1 (length table))))
  13516. (org-trim
  13517. (completing-read
  13518. "Tags: "
  13519. #'org-tags-completion-function
  13520. nil nil current 'org-tags-history))))))))))
  13521. (when org-tags-sort-function
  13522. (setq tags
  13523. (mapconcat
  13524. #'identity
  13525. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13526. org-tags-sort-function)
  13527. ":")))
  13528. (if (or (string= ":" tags)
  13529. (string= "::" tags))
  13530. (setq tags ""))
  13531. (if (not (org-string-nw-p tags)) (setq tags "")
  13532. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13533. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13534. ;; Insert new tags at the correct column.
  13535. (unless (equal current tags)
  13536. (save-excursion
  13537. (beginning-of-line)
  13538. (let ((case-fold-search nil))
  13539. (looking-at org-complex-heading-regexp))
  13540. ;; Remove current tags, if any.
  13541. (when (match-end 5) (replace-match "" nil nil nil 5))
  13542. ;; Insert new tags, if any. Otherwise, remove trailing
  13543. ;; white spaces.
  13544. (end-of-line)
  13545. (if (not (equal tags ""))
  13546. ;; When text is being inserted on an invisible
  13547. ;; region boundary, it can be inadvertently sucked
  13548. ;; into invisibility.
  13549. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13550. (skip-chars-backward " \t")
  13551. (delete-region (point) (line-end-position)))))
  13552. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13553. ;; is on.
  13554. (unless (equal tags "")
  13555. (let* ((level (save-excursion
  13556. (beginning-of-line)
  13557. (skip-chars-forward "\\*")))
  13558. (offset (if (bound-and-true-p org-indent-mode)
  13559. (* (1- org-indent-indentation-per-level)
  13560. (1- level))
  13561. 0))
  13562. (tags-column
  13563. (+ org-tags-column
  13564. (if (> org-tags-column 0) (- offset) offset))))
  13565. (org--align-tags-here tags-column))))
  13566. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13567. (defun org-change-tag-in-region (beg end tag off)
  13568. "Add or remove TAG for each entry in the region.
  13569. This works in the agenda, and also in an Org buffer."
  13570. (interactive
  13571. (list (region-beginning) (region-end)
  13572. (let ((org-last-tags-completion-table
  13573. (if (derived-mode-p 'org-mode)
  13574. (org-uniquify
  13575. (delq nil (append (org-get-buffer-tags)
  13576. (org-global-tags-completion-table))))
  13577. (org-global-tags-completion-table))))
  13578. (completing-read
  13579. "Tag: " 'org-tags-completion-function nil nil nil
  13580. 'org-tags-history))
  13581. (progn
  13582. (message "[s]et or [r]emove? ")
  13583. (equal (read-char-exclusive) ?r))))
  13584. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13585. (let ((agendap (equal major-mode 'org-agenda-mode))
  13586. l1 l2 m buf pos newhead (cnt 0))
  13587. (goto-char end)
  13588. (setq l2 (1- (org-current-line)))
  13589. (goto-char beg)
  13590. (setq l1 (org-current-line))
  13591. (cl-loop for l from l1 to l2 do
  13592. (org-goto-line l)
  13593. (setq m (get-text-property (point) 'org-hd-marker))
  13594. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13595. (and agendap m))
  13596. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13597. pos (if agendap m (point)))
  13598. (with-current-buffer buf
  13599. (save-excursion
  13600. (save-restriction
  13601. (goto-char pos)
  13602. (setq cnt (1+ cnt))
  13603. (org-toggle-tag tag (if off 'off 'on))
  13604. (setq newhead (org-get-heading)))))
  13605. (and agendap (org-agenda-change-all-lines newhead m))))
  13606. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13607. (defun org-tags-completion-function (string _predicate &optional flag)
  13608. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13609. (confirm (lambda (x) (stringp (car x)))))
  13610. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13611. (setq s1 (match-string 1 string)
  13612. s2 (match-string 2 string))
  13613. (setq s1 "" s2 string))
  13614. (cond
  13615. ((eq flag nil)
  13616. ;; try completion
  13617. (setq rtn (try-completion s2 ctable confirm))
  13618. (when (stringp rtn)
  13619. (setq rtn
  13620. (concat s1 s2 (substring rtn (length s2))
  13621. (if (and org-add-colon-after-tag-completion
  13622. (assoc rtn ctable))
  13623. ":" ""))))
  13624. rtn)
  13625. ((eq flag t)
  13626. ;; all-completions
  13627. (all-completions s2 ctable confirm))
  13628. ((eq flag 'lambda)
  13629. ;; exact match?
  13630. (assoc s2 ctable)))))
  13631. (defun org-fast-tag-insert (kwd tags face &optional end)
  13632. "Insert KDW, and the TAGS, the latter with face FACE.
  13633. Also insert END."
  13634. (insert (format "%-12s" (concat kwd ":"))
  13635. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13636. (or end "")))
  13637. (defun org-fast-tag-show-exit (flag)
  13638. (save-excursion
  13639. (org-goto-line 3)
  13640. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13641. (replace-match ""))
  13642. (when flag
  13643. (end-of-line 1)
  13644. (org-move-to-column (- (window-width) 19) t)
  13645. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13646. (defun org-set-current-tags-overlay (current prefix)
  13647. "Add an overlay to CURRENT tag with PREFIX."
  13648. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13649. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13650. (org-overlay-display org-tags-overlay (concat prefix s))))
  13651. (defvar org-last-tag-selection-key nil)
  13652. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13653. "Fast tag selection with single keys.
  13654. CURRENT is the current list of tags in the headline, INHERITED is the
  13655. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13656. possibly with grouping information. TODO-TABLE is a similar table with
  13657. TODO keywords, should these have keys assigned to them.
  13658. If the keys are nil, a-z are automatically assigned.
  13659. Returns the new tags string, or nil to not change the current settings."
  13660. (let* ((fulltable (append table todo-table))
  13661. (maxlen (apply 'max (mapcar
  13662. (lambda (x)
  13663. (if (stringp (car x)) (string-width (car x)) 0))
  13664. fulltable)))
  13665. (buf (current-buffer))
  13666. (expert (eq org-fast-tag-selection-single-key 'expert))
  13667. (buffer-tags nil)
  13668. (fwidth (+ maxlen 3 1 3))
  13669. (ncol (/ (- (window-width) 4) fwidth))
  13670. (i-face 'org-done)
  13671. (c-face 'org-todo)
  13672. tg cnt e c char c1 c2 ntable tbl rtn
  13673. ov-start ov-end ov-prefix
  13674. (exit-after-next org-fast-tag-selection-single-key)
  13675. (done-keywords org-done-keywords)
  13676. groups ingroup intaggroup)
  13677. (save-excursion
  13678. (beginning-of-line 1)
  13679. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13680. (setq ov-start (match-beginning 1)
  13681. ov-end (match-end 1)
  13682. ov-prefix "")
  13683. (setq ov-start (1- (point-at-eol))
  13684. ov-end (1+ ov-start))
  13685. (skip-chars-forward "^\n\r")
  13686. (setq ov-prefix
  13687. (concat
  13688. (buffer-substring (1- (point)) (point))
  13689. (if (> (current-column) org-tags-column)
  13690. " "
  13691. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13692. (move-overlay org-tags-overlay ov-start ov-end)
  13693. (save-window-excursion
  13694. (if expert
  13695. (set-buffer (get-buffer-create " *Org tags*"))
  13696. (delete-other-windows)
  13697. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13698. (org-switch-to-buffer-other-window " *Org tags*"))
  13699. (erase-buffer)
  13700. (setq-local org-done-keywords done-keywords)
  13701. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13702. (org-fast-tag-insert "Current" current c-face "\n\n")
  13703. (org-fast-tag-show-exit exit-after-next)
  13704. (org-set-current-tags-overlay current ov-prefix)
  13705. (setq tbl fulltable char ?a cnt 0)
  13706. (while (setq e (pop tbl))
  13707. (cond
  13708. ((eq (car e) :startgroup)
  13709. (push '() groups) (setq ingroup t)
  13710. (unless (zerop cnt)
  13711. (setq cnt 0)
  13712. (insert "\n"))
  13713. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13714. ((eq (car e) :endgroup)
  13715. (setq ingroup nil cnt 0)
  13716. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13717. ((eq (car e) :startgrouptag)
  13718. (setq intaggroup t)
  13719. (unless (zerop cnt)
  13720. (setq cnt 0)
  13721. (insert "\n"))
  13722. (insert "[ "))
  13723. ((eq (car e) :endgrouptag)
  13724. (setq intaggroup nil cnt 0)
  13725. (insert "]\n"))
  13726. ((equal e '(:newline))
  13727. (unless (zerop cnt)
  13728. (setq cnt 0)
  13729. (insert "\n")
  13730. (setq e (car tbl))
  13731. (while (equal (car tbl) '(:newline))
  13732. (insert "\n")
  13733. (setq tbl (cdr tbl)))))
  13734. ((equal e '(:grouptags)) (insert " : "))
  13735. (t
  13736. (setq tg (copy-sequence (car e)) c2 nil)
  13737. (if (cdr e)
  13738. (setq c (cdr e))
  13739. ;; automatically assign a character.
  13740. (setq c1 (string-to-char
  13741. (downcase (substring
  13742. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13743. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13744. (while (or (rassoc char ntable) (rassoc char table))
  13745. (setq char (1+ char)))
  13746. (setq c2 c1))
  13747. (setq c (or c2 char)))
  13748. (when ingroup (push tg (car groups)))
  13749. (setq tg (org-add-props tg nil 'face
  13750. (cond
  13751. ((not (assoc tg table))
  13752. (org-get-todo-face tg))
  13753. ((member tg current) c-face)
  13754. ((member tg inherited) i-face))))
  13755. (when (equal (caar tbl) :grouptags)
  13756. (org-add-props tg nil 'face 'org-tag-group))
  13757. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13758. (insert "[" c "] " tg (make-string
  13759. (- fwidth 4 (length tg)) ?\ ))
  13760. (push (cons tg c) ntable)
  13761. (when (= (cl-incf cnt) ncol)
  13762. (insert "\n")
  13763. (when (or ingroup intaggroup) (insert " "))
  13764. (setq cnt 0)))))
  13765. (setq ntable (nreverse ntable))
  13766. (insert "\n")
  13767. (goto-char (point-min))
  13768. (unless expert (org-fit-window-to-buffer))
  13769. (setq rtn
  13770. (catch 'exit
  13771. (while t
  13772. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13773. (if (not groups) "no " "")
  13774. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13775. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13776. (setq org-last-tag-selection-key c)
  13777. (cond
  13778. ((= c ?\r) (throw 'exit t))
  13779. ((= c ?!)
  13780. (setq groups (not groups))
  13781. (goto-char (point-min))
  13782. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13783. ((= c ?\C-c)
  13784. (if (not expert)
  13785. (org-fast-tag-show-exit
  13786. (setq exit-after-next (not exit-after-next)))
  13787. (setq expert nil)
  13788. (delete-other-windows)
  13789. (set-window-buffer (split-window-vertically) " *Org tags*")
  13790. (org-switch-to-buffer-other-window " *Org tags*")
  13791. (org-fit-window-to-buffer)))
  13792. ((or (= c ?\C-g)
  13793. (and (= c ?q) (not (rassoc c ntable))))
  13794. (delete-overlay org-tags-overlay)
  13795. (setq quit-flag t))
  13796. ((= c ?\ )
  13797. (setq current nil)
  13798. (when exit-after-next (setq exit-after-next 'now)))
  13799. ((= c ?\t)
  13800. (condition-case nil
  13801. (setq tg (completing-read
  13802. "Tag: "
  13803. (or buffer-tags
  13804. (with-current-buffer buf
  13805. (setq buffer-tags
  13806. (org-get-buffer-tags))))))
  13807. (quit (setq tg "")))
  13808. (when (string-match "\\S-" tg)
  13809. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13810. (if (member tg current)
  13811. (setq current (delete tg current))
  13812. (push tg current)))
  13813. (when exit-after-next (setq exit-after-next 'now)))
  13814. ((setq e (rassoc c todo-table) tg (car e))
  13815. (with-current-buffer buf
  13816. (save-excursion (org-todo tg)))
  13817. (when exit-after-next (setq exit-after-next 'now)))
  13818. ((setq e (rassoc c ntable) tg (car e))
  13819. (if (member tg current)
  13820. (setq current (delete tg current))
  13821. (cl-loop for g in groups do
  13822. (when (member tg g)
  13823. (dolist (x g) (setq current (delete x current)))))
  13824. (push tg current))
  13825. (when exit-after-next (setq exit-after-next 'now))))
  13826. ;; Create a sorted list
  13827. (setq current
  13828. (sort current
  13829. (lambda (a b)
  13830. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13831. (when (eq exit-after-next 'now) (throw 'exit t))
  13832. (goto-char (point-min))
  13833. (beginning-of-line 2)
  13834. (delete-region (point) (point-at-eol))
  13835. (org-fast-tag-insert "Current" current c-face)
  13836. (org-set-current-tags-overlay current ov-prefix)
  13837. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13838. (setq tg (match-string 1))
  13839. (add-text-properties
  13840. (match-beginning 1) (match-end 1)
  13841. (list 'face
  13842. (cond
  13843. ((member tg current) c-face)
  13844. ((member tg inherited) i-face)
  13845. (t (get-text-property (match-beginning 1) 'face))))))
  13846. (goto-char (point-min)))))
  13847. (delete-overlay org-tags-overlay)
  13848. (if rtn
  13849. (mapconcat 'identity current ":")
  13850. nil))))
  13851. (defun org-get-tags-string ()
  13852. "Get the TAGS string in the current headline."
  13853. (unless (org-at-heading-p t)
  13854. (user-error "Not on a heading"))
  13855. (save-excursion
  13856. (beginning-of-line 1)
  13857. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13858. (match-string-no-properties 1)
  13859. "")))
  13860. (defun org-get-tags ()
  13861. "Get the list of tags specified in the current headline."
  13862. (org-split-string (org-get-tags-string) ":"))
  13863. (defun org-get-buffer-tags ()
  13864. "Get a table of all tags used in the buffer, for completion."
  13865. (org-with-wide-buffer
  13866. (goto-char (point-min))
  13867. (let ((tag-re (concat org-outline-regexp-bol
  13868. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13869. tags)
  13870. (while (re-search-forward tag-re nil t)
  13871. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13872. (push tag tags)))
  13873. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13874. ;;;; The mapping API
  13875. (defvar org-agenda-skip-comment-trees)
  13876. (defvar org-agenda-skip-function)
  13877. (defun org-map-entries (func &optional match scope &rest skip)
  13878. "Call FUNC at each headline selected by MATCH in SCOPE.
  13879. FUNC is a function or a lisp form. The function will be called without
  13880. arguments, with the cursor positioned at the beginning of the headline.
  13881. The return values of all calls to the function will be collected and
  13882. returned as a list.
  13883. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13884. does not need to preserve point. After evaluation, the cursor will be
  13885. moved to the end of the line (presumably of the headline of the
  13886. processed entry) and search continues from there. Under some
  13887. circumstances, this may not produce the wanted results. For example,
  13888. if you have removed (e.g. archived) the current (sub)tree it could
  13889. mean that the next entry will be skipped entirely. In such cases, you
  13890. can specify the position from where search should continue by making
  13891. FUNC set the variable `org-map-continue-from' to the desired buffer
  13892. position.
  13893. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13894. Only headlines that are matched by this query will be considered during
  13895. the iteration. When MATCH is nil or t, all headlines will be
  13896. visited by the iteration.
  13897. SCOPE determines the scope of this command. It can be any of:
  13898. nil The current buffer, respecting the restriction if any
  13899. tree The subtree started with the entry at point
  13900. region The entries within the active region, if any
  13901. region-start-level
  13902. The entries within the active region, but only those at
  13903. the same level than the first one.
  13904. file The current buffer, without restriction
  13905. file-with-archives
  13906. The current buffer, and any archives associated with it
  13907. agenda All agenda files
  13908. agenda-with-archives
  13909. All agenda files with any archive files associated with them
  13910. \(file1 file2 ...)
  13911. If this is a list, all files in the list will be scanned
  13912. The remaining args are treated as settings for the skipping facilities of
  13913. the scanner. The following items can be given here:
  13914. archive skip trees with the archive tag
  13915. comment skip trees with the COMMENT keyword
  13916. function or Emacs Lisp form:
  13917. will be used as value for `org-agenda-skip-function', so
  13918. whenever the function returns a position, FUNC will not be
  13919. called for that entry and search will continue from the
  13920. position returned
  13921. If your function needs to retrieve the tags including inherited tags
  13922. at the *current* entry, you can use the value of the variable
  13923. `org-scanner-tags' which will be much faster than getting the value
  13924. with `org-get-tags-at'. If your function gets properties with
  13925. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13926. to t around the call to `org-entry-properties' to get the same speedup.
  13927. Note that if your function moves around to retrieve tags and properties at
  13928. a *different* entry, you cannot use these techniques."
  13929. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13930. (not (org-region-active-p)))
  13931. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13932. (org-agenda-skip-archived-trees (memq 'archive skip))
  13933. (org-agenda-skip-comment-trees (memq 'comment skip))
  13934. (org-agenda-skip-function
  13935. (car (org-delete-all '(comment archive) skip)))
  13936. (org-tags-match-list-sublevels t)
  13937. (start-level (eq scope 'region-start-level))
  13938. matcher res
  13939. org-todo-keywords-for-agenda
  13940. org-done-keywords-for-agenda
  13941. org-todo-keyword-alist-for-agenda
  13942. org-tag-alist-for-agenda
  13943. org--matcher-tags-todo-only)
  13944. (cond
  13945. ((eq match t) (setq matcher t))
  13946. ((eq match nil) (setq matcher t))
  13947. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13948. (save-excursion
  13949. (save-restriction
  13950. (cond ((eq scope 'tree)
  13951. (org-back-to-heading t)
  13952. (org-narrow-to-subtree)
  13953. (setq scope nil))
  13954. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13955. (org-region-active-p))
  13956. ;; If needed, set start-level to a string like "2"
  13957. (when start-level
  13958. (save-excursion
  13959. (goto-char (region-beginning))
  13960. (unless (org-at-heading-p) (outline-next-heading))
  13961. (setq start-level (org-current-level))))
  13962. (narrow-to-region (region-beginning)
  13963. (save-excursion
  13964. (goto-char (region-end))
  13965. (unless (and (bolp) (org-at-heading-p))
  13966. (outline-next-heading))
  13967. (point)))
  13968. (setq scope nil)))
  13969. (if (not scope)
  13970. (progn
  13971. (org-agenda-prepare-buffers
  13972. (and buffer-file-name (list buffer-file-name)))
  13973. (setq res
  13974. (org-scan-tags
  13975. func matcher org--matcher-tags-todo-only start-level)))
  13976. ;; Get the right scope
  13977. (cond
  13978. ((and scope (listp scope) (symbolp (car scope)))
  13979. (setq scope (eval scope)))
  13980. ((eq scope 'agenda)
  13981. (setq scope (org-agenda-files t)))
  13982. ((eq scope 'agenda-with-archives)
  13983. (setq scope (org-agenda-files t))
  13984. (setq scope (org-add-archive-files scope)))
  13985. ((eq scope 'file)
  13986. (setq scope (and buffer-file-name (list buffer-file-name))))
  13987. ((eq scope 'file-with-archives)
  13988. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13989. (org-agenda-prepare-buffers scope)
  13990. (dolist (file scope)
  13991. (with-current-buffer (org-find-base-buffer-visiting file)
  13992. (org-with-wide-buffer
  13993. (goto-char (point-min))
  13994. (setq res
  13995. (append
  13996. res
  13997. (org-scan-tags
  13998. func matcher org--matcher-tags-todo-only)))))))))
  13999. res)))
  14000. ;;; Properties API
  14001. (defconst org-special-properties
  14002. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14003. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14004. "The special properties valid in Org mode.
  14005. These are properties that are not defined in the property drawer,
  14006. but in some other way.")
  14007. (defconst org-default-properties
  14008. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14009. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14010. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14011. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14012. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14013. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14014. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14015. "Some properties that are used by Org mode for various purposes.
  14016. Being in this list makes sure that they are offered for completion.")
  14017. (defun org--valid-property-p (property)
  14018. "Non nil when string PROPERTY is a valid property name."
  14019. (not
  14020. (or (equal property "")
  14021. (string-match-p "\\s-" property))))
  14022. (defun org--update-property-plist (key val props)
  14023. "Associate KEY to VAL in alist PROPS.
  14024. Modifications are made by side-effect. Return new alist."
  14025. (let* ((appending (string= (substring key -1) "+"))
  14026. (key (if appending (substring key 0 -1) key))
  14027. (old (assoc-string key props t)))
  14028. (if (not old) (cons (cons key val) props)
  14029. (setcdr old (if appending (concat (cdr old) " " val) val))
  14030. props)))
  14031. (defun org-get-property-block (&optional beg force)
  14032. "Return the (beg . end) range of the body of the property drawer.
  14033. BEG is the beginning of the current subtree, or of the part
  14034. before the first headline. If it is not given, it will be found.
  14035. If the drawer does not exist, create it if FORCE is non-nil, or
  14036. return nil."
  14037. (org-with-wide-buffer
  14038. (when beg (goto-char beg))
  14039. (unless (org-before-first-heading-p)
  14040. (let ((beg (cond (beg)
  14041. ((or (not (featurep 'org-inlinetask))
  14042. (org-inlinetask-in-task-p))
  14043. (org-back-to-heading t))
  14044. (t (org-with-limited-levels (org-back-to-heading t))))))
  14045. (forward-line)
  14046. (when (looking-at-p org-planning-line-re) (forward-line))
  14047. (cond ((looking-at org-property-drawer-re)
  14048. (forward-line)
  14049. (cons (point) (progn (goto-char (match-end 0))
  14050. (line-beginning-position))))
  14051. (force
  14052. (goto-char beg)
  14053. (org-insert-property-drawer)
  14054. (let ((pos (save-excursion (search-forward ":END:")
  14055. (line-beginning-position))))
  14056. (cons pos pos))))))))
  14057. (defun org-at-property-p ()
  14058. "Non-nil when point is inside a property drawer.
  14059. See `org-property-re' for match data, if applicable."
  14060. (save-excursion
  14061. (beginning-of-line)
  14062. (and (looking-at org-property-re)
  14063. (let ((property-drawer (save-match-data (org-get-property-block))))
  14064. (and property-drawer
  14065. (>= (point) (car property-drawer))
  14066. (< (point) (cdr property-drawer)))))))
  14067. (defun org-property-action ()
  14068. "Do an action on properties."
  14069. (interactive)
  14070. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14071. (let ((c (read-char-exclusive)))
  14072. (cl-case c
  14073. (?s (call-interactively #'org-set-property))
  14074. (?d (call-interactively #'org-delete-property))
  14075. (?D (call-interactively #'org-delete-property-globally))
  14076. (?c (call-interactively #'org-compute-property-at-point))
  14077. (otherwise (user-error "No such property action %c" c)))))
  14078. (defun org-inc-effort ()
  14079. "Increment the value of the effort property in the current entry."
  14080. (interactive)
  14081. (org-set-effort nil t))
  14082. (defvar org-clock-effort) ; Defined in org-clock.el.
  14083. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14084. (defun org-set-effort (&optional value increment)
  14085. "Set the effort property of the current entry.
  14086. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14087. 10th allowed value.
  14088. When INCREMENT is non-nil, set the property to the next allowed value."
  14089. (interactive "P")
  14090. (when (equal value 0) (setq value 10))
  14091. (let* ((completion-ignore-case t)
  14092. (prop org-effort-property)
  14093. (cur (org-entry-get nil prop))
  14094. (allowed (org-property-get-allowed-values nil prop 'table))
  14095. (existing (mapcar 'list (org-property-values prop)))
  14096. (heading (nth 4 (org-heading-components)))
  14097. rpl
  14098. (val (cond
  14099. ((stringp value) value)
  14100. ((and allowed (integerp value))
  14101. (or (car (nth (1- value) allowed))
  14102. (car (org-last allowed))))
  14103. ((and allowed increment)
  14104. (or (cl-caadr (member (list cur) allowed))
  14105. (user-error "Allowed effort values are not set")))
  14106. (allowed
  14107. (message "Select 1-9,0, [RET%s]: %s"
  14108. (if cur (concat "=" cur) "")
  14109. (mapconcat 'car allowed " "))
  14110. (setq rpl (read-char-exclusive))
  14111. (if (equal rpl ?\r)
  14112. cur
  14113. (setq rpl (- rpl ?0))
  14114. (when (equal rpl 0) (setq rpl 10))
  14115. (if (and (> rpl 0) (<= rpl (length allowed)))
  14116. (car (nth (1- rpl) allowed))
  14117. (org-completing-read "Effort: " allowed nil))))
  14118. (t
  14119. (org-completing-read
  14120. (concat "Effort" (and cur (string-match "\\S-" cur)
  14121. (concat " [" cur "]"))
  14122. ": ")
  14123. existing nil nil "" nil cur)))))
  14124. (unless (equal (org-entry-get nil prop) val)
  14125. (org-entry-put nil prop val))
  14126. (org-refresh-property
  14127. '((effort . identity)
  14128. (effort-minutes . org-duration-to-minutes))
  14129. val)
  14130. (when (equal heading (bound-and-true-p org-clock-current-task))
  14131. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14132. (org-clock-update-mode-line))
  14133. (message "%s is now %s" prop val)))
  14134. (defun org-entry-properties (&optional pom which)
  14135. "Get all properties of the current entry.
  14136. When POM is a buffer position, get all properties from the entry
  14137. there instead.
  14138. This includes the TODO keyword, the tags, time strings for
  14139. deadline, scheduled, and clocking, and any additional properties
  14140. defined in the entry.
  14141. If WHICH is nil or `all', get all properties. If WHICH is
  14142. `special' or `standard', only get that subclass. If WHICH is
  14143. a string, only get that property.
  14144. Return value is an alist. Keys are properties, as upcased
  14145. strings."
  14146. (org-with-point-at pom
  14147. (when (and (derived-mode-p 'org-mode)
  14148. (ignore-errors (org-back-to-heading t)))
  14149. (catch 'exit
  14150. (let* ((beg (point))
  14151. (specific (and (stringp which) (upcase which)))
  14152. (which (cond ((not specific) which)
  14153. ((member specific org-special-properties) 'special)
  14154. (t 'standard)))
  14155. props)
  14156. ;; Get the special properties, like TODO and TAGS.
  14157. (when (memq which '(nil all special))
  14158. (when (or (not specific) (string= specific "CLOCKSUM"))
  14159. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14160. (when clocksum
  14161. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14162. props)))
  14163. (when specific (throw 'exit props)))
  14164. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14165. (let ((clocksumt (get-text-property (point)
  14166. :org-clock-minutes-today)))
  14167. (when clocksumt
  14168. (push (cons "CLOCKSUM_T"
  14169. (org-duration-from-minutes clocksumt))
  14170. props)))
  14171. (when specific (throw 'exit props)))
  14172. (when (or (not specific) (string= specific "ITEM"))
  14173. (let ((case-fold-search nil))
  14174. (when (looking-at org-complex-heading-regexp)
  14175. (push (cons "ITEM"
  14176. (let ((title (match-string-no-properties 4)))
  14177. (if (org-string-nw-p title)
  14178. (org-remove-tabs title)
  14179. "")))
  14180. props)))
  14181. (when specific (throw 'exit props)))
  14182. (when (or (not specific) (string= specific "TODO"))
  14183. (let ((case-fold-search nil))
  14184. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14185. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14186. (when specific (throw 'exit props)))
  14187. (when (or (not specific) (string= specific "PRIORITY"))
  14188. (push (cons "PRIORITY"
  14189. (if (looking-at org-priority-regexp)
  14190. (match-string-no-properties 2)
  14191. (char-to-string org-default-priority)))
  14192. props)
  14193. (when specific (throw 'exit props)))
  14194. (when (or (not specific) (string= specific "FILE"))
  14195. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14196. props)
  14197. (when specific (throw 'exit props)))
  14198. (when (or (not specific) (string= specific "TAGS"))
  14199. (let ((value (org-string-nw-p (org-get-tags-string))))
  14200. (when value (push (cons "TAGS" value) props)))
  14201. (when specific (throw 'exit props)))
  14202. (when (or (not specific) (string= specific "ALLTAGS"))
  14203. (let ((value (org-get-tags-at)))
  14204. (when value
  14205. (push (cons "ALLTAGS"
  14206. (format ":%s:" (mapconcat #'identity value ":")))
  14207. props)))
  14208. (when specific (throw 'exit props)))
  14209. (when (or (not specific) (string= specific "BLOCKED"))
  14210. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14211. (when specific (throw 'exit props)))
  14212. (when (or (not specific)
  14213. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14214. (forward-line)
  14215. (when (looking-at-p org-planning-line-re)
  14216. (end-of-line)
  14217. (let ((bol (line-beginning-position))
  14218. ;; Backward compatibility: time keywords used to
  14219. ;; be configurable (before 8.3). Make sure we
  14220. ;; get the correct keyword.
  14221. (key-assoc `(("CLOSED" . ,org-closed-string)
  14222. ("DEADLINE" . ,org-deadline-string)
  14223. ("SCHEDULED" . ,org-scheduled-string))))
  14224. (dolist (pair (if specific (list (assoc specific key-assoc))
  14225. key-assoc))
  14226. (save-excursion
  14227. (when (search-backward (cdr pair) bol t)
  14228. (goto-char (match-end 0))
  14229. (skip-chars-forward " \t")
  14230. (and (looking-at org-ts-regexp-both)
  14231. (push (cons (car pair)
  14232. (match-string-no-properties 0))
  14233. props)))))))
  14234. (when specific (throw 'exit props)))
  14235. (when (or (not specific)
  14236. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14237. (let ((find-ts
  14238. (lambda (end ts)
  14239. ;; Fix next time-stamp before END. TS is the
  14240. ;; list of time-stamps found so far.
  14241. (let ((ts ts)
  14242. (regexp (cond
  14243. ((string= specific "TIMESTAMP")
  14244. org-ts-regexp)
  14245. ((string= specific "TIMESTAMP_IA")
  14246. org-ts-regexp-inactive)
  14247. ((assoc "TIMESTAMP_IA" ts)
  14248. org-ts-regexp)
  14249. ((assoc "TIMESTAMP" ts)
  14250. org-ts-regexp-inactive)
  14251. (t org-ts-regexp-both))))
  14252. (catch 'next
  14253. (while (re-search-forward regexp end t)
  14254. (backward-char)
  14255. (let ((object (org-element-context)))
  14256. ;; Accept to match timestamps in node
  14257. ;; properties, too.
  14258. (when (memq (org-element-type object)
  14259. '(node-property timestamp))
  14260. (let ((type
  14261. (org-element-property :type object)))
  14262. (cond
  14263. ((and (memq type '(active active-range))
  14264. (not (equal specific "TIMESTAMP_IA")))
  14265. (unless (assoc "TIMESTAMP" ts)
  14266. (push (cons "TIMESTAMP"
  14267. (org-element-property
  14268. :raw-value object))
  14269. ts)
  14270. (when specific (throw 'exit ts))))
  14271. ((and (memq type '(inactive inactive-range))
  14272. (not (string= specific "TIMESTAMP")))
  14273. (unless (assoc "TIMESTAMP_IA" ts)
  14274. (push (cons "TIMESTAMP_IA"
  14275. (org-element-property
  14276. :raw-value object))
  14277. ts)
  14278. (when specific (throw 'exit ts))))))
  14279. ;; Both timestamp types are found,
  14280. ;; move to next part.
  14281. (when (= (length ts) 2) (throw 'next ts)))))
  14282. ts)))))
  14283. (goto-char beg)
  14284. ;; First look for timestamps within headline.
  14285. (let ((ts (funcall find-ts (line-end-position) nil)))
  14286. (if (= (length ts) 2) (setq props (nconc ts props))
  14287. ;; Then find timestamps in the section, skipping
  14288. ;; planning line.
  14289. (let ((end (save-excursion (outline-next-heading))))
  14290. (forward-line)
  14291. (when (looking-at-p org-planning-line-re) (forward-line))
  14292. (setq props (nconc (funcall find-ts end ts) props))))))))
  14293. ;; Get the standard properties, like :PROP:.
  14294. (when (memq which '(nil all standard))
  14295. ;; If we are looking after a specific property, delegate
  14296. ;; to `org-entry-get', which is faster. However, make an
  14297. ;; exception for "CATEGORY", since it can be also set
  14298. ;; through keywords (i.e. #+CATEGORY).
  14299. (if (and specific (not (equal specific "CATEGORY")))
  14300. (let ((value (org-entry-get beg specific nil t)))
  14301. (throw 'exit (and value (list (cons specific value)))))
  14302. (let ((range (org-get-property-block beg)))
  14303. (when range
  14304. (let ((end (cdr range)) seen-base)
  14305. (goto-char (car range))
  14306. ;; Unlike to `org--update-property-plist', we
  14307. ;; handle the case where base values is found
  14308. ;; after its extension. We also forbid standard
  14309. ;; properties to be named as special properties.
  14310. (while (re-search-forward org-property-re end t)
  14311. (let* ((key (upcase (match-string-no-properties 2)))
  14312. (extendp (string-match-p "\\+\\'" key))
  14313. (key-base (if extendp (substring key 0 -1) key))
  14314. (value (match-string-no-properties 3)))
  14315. (cond
  14316. ((member-ignore-case key-base org-special-properties))
  14317. (extendp
  14318. (setq props
  14319. (org--update-property-plist key value props)))
  14320. ((member key seen-base))
  14321. (t (push key seen-base)
  14322. (let ((p (assoc-string key props t)))
  14323. (if p (setcdr p (concat value " " (cdr p)))
  14324. (push (cons key value) props))))))))))))
  14325. (unless (assoc "CATEGORY" props)
  14326. (push (cons "CATEGORY" (org-get-category beg)) props)
  14327. (when (string= specific "CATEGORY") (throw 'exit props)))
  14328. ;; Return value.
  14329. props)))))
  14330. (defun org--property-local-values (property literal-nil)
  14331. "Return value for PROPERTY in current entry.
  14332. Value is a list whose car is the base value for PROPERTY and cdr
  14333. a list of accumulated values. Return nil if neither is found in
  14334. the entry. Also return nil when PROPERTY is set to \"nil\",
  14335. unless LITERAL-NIL is non-nil."
  14336. (let ((range (org-get-property-block)))
  14337. (when range
  14338. (goto-char (car range))
  14339. (let* ((case-fold-search t)
  14340. (end (cdr range))
  14341. (value
  14342. ;; Base value.
  14343. (save-excursion
  14344. (let ((v (and (re-search-forward
  14345. (org-re-property property nil t) end t)
  14346. (match-string-no-properties 3))))
  14347. (list (if literal-nil v (org-not-nil v)))))))
  14348. ;; Find additional values.
  14349. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14350. (while (re-search-forward property+ end t)
  14351. (push (match-string-no-properties 3) value)))
  14352. ;; Return final values.
  14353. (and (not (equal value '(nil))) (nreverse value))))))
  14354. (defun org--property-global-value (property literal-nil)
  14355. "Return value for PROPERTY in current buffer.
  14356. Return value is a string. Return nil if property is not set
  14357. globally. Also return nil when PROPERTY is set to \"nil\",
  14358. unless LITERAL-NIL is non-nil."
  14359. (let ((global
  14360. (cdr (or (assoc-string property org-file-properties t)
  14361. (assoc-string property org-global-properties t)
  14362. (assoc-string property org-global-properties-fixed t)))))
  14363. (if literal-nil global (org-not-nil global))))
  14364. (defun org-entry-get (pom property &optional inherit literal-nil)
  14365. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14366. If INHERIT is non-nil and the entry does not have the property,
  14367. then also check higher levels of the hierarchy. If INHERIT is
  14368. the symbol `selective', use inheritance only if the setting in
  14369. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14370. If the property is present but empty, the return value is the
  14371. empty string. If the property is not present at all, nil is
  14372. returned. In any other case, return the value as a string.
  14373. Search is case-insensitive.
  14374. If LITERAL-NIL is set, return the string value \"nil\" as
  14375. a string, do not interpret it as the list atom nil. This is used
  14376. for inheritance when a \"nil\" value can supersede a non-nil
  14377. value higher up the hierarchy."
  14378. (org-with-point-at pom
  14379. (cond
  14380. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14381. ;; We need a special property. Use `org-entry-properties' to
  14382. ;; retrieve it, but specify the wanted property.
  14383. (cdr (assoc-string property (org-entry-properties nil property))))
  14384. ((and inherit
  14385. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14386. (org-entry-get-with-inheritance property literal-nil))
  14387. (t
  14388. (let* ((local (org--property-local-values property literal-nil))
  14389. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14390. (if literal-nil value (org-not-nil value)))))))
  14391. (defun org-property-or-variable-value (var &optional inherit)
  14392. "Check if there is a property fixing the value of VAR.
  14393. If yes, return this value. If not, return the current value of the variable."
  14394. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14395. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14396. (read prop)
  14397. (symbol-value var))))
  14398. (defun org-entry-delete (pom property)
  14399. "Delete PROPERTY from entry at point-or-marker POM.
  14400. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14401. non-nil when a property was removed."
  14402. (org-with-point-at pom
  14403. (pcase (org-get-property-block)
  14404. (`(,begin . ,origin)
  14405. (let* ((end (copy-marker origin))
  14406. (re (org-re-property
  14407. (concat (regexp-quote property) "\\+?") t t)))
  14408. (goto-char begin)
  14409. (while (re-search-forward re end t)
  14410. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14411. ;; If drawer is empty, remove it altogether.
  14412. (when (= begin end)
  14413. (delete-region (line-beginning-position 0)
  14414. (line-beginning-position 2)))
  14415. ;; Return non-nil if some property was removed.
  14416. (prog1 (/= end origin) (set-marker end nil))))
  14417. (_ nil))))
  14418. ;; Multi-values properties are properties that contain multiple values
  14419. ;; These values are assumed to be single words, separated by whitespace.
  14420. (defun org-entry-add-to-multivalued-property (pom property value)
  14421. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14422. (let* ((old (org-entry-get pom property))
  14423. (values (and old (org-split-string old "[ \t]"))))
  14424. (setq value (org-entry-protect-space value))
  14425. (unless (member value values)
  14426. (setq values (append values (list value)))
  14427. (org-entry-put pom property
  14428. (mapconcat 'identity values " ")))))
  14429. (defun org-entry-remove-from-multivalued-property (pom property value)
  14430. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14431. (let* ((old (org-entry-get pom property))
  14432. (values (and old (org-split-string old "[ \t]"))))
  14433. (setq value (org-entry-protect-space value))
  14434. (when (member value values)
  14435. (setq values (delete value values))
  14436. (org-entry-put pom property
  14437. (mapconcat 'identity values " ")))))
  14438. (defun org-entry-member-in-multivalued-property (pom property value)
  14439. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14440. (let* ((old (org-entry-get pom property))
  14441. (values (and old (org-split-string old "[ \t]"))))
  14442. (setq value (org-entry-protect-space value))
  14443. (member value values)))
  14444. (defun org-entry-get-multivalued-property (pom property)
  14445. "Return a list of values in a multivalued property."
  14446. (let* ((value (org-entry-get pom property))
  14447. (values (and value (org-split-string value "[ \t]"))))
  14448. (mapcar 'org-entry-restore-space values)))
  14449. (defun org-entry-put-multivalued-property (pom property &rest values)
  14450. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14451. VALUES should be a list of strings. Spaces will be protected."
  14452. (org-entry-put pom property
  14453. (mapconcat 'org-entry-protect-space values " "))
  14454. (let* ((value (org-entry-get pom property))
  14455. (values (and value (org-split-string value "[ \t]"))))
  14456. (mapcar 'org-entry-restore-space values)))
  14457. (defun org-entry-protect-space (s)
  14458. "Protect spaces and newline in string S."
  14459. (while (string-match " " s)
  14460. (setq s (replace-match "%20" t t s)))
  14461. (while (string-match "\n" s)
  14462. (setq s (replace-match "%0A" t t s)))
  14463. s)
  14464. (defun org-entry-restore-space (s)
  14465. "Restore spaces and newline in string S."
  14466. (while (string-match "%20" s)
  14467. (setq s (replace-match " " t t s)))
  14468. (while (string-match "%0A" s)
  14469. (setq s (replace-match "\n" t t s)))
  14470. s)
  14471. (defvar org-entry-property-inherited-from (make-marker)
  14472. "Marker pointing to the entry from where a property was inherited.
  14473. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14474. location of the entry where the inheritance search matched. If there was
  14475. no match, the marker will point nowhere.
  14476. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14477. is set.")
  14478. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14479. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14480. The search will stop at the first ancestor which has the property defined.
  14481. If the value found is \"nil\", return nil to show that the property
  14482. should be considered as undefined (this is the meaning of nil here).
  14483. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14484. (move-marker org-entry-property-inherited-from nil)
  14485. (org-with-wide-buffer
  14486. (let (value)
  14487. (catch 'exit
  14488. (while t
  14489. (let ((v (org--property-local-values property literal-nil)))
  14490. (when v
  14491. (setq value
  14492. (concat (mapconcat #'identity (delq nil v) " ")
  14493. (and value " ")
  14494. value)))
  14495. (cond
  14496. ((car v)
  14497. (org-back-to-heading t)
  14498. (move-marker org-entry-property-inherited-from (point))
  14499. (throw 'exit nil))
  14500. ((org-up-heading-safe))
  14501. (t
  14502. (let ((global (org--property-global-value property literal-nil)))
  14503. (cond ((not global))
  14504. (value (setq value (concat global " " value)))
  14505. (t (setq value global))))
  14506. (throw 'exit nil))))))
  14507. (if literal-nil value (org-not-nil value)))))
  14508. (defvar org-property-changed-functions nil
  14509. "Hook called when the value of a property has changed.
  14510. Each hook function should accept two arguments, the name of the property
  14511. and the new value.")
  14512. (defun org-entry-put (pom property value)
  14513. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14514. If the value is nil, it is converted to the empty string. If it
  14515. is not a string, an error is raised. Also raise an error on
  14516. invalid property names.
  14517. PROPERTY can be any regular property (see
  14518. `org-special-properties'). It can also be \"TODO\",
  14519. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14520. For the last two properties, VALUE may have any of the special
  14521. values \"earlier\" and \"later\". The function then increases or
  14522. decreases scheduled or deadline date by one day."
  14523. (cond ((null value) (setq value ""))
  14524. ((not (stringp value)) (error "Properties values should be strings"))
  14525. ((not (org--valid-property-p property))
  14526. (user-error "Invalid property name: \"%s\"" property)))
  14527. (org-with-point-at pom
  14528. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14529. (org-back-to-heading t)
  14530. (org-with-limited-levels (org-back-to-heading t)))
  14531. (let ((beg (point)))
  14532. (cond
  14533. ((equal property "TODO")
  14534. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14535. ((not (member value org-todo-keywords-1))
  14536. (user-error "\"%s\" is not a valid TODO state" value)))
  14537. (org-todo value)
  14538. (org-set-tags nil 'align))
  14539. ((equal property "PRIORITY")
  14540. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14541. (org-set-tags nil 'align))
  14542. ((equal property "SCHEDULED")
  14543. (forward-line)
  14544. (if (and (looking-at-p org-planning-line-re)
  14545. (re-search-forward
  14546. org-scheduled-time-regexp (line-end-position) t))
  14547. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14548. ((string= value "later") (org-timestamp-change 1 'day))
  14549. ((string= value "") (org-schedule '(4)))
  14550. (t (org-schedule nil value)))
  14551. (if (member value '("earlier" "later" ""))
  14552. (call-interactively #'org-schedule)
  14553. (org-schedule nil value))))
  14554. ((equal property "DEADLINE")
  14555. (forward-line)
  14556. (if (and (looking-at-p org-planning-line-re)
  14557. (re-search-forward
  14558. org-deadline-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-deadline '(4)))
  14562. (t (org-deadline nil value)))
  14563. (if (member value '("earlier" "later" ""))
  14564. (call-interactively #'org-deadline)
  14565. (org-deadline nil value))))
  14566. ((member property org-special-properties)
  14567. (error "The %s property cannot be set with `org-entry-put'" property))
  14568. (t
  14569. (let* ((range (org-get-property-block beg 'force))
  14570. (end (cdr range))
  14571. (case-fold-search t))
  14572. (goto-char (car range))
  14573. (if (re-search-forward (org-re-property property nil t) end t)
  14574. (progn (delete-region (match-beginning 0) (match-end 0))
  14575. (goto-char (match-beginning 0)))
  14576. (goto-char end)
  14577. (insert "\n")
  14578. (backward-char))
  14579. (insert ":" property ":")
  14580. (when value (insert " " value))
  14581. (org-indent-line)))))
  14582. (run-hook-with-args 'org-property-changed-functions property value)))
  14583. (defun org-buffer-property-keys
  14584. (&optional specials defaults columns ignore-malformed)
  14585. "Get all property keys in the current buffer.
  14586. When SPECIALS is non-nil, also list the special properties that
  14587. reflect things like tags and TODO state.
  14588. When DEFAULTS is non-nil, also include properties that has
  14589. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14590. DESCRIPTION, LOCATION, and LOGGING and others.
  14591. When COLUMNS in non-nil, also include property names given in
  14592. COLUMN formats in the current buffer.
  14593. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14594. automatically performed, such drawers will be silently ignored."
  14595. (let ((case-fold-search t)
  14596. (props (append
  14597. (and specials org-special-properties)
  14598. (and defaults (cons org-effort-property org-default-properties))
  14599. nil)))
  14600. (org-with-wide-buffer
  14601. (goto-char (point-min))
  14602. (while (re-search-forward org-property-start-re nil t)
  14603. (let ((range (org-get-property-block)))
  14604. (catch 'skip
  14605. (unless range
  14606. (when (and (not ignore-malformed)
  14607. (not (org-before-first-heading-p))
  14608. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14609. (line-beginning-position))))
  14610. (org-get-property-block nil t))
  14611. (throw 'skip nil))
  14612. (goto-char (car range))
  14613. (let ((begin (car range))
  14614. (end (cdr range)))
  14615. ;; Make sure that found property block is not located
  14616. ;; before current point, as it would generate an infloop.
  14617. ;; It can happen, for example, in the following
  14618. ;; situation:
  14619. ;;
  14620. ;; * Headline
  14621. ;; :PROPERTIES:
  14622. ;; ...
  14623. ;; :END:
  14624. ;; *************** Inlinetask
  14625. ;; #+BEGIN_EXAMPLE
  14626. ;; :PROPERTIES:
  14627. ;; #+END_EXAMPLE
  14628. ;;
  14629. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14630. (while (< (point) end)
  14631. (let ((p (progn (looking-at org-property-re)
  14632. (match-string-no-properties 2))))
  14633. ;; Only add true property name, not extension symbol.
  14634. (push (if (not (string-match-p "\\+\\'" p)) p
  14635. (substring p 0 -1))
  14636. props))
  14637. (forward-line))))
  14638. (outline-next-heading)))
  14639. (when columns
  14640. (goto-char (point-min))
  14641. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14642. (let ((element (org-element-at-point)))
  14643. (when (memq (org-element-type element) '(keyword node-property))
  14644. (let ((value (org-element-property :value element))
  14645. (start 0))
  14646. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14647. (setq start (match-end 0))
  14648. (let ((p (match-string-no-properties 1 value)))
  14649. (unless (member-ignore-case p org-special-properties)
  14650. (push p props))))))))))
  14651. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14652. (defun org-property-values (key)
  14653. "List all non-nil values of property KEY in current buffer."
  14654. (org-with-wide-buffer
  14655. (goto-char (point-min))
  14656. (let ((case-fold-search t)
  14657. (re (org-re-property key))
  14658. values)
  14659. (while (re-search-forward re nil t)
  14660. (push (org-entry-get (point) key) values))
  14661. (delete-dups values))))
  14662. (defun org-insert-property-drawer ()
  14663. "Insert a property drawer into the current entry."
  14664. (org-with-wide-buffer
  14665. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14666. (org-back-to-heading t)
  14667. (org-with-limited-levels (org-back-to-heading t)))
  14668. (forward-line)
  14669. (when (looking-at-p org-planning-line-re) (forward-line))
  14670. (unless (looking-at-p org-property-drawer-re)
  14671. ;; Make sure we start editing a line from current entry, not from
  14672. ;; next one. It prevents extending text properties or overlays
  14673. ;; belonging to the latter.
  14674. (when (bolp) (backward-char))
  14675. (let ((begin (1+ (point)))
  14676. (inhibit-read-only t))
  14677. (insert "\n:PROPERTIES:\n:END:")
  14678. (when (eobp) (insert "\n"))
  14679. (org-indent-region begin (point))))))
  14680. (defun org-insert-drawer (&optional arg drawer)
  14681. "Insert a drawer at point.
  14682. When optional argument ARG is non-nil, insert a property drawer.
  14683. Optional argument DRAWER, when non-nil, is a string representing
  14684. drawer's name. Otherwise, the user is prompted for a name.
  14685. If a region is active, insert the drawer around that region
  14686. instead.
  14687. Point is left between drawer's boundaries."
  14688. (interactive "P")
  14689. (let* ((drawer (if arg "PROPERTIES"
  14690. (or drawer (read-from-minibuffer "Drawer: ")))))
  14691. (cond
  14692. ;; With C-u, fall back on `org-insert-property-drawer'
  14693. (arg (org-insert-property-drawer))
  14694. ;; Check validity of suggested drawer's name.
  14695. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14696. (user-error "Invalid drawer name"))
  14697. ;; With an active region, insert a drawer at point.
  14698. ((not (org-region-active-p))
  14699. (progn
  14700. (unless (bolp) (insert "\n"))
  14701. (insert (format ":%s:\n\n:END:\n" drawer))
  14702. (forward-line -2)))
  14703. ;; Otherwise, insert the drawer at point
  14704. (t
  14705. (let ((rbeg (region-beginning))
  14706. (rend (copy-marker (region-end))))
  14707. (unwind-protect
  14708. (progn
  14709. (goto-char rbeg)
  14710. (beginning-of-line)
  14711. (when (save-excursion
  14712. (re-search-forward org-outline-regexp-bol rend t))
  14713. (user-error "Drawers cannot contain headlines"))
  14714. ;; Position point at the beginning of the first
  14715. ;; non-blank line in region. Insert drawer's opening
  14716. ;; there, then indent it.
  14717. (org-skip-whitespace)
  14718. (beginning-of-line)
  14719. (insert ":" drawer ":\n")
  14720. (forward-line -1)
  14721. (indent-for-tab-command)
  14722. ;; Move point to the beginning of the first blank line
  14723. ;; after the last non-blank line in region. Insert
  14724. ;; drawer's closing, then indent it.
  14725. (goto-char rend)
  14726. (skip-chars-backward " \r\t\n")
  14727. (insert "\n:END:")
  14728. (deactivate-mark t)
  14729. (indent-for-tab-command)
  14730. (unless (eolp) (insert "\n")))
  14731. ;; Clear marker, whatever the outcome of insertion is.
  14732. (set-marker rend nil)))))))
  14733. (defvar org-property-set-functions-alist nil
  14734. "Property set function alist.
  14735. Each entry should have the following format:
  14736. (PROPERTY . READ-FUNCTION)
  14737. The read function will be called with the same argument as
  14738. `org-completing-read'.")
  14739. (defun org-set-property-function (property)
  14740. "Get the function that should be used to set PROPERTY.
  14741. This is computed according to `org-property-set-functions-alist'."
  14742. (or (cdr (assoc property org-property-set-functions-alist))
  14743. 'org-completing-read))
  14744. (defun org-read-property-value (property)
  14745. "Read PROPERTY value from user."
  14746. (let* ((completion-ignore-case t)
  14747. (allowed (org-property-get-allowed-values nil property 'table))
  14748. (cur (org-entry-get nil property))
  14749. (prompt (concat property " value"
  14750. (if (and cur (string-match "\\S-" cur))
  14751. (concat " [" cur "]") "") ": "))
  14752. (set-function (org-set-property-function property))
  14753. (val (if allowed
  14754. (funcall set-function prompt allowed nil
  14755. (not (get-text-property 0 'org-unrestricted
  14756. (caar allowed))))
  14757. (funcall set-function prompt
  14758. (mapcar 'list (org-property-values property))
  14759. nil nil "" nil cur))))
  14760. (org-trim val)))
  14761. (defvar org-last-set-property nil)
  14762. (defvar org-last-set-property-value nil)
  14763. (defun org-read-property-name ()
  14764. "Read a property name."
  14765. (let ((completion-ignore-case t)
  14766. (default-prop (or (and (org-at-property-p)
  14767. (match-string-no-properties 2))
  14768. org-last-set-property)))
  14769. (org-completing-read
  14770. (concat "Property"
  14771. (if default-prop (concat " [" default-prop "]") "")
  14772. ": ")
  14773. (mapcar #'list (org-buffer-property-keys nil t t))
  14774. nil nil nil nil default-prop)))
  14775. (defun org-set-property-and-value (use-last)
  14776. "Allow to set [PROPERTY]: [value] direction from prompt.
  14777. When use-default, don't even ask, just use the last
  14778. \"[PROPERTY]: [value]\" string from the history."
  14779. (interactive "P")
  14780. (let* ((completion-ignore-case t)
  14781. (pv (or (and use-last org-last-set-property-value)
  14782. (org-completing-read
  14783. "Enter a \"[Property]: [value]\" pair: "
  14784. nil nil nil nil nil
  14785. org-last-set-property-value)))
  14786. prop val)
  14787. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14788. (setq prop (match-string 1 pv)
  14789. val (match-string 2 pv))
  14790. (org-set-property prop val))))
  14791. (defun org-set-property (property value)
  14792. "In the current entry, set PROPERTY to VALUE.
  14793. When called interactively, this will prompt for a property name, offering
  14794. completion on existing and default properties. And then it will prompt
  14795. for a value, offering completion either on allowed values (via an inherited
  14796. xxx_ALL property) or on existing values in other instances of this property
  14797. in the current file.
  14798. Throw an error when trying to set a property with an invalid name."
  14799. (interactive (list nil nil))
  14800. (let ((property (or property (org-read-property-name))))
  14801. ;; `org-entry-put' also makes the following check, but this one
  14802. ;; avoids polluting `org-last-set-property' and
  14803. ;; `org-last-set-property-value' needlessly.
  14804. (unless (org--valid-property-p property)
  14805. (user-error "Invalid property name: \"%s\"" property))
  14806. (let ((value (or value (org-read-property-value property)))
  14807. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14808. (setq org-last-set-property property)
  14809. (setq org-last-set-property-value (concat property ": " value))
  14810. ;; Possibly postprocess the inserted value:
  14811. (when fn (setq value (funcall fn value)))
  14812. (unless (equal (org-entry-get nil property) value)
  14813. (org-entry-put nil property value)))))
  14814. (defun org-find-property (property &optional value)
  14815. "Find first entry in buffer that sets PROPERTY.
  14816. When optional argument VALUE is non-nil, only consider an entry
  14817. if it contains PROPERTY set to this value. If PROPERTY should be
  14818. explicitly set to nil, use string \"nil\" for VALUE.
  14819. Return position where the entry begins, or nil if there is no
  14820. such entry. If narrowing is in effect, only search the visible
  14821. part of the buffer."
  14822. (save-excursion
  14823. (goto-char (point-min))
  14824. (let ((case-fold-search t)
  14825. (re (org-re-property property nil (not value) value)))
  14826. (catch 'exit
  14827. (while (re-search-forward re nil t)
  14828. (when (if value (org-at-property-p)
  14829. (org-entry-get (point) property nil t))
  14830. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14831. (defun org-delete-property (property)
  14832. "In the current entry, delete PROPERTY."
  14833. (interactive
  14834. (let* ((completion-ignore-case t)
  14835. (cat (org-entry-get (point) "CATEGORY"))
  14836. (props0 (org-entry-properties nil 'standard))
  14837. (props (if cat props0
  14838. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14839. (prop (if (< 1 (length props))
  14840. (completing-read "Property: " props nil t)
  14841. (caar props))))
  14842. (list prop)))
  14843. (if (not property)
  14844. (message "No property to delete in this entry")
  14845. (org-entry-delete nil property)
  14846. (message "Property \"%s\" deleted" property)))
  14847. (defun org-delete-property-globally (property)
  14848. "Remove PROPERTY globally, from all entries.
  14849. This function ignores narrowing, if any."
  14850. (interactive
  14851. (let* ((completion-ignore-case t)
  14852. (prop (completing-read
  14853. "Globally remove property: "
  14854. (mapcar #'list (org-buffer-property-keys)))))
  14855. (list prop)))
  14856. (org-with-wide-buffer
  14857. (goto-char (point-min))
  14858. (let ((count 0)
  14859. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14860. (while (re-search-forward re nil t)
  14861. (when (org-entry-delete (point) property) (cl-incf count)))
  14862. (message "Property \"%s\" removed from %d entries" property count))))
  14863. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14864. (defun org-compute-property-at-point ()
  14865. "Compute the property at point.
  14866. This looks for an enclosing column format, extracts the operator and
  14867. then applies it to the property in the column format's scope."
  14868. (interactive)
  14869. (unless (org-at-property-p)
  14870. (user-error "Not at a property"))
  14871. (let ((prop (match-string-no-properties 2)))
  14872. (org-columns-get-format-and-top-level)
  14873. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14874. (user-error "No operator defined for property %s" prop))
  14875. (org-columns-compute prop)))
  14876. (defvar org-property-allowed-value-functions nil
  14877. "Hook for functions supplying allowed values for a specific property.
  14878. The functions must take a single argument, the name of the property, and
  14879. return a flat list of allowed values. If \":ETC\" is one of
  14880. the values, this means that these values are intended as defaults for
  14881. completion, but that other values should be allowed too.
  14882. The functions must return nil if they are not responsible for this
  14883. property.")
  14884. (defun org-property-get-allowed-values (pom property &optional table)
  14885. "Get allowed values for the property PROPERTY.
  14886. When TABLE is non-nil, return an alist that can directly be used for
  14887. completion."
  14888. (let (vals)
  14889. (cond
  14890. ((equal property "TODO")
  14891. (setq vals (org-with-point-at pom
  14892. (append org-todo-keywords-1 '("")))))
  14893. ((equal property "PRIORITY")
  14894. (let ((n org-lowest-priority))
  14895. (while (>= n org-highest-priority)
  14896. (push (char-to-string n) vals)
  14897. (setq n (1- n)))))
  14898. ((equal property "CATEGORY"))
  14899. ((member property org-special-properties))
  14900. ((setq vals (run-hook-with-args-until-success
  14901. 'org-property-allowed-value-functions property)))
  14902. (t
  14903. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14904. (when (and vals (string-match "\\S-" vals))
  14905. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14906. (setq vals (mapcar (lambda (x)
  14907. (cond ((stringp x) x)
  14908. ((numberp x) (number-to-string x))
  14909. ((symbolp x) (symbol-name x))
  14910. (t "???")))
  14911. vals)))))
  14912. (when (member ":ETC" vals)
  14913. (setq vals (remove ":ETC" vals))
  14914. (org-add-props (car vals) '(org-unrestricted t)))
  14915. (if table (mapcar 'list vals) vals)))
  14916. (defun org-property-previous-allowed-value (&optional _previous)
  14917. "Switch to the next allowed value for this property."
  14918. (interactive)
  14919. (org-property-next-allowed-value t))
  14920. (defun org-property-next-allowed-value (&optional previous)
  14921. "Switch to the next allowed value for this property."
  14922. (interactive)
  14923. (unless (org-at-property-p)
  14924. (user-error "Not at a property"))
  14925. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14926. (key (match-string 2))
  14927. (value (match-string 3))
  14928. (allowed (or (org-property-get-allowed-values (point) key)
  14929. (and (member value '("[ ]" "[-]" "[X]"))
  14930. '("[ ]" "[X]"))))
  14931. (heading (save-match-data (nth 4 (org-heading-components))))
  14932. nval)
  14933. (unless allowed
  14934. (user-error "Allowed values for this property have not been defined"))
  14935. (when previous (setq allowed (reverse allowed)))
  14936. (when (member value allowed)
  14937. (setq nval (car (cdr (member value allowed)))))
  14938. (setq nval (or nval (car allowed)))
  14939. (when (equal nval value)
  14940. (user-error "Only one allowed value for this property"))
  14941. (org-at-property-p)
  14942. (replace-match (concat " :" key ": " nval) t t)
  14943. (org-indent-line)
  14944. (beginning-of-line 1)
  14945. (skip-chars-forward " \t")
  14946. (when (equal prop org-effort-property)
  14947. (org-refresh-property
  14948. '((effort . identity)
  14949. (effort-minutes . org-duration-to-minutes))
  14950. nval)
  14951. (when (string= org-clock-current-task heading)
  14952. (setq org-clock-effort nval)
  14953. (org-clock-update-mode-line)))
  14954. (run-hook-with-args 'org-property-changed-functions key nval)))
  14955. (defun org-find-olp (path &optional this-buffer)
  14956. "Return a marker pointing to the entry at outline path OLP.
  14957. If anything goes wrong, throw an error.
  14958. You can wrap this call to catch the error like this:
  14959. (condition-case msg
  14960. (org-mobile-locate-entry (match-string 4))
  14961. (error (nth 1 msg)))
  14962. The return value will then be either a string with the error message,
  14963. or a marker if everything is OK.
  14964. If THIS-BUFFER is set, the outline path does not contain a file,
  14965. only headings."
  14966. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14967. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14968. (level 1)
  14969. (lmin 1)
  14970. (lmax 1)
  14971. end found flevel)
  14972. (unless buffer (error "File not found :%s" file))
  14973. (with-current-buffer buffer
  14974. (unless (derived-mode-p 'org-mode)
  14975. (error "Buffer %s needs to be in Org mode" buffer))
  14976. (org-with-wide-buffer
  14977. (goto-char (point-min))
  14978. (dolist (heading path)
  14979. (let ((re (format org-complex-heading-regexp-format
  14980. (regexp-quote heading)))
  14981. (cnt 0))
  14982. (while (re-search-forward re end t)
  14983. (setq level (- (match-end 1) (match-beginning 1)))
  14984. (when (and (>= level lmin) (<= level lmax))
  14985. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14986. (when (= cnt 0)
  14987. (error "Heading not found on level %d: %s" lmax heading))
  14988. (when (> cnt 1)
  14989. (error "Heading not unique on level %d: %s" lmax heading))
  14990. (goto-char found)
  14991. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14992. (setq end (save-excursion (org-end-of-subtree t t)))))
  14993. (when (org-at-heading-p)
  14994. (point-marker))))))
  14995. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14996. "Find node HEADING in BUFFER.
  14997. Return a marker to the heading if it was found, or nil if not.
  14998. If POS-ONLY is set, return just the position instead of a marker.
  14999. The heading text must match exact, but it may have a TODO keyword,
  15000. a priority cookie and tags in the standard locations."
  15001. (with-current-buffer (or buffer (current-buffer))
  15002. (org-with-wide-buffer
  15003. (goto-char (point-min))
  15004. (let (case-fold-search)
  15005. (when (re-search-forward
  15006. (format org-complex-heading-regexp-format
  15007. (regexp-quote heading)) nil t)
  15008. (if pos-only
  15009. (match-beginning 0)
  15010. (move-marker (make-marker) (match-beginning 0))))))))
  15011. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15012. "Find Org node headline HEADING in all .org files in directory DIR.
  15013. When the target headline is found, return a marker to this location."
  15014. (let ((files (directory-files (or dir default-directory)
  15015. t "\\`[^.#].*\\.org\\'"))
  15016. visiting m buffer)
  15017. (catch 'found
  15018. (dolist (file files)
  15019. (message "trying %s" file)
  15020. (setq visiting (org-find-base-buffer-visiting file))
  15021. (setq buffer (or visiting (find-file-noselect file)))
  15022. (setq m (org-find-exact-headline-in-buffer
  15023. heading buffer))
  15024. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15025. (and m (throw 'found m))))))
  15026. (defun org-find-entry-with-id (ident)
  15027. "Locate the entry that contains the ID property with exact value IDENT.
  15028. IDENT can be a string, a symbol or a number, this function will search for
  15029. the string representation of it.
  15030. Return the position where this entry starts, or nil if there is no such entry."
  15031. (interactive "sID: ")
  15032. (let ((id (cond
  15033. ((stringp ident) ident)
  15034. ((symbolp ident) (symbol-name ident))
  15035. ((numberp ident) (number-to-string ident))
  15036. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15037. (org-with-wide-buffer (org-find-property "ID" id))))
  15038. ;;;; Timestamps
  15039. (defvar org-last-changed-timestamp nil)
  15040. (defvar org-last-inserted-timestamp nil
  15041. "The last time stamp inserted with `org-insert-time-stamp'.")
  15042. (defun org-time-stamp (arg &optional inactive)
  15043. "Prompt for a date/time and insert a time stamp.
  15044. If the user specifies a time like HH:MM or if this command is
  15045. called with at least one prefix argument, the time stamp contains
  15046. the date and the time. Otherwise, only the date is included.
  15047. All parts of a date not specified by the user are filled in from
  15048. the timestamp at point, if any, or the current date/time
  15049. otherwise.
  15050. If there is already a timestamp at the cursor, it is replaced.
  15051. With two universal prefix arguments, insert an active timestamp
  15052. with the current time without prompting the user.
  15053. When called from lisp, the timestamp is inactive if INACTIVE is
  15054. non-nil."
  15055. (interactive "P")
  15056. (let* ((ts (cond
  15057. ((org-at-date-range-p t)
  15058. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15059. ((org-at-timestamp-p 'lax) (match-string 0))))
  15060. ;; Default time is either the timestamp at point or today.
  15061. ;; When entering a range, only the range start is considered.
  15062. (default-time (if (not ts) (current-time)
  15063. (apply #'encode-time (org-parse-time-string ts))))
  15064. (default-input (and ts (org-get-compact-tod ts)))
  15065. (repeater (and ts
  15066. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15067. (match-string 0 ts)))
  15068. org-time-was-given
  15069. org-end-time-was-given
  15070. (time
  15071. (and (if (equal arg '(16)) (current-time)
  15072. ;; Preserve `this-command' and `last-command'.
  15073. (let ((this-command this-command)
  15074. (last-command last-command))
  15075. (org-read-date
  15076. arg 'totime nil nil default-time default-input
  15077. inactive))))))
  15078. (cond
  15079. ((and ts
  15080. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15081. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15082. (insert "--")
  15083. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15084. (ts
  15085. ;; Make sure we're on a timestamp. When in the middle of a date
  15086. ;; range, move arbitrarily to range end.
  15087. (unless (org-at-timestamp-p 'lax)
  15088. (skip-chars-forward "-")
  15089. (org-at-timestamp-p 'lax))
  15090. (replace-match "")
  15091. (setq org-last-changed-timestamp
  15092. (org-insert-time-stamp
  15093. time (or org-time-was-given arg)
  15094. inactive nil nil (list org-end-time-was-given)))
  15095. (when repeater
  15096. (backward-char)
  15097. (insert " " repeater)
  15098. (setq org-last-changed-timestamp
  15099. (concat (substring org-last-inserted-timestamp 0 -1)
  15100. " " repeater ">")))
  15101. (message "Timestamp updated"))
  15102. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15103. (t (org-insert-time-stamp
  15104. time (or org-time-was-given arg) inactive nil nil
  15105. (list org-end-time-was-given))))))
  15106. ;; FIXME: can we use this for something else, like computing time differences?
  15107. (defun org-get-compact-tod (s)
  15108. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15109. (let* ((t1 (match-string 1 s))
  15110. (h1 (string-to-number (match-string 2 s)))
  15111. (m1 (string-to-number (match-string 3 s)))
  15112. (t2 (and (match-end 4) (match-string 5 s)))
  15113. (h2 (and t2 (string-to-number (match-string 6 s))))
  15114. (m2 (and t2 (string-to-number (match-string 7 s))))
  15115. dh dm)
  15116. (if (not t2)
  15117. t1
  15118. (setq dh (- h2 h1) dm (- m2 m1))
  15119. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15120. (concat t1 "+" (number-to-string dh)
  15121. (and (/= 0 dm) (format ":%02d" dm)))))))
  15122. (defun org-time-stamp-inactive (&optional arg)
  15123. "Insert an inactive time stamp.
  15124. An inactive time stamp is enclosed in square brackets instead of angle
  15125. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15126. does not link to the calendar and cannot be changed with the S-cursor keys.
  15127. So these are more for recording a certain time/date."
  15128. (interactive "P")
  15129. (org-time-stamp arg 'inactive))
  15130. (defvar org-date-ovl (make-overlay 1 1))
  15131. (overlay-put org-date-ovl 'face 'org-date-selected)
  15132. (delete-overlay org-date-ovl)
  15133. (defvar org-ans1) ; dynamically scoped parameter
  15134. (defvar org-ans2) ; dynamically scoped parameter
  15135. (defvar org-plain-time-of-day-regexp) ; defined below
  15136. (defvar org-overriding-default-time nil) ; dynamically scoped
  15137. (defvar org-read-date-overlay nil)
  15138. (defvar org-dcst nil) ; dynamically scoped
  15139. (defvar org-read-date-history nil)
  15140. (defvar org-read-date-final-answer nil)
  15141. (defvar org-read-date-analyze-futurep nil)
  15142. (defvar org-read-date-analyze-forced-year nil)
  15143. (defvar org-read-date-inactive)
  15144. (defvar org-read-date-minibuffer-local-map
  15145. (let* ((map (make-sparse-keymap)))
  15146. (set-keymap-parent map minibuffer-local-map)
  15147. (org-defkey map (kbd ".")
  15148. (lambda () (interactive)
  15149. ;; Are we at the beginning of the prompt?
  15150. (if (looking-back "^[^:]+: "
  15151. (let ((inhibit-field-text-motion t))
  15152. (line-beginning-position)))
  15153. (org-eval-in-calendar '(calendar-goto-today))
  15154. (insert "."))))
  15155. (org-defkey map (kbd "C-.")
  15156. (lambda () (interactive)
  15157. (org-eval-in-calendar '(calendar-goto-today))))
  15158. (org-defkey map [(meta shift left)]
  15159. (lambda () (interactive)
  15160. (org-eval-in-calendar '(calendar-backward-month 1))))
  15161. (org-defkey map [(meta shift right)]
  15162. (lambda () (interactive)
  15163. (org-eval-in-calendar '(calendar-forward-month 1))))
  15164. (org-defkey map [(meta shift up)]
  15165. (lambda () (interactive)
  15166. (org-eval-in-calendar '(calendar-backward-year 1))))
  15167. (org-defkey map [(meta shift down)]
  15168. (lambda () (interactive)
  15169. (org-eval-in-calendar '(calendar-forward-year 1))))
  15170. (org-defkey map [?\e (shift left)]
  15171. (lambda () (interactive)
  15172. (org-eval-in-calendar '(calendar-backward-month 1))))
  15173. (org-defkey map [?\e (shift right)]
  15174. (lambda () (interactive)
  15175. (org-eval-in-calendar '(calendar-forward-month 1))))
  15176. (org-defkey map [?\e (shift up)]
  15177. (lambda () (interactive)
  15178. (org-eval-in-calendar '(calendar-backward-year 1))))
  15179. (org-defkey map [?\e (shift down)]
  15180. (lambda () (interactive)
  15181. (org-eval-in-calendar '(calendar-forward-year 1))))
  15182. (org-defkey map [(shift up)]
  15183. (lambda () (interactive)
  15184. (org-eval-in-calendar '(calendar-backward-week 1))))
  15185. (org-defkey map [(shift down)]
  15186. (lambda () (interactive)
  15187. (org-eval-in-calendar '(calendar-forward-week 1))))
  15188. (org-defkey map [(shift left)]
  15189. (lambda () (interactive)
  15190. (org-eval-in-calendar '(calendar-backward-day 1))))
  15191. (org-defkey map [(shift right)]
  15192. (lambda () (interactive)
  15193. (org-eval-in-calendar '(calendar-forward-day 1))))
  15194. (org-defkey map "!"
  15195. (lambda () (interactive)
  15196. (org-eval-in-calendar '(diary-view-entries))
  15197. (message "")))
  15198. (org-defkey map ">"
  15199. (lambda () (interactive)
  15200. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15201. (org-defkey map "<"
  15202. (lambda () (interactive)
  15203. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15204. (org-defkey map "\C-v"
  15205. (lambda () (interactive)
  15206. (org-eval-in-calendar
  15207. '(calendar-scroll-left-three-months 1))))
  15208. (org-defkey map "\M-v"
  15209. (lambda () (interactive)
  15210. (org-eval-in-calendar
  15211. '(calendar-scroll-right-three-months 1))))
  15212. map)
  15213. "Keymap for minibuffer commands when using `org-read-date'.")
  15214. (defvar org-def)
  15215. (defvar org-defdecode)
  15216. (defvar org-with-time)
  15217. (defvar calendar-setup) ; Dynamically scoped.
  15218. (defun org-read-date (&optional with-time to-time from-string prompt
  15219. default-time default-input inactive)
  15220. "Read a date, possibly a time, and make things smooth for the user.
  15221. The prompt will suggest to enter an ISO date, but you can also enter anything
  15222. which will at least partially be understood by `parse-time-string'.
  15223. Unrecognized parts of the date will default to the current day, month, year,
  15224. hour and minute. If this command is called to replace a timestamp at point,
  15225. or to enter the second timestamp of a range, the default time is taken
  15226. from the existing stamp. Furthermore, the command prefers the future,
  15227. so if you are giving a date where the year is not given, and the day-month
  15228. combination is already past in the current year, it will assume you
  15229. mean next year. For details, see the manual. A few examples:
  15230. 3-2-5 --> 2003-02-05
  15231. feb 15 --> currentyear-02-15
  15232. 2/15 --> currentyear-02-15
  15233. sep 12 9 --> 2009-09-12
  15234. 12:45 --> today 12:45
  15235. 22 sept 0:34 --> currentyear-09-22 0:34
  15236. 12 --> currentyear-currentmonth-12
  15237. Fri --> nearest Friday after today
  15238. -Tue --> last Tuesday
  15239. etc.
  15240. Furthermore you can specify a relative date by giving, as the *first* thing
  15241. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15242. change in days weeks, months, years.
  15243. With a single plus or minus, the date is relative to today. With a double
  15244. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15245. +4d --> four days from today
  15246. +4 --> same as above
  15247. +2w --> two weeks from today
  15248. ++5 --> five days from default date
  15249. The function understands only English month and weekday abbreviations.
  15250. While prompting, a calendar is popped up - you can also select the
  15251. date with the mouse (button 1). The calendar shows a period of three
  15252. months. To scroll it to other months, use the keys `>' and `<'.
  15253. If you don't like the calendar, turn it off with
  15254. (setq org-read-date-popup-calendar nil)
  15255. With optional argument TO-TIME, the date will immediately be converted
  15256. to an internal time.
  15257. With an optional argument WITH-TIME, the prompt will suggest to
  15258. also insert a time. Note that when WITH-TIME is not set, you can
  15259. still enter a time, and this function will inform the calling routine
  15260. about this change. The calling routine may then choose to change the
  15261. format used to insert the time stamp into the buffer to include the time.
  15262. With optional argument FROM-STRING, read from this string instead from
  15263. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15264. the time/date that is used for everything that is not specified by the
  15265. user."
  15266. (require 'parse-time)
  15267. (let* ((org-with-time with-time)
  15268. (org-time-stamp-rounding-minutes
  15269. (if (equal org-with-time '(16))
  15270. '(0 0)
  15271. org-time-stamp-rounding-minutes))
  15272. (org-dcst org-display-custom-times)
  15273. (ct (org-current-time))
  15274. (org-def (or org-overriding-default-time default-time ct))
  15275. (org-defdecode (decode-time org-def))
  15276. (cur-frame (selected-frame))
  15277. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15278. (calendar-setup
  15279. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15280. (calendar-move-hook nil)
  15281. (calendar-view-diary-initially-flag nil)
  15282. (calendar-view-holidays-initially-flag nil)
  15283. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15284. ;; Rationalize `org-def' and `org-defdecode', if required.
  15285. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15286. (setf (nth 2 org-defdecode) -1)
  15287. (setf (nth 1 org-defdecode) 59)
  15288. (setq org-def (apply #'encode-time org-defdecode))
  15289. (setq org-defdecode (decode-time org-def)))
  15290. (let* ((timestr (format-time-string
  15291. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15292. org-def))
  15293. (prompt (concat (if prompt (concat prompt " ") "")
  15294. (format "Date+time [%s]: " timestr))))
  15295. (cond
  15296. (from-string (setq ans from-string))
  15297. (org-read-date-popup-calendar
  15298. (save-excursion
  15299. (save-window-excursion
  15300. (calendar)
  15301. (when (eq calendar-setup 'calendar-only)
  15302. (setq cal-frame
  15303. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15304. (select-frame cal-frame))
  15305. (org-eval-in-calendar '(setq cursor-type nil) t)
  15306. (unwind-protect
  15307. (progn
  15308. (calendar-forward-day (- (time-to-days org-def)
  15309. (calendar-absolute-from-gregorian
  15310. (calendar-current-date))))
  15311. (org-eval-in-calendar nil t)
  15312. (let* ((old-map (current-local-map))
  15313. (map (copy-keymap calendar-mode-map))
  15314. (minibuffer-local-map
  15315. (copy-keymap org-read-date-minibuffer-local-map)))
  15316. (org-defkey map (kbd "RET") 'org-calendar-select)
  15317. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15318. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15319. (unwind-protect
  15320. (progn
  15321. (use-local-map map)
  15322. (setq org-read-date-inactive inactive)
  15323. (add-hook 'post-command-hook 'org-read-date-display)
  15324. (setq org-ans0
  15325. (read-string prompt
  15326. default-input
  15327. 'org-read-date-history
  15328. nil))
  15329. ;; org-ans0: from prompt
  15330. ;; org-ans1: from mouse click
  15331. ;; org-ans2: from calendar motion
  15332. (setq ans
  15333. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15334. (remove-hook 'post-command-hook 'org-read-date-display)
  15335. (use-local-map old-map)
  15336. (when org-read-date-overlay
  15337. (delete-overlay org-read-date-overlay)
  15338. (setq org-read-date-overlay nil)))))
  15339. (bury-buffer "*Calendar*")
  15340. (when cal-frame
  15341. (delete-frame cal-frame)
  15342. (select-frame-set-input-focus cur-frame))))))
  15343. (t ; Naked prompt only
  15344. (unwind-protect
  15345. (setq ans (read-string prompt default-input
  15346. 'org-read-date-history timestr))
  15347. (when org-read-date-overlay
  15348. (delete-overlay org-read-date-overlay)
  15349. (setq org-read-date-overlay nil))))))
  15350. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15351. (when org-read-date-analyze-forced-year
  15352. (message "Year was forced into %s"
  15353. (if org-read-date-force-compatible-dates
  15354. "compatible range (1970-2037)"
  15355. "range representable on this machine"))
  15356. (ding))
  15357. ;; One round trip to get rid of 34th of August and stuff like that....
  15358. (setq final (decode-time (apply 'encode-time final)))
  15359. (setq org-read-date-final-answer ans)
  15360. (if to-time
  15361. (apply 'encode-time final)
  15362. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15363. (format "%04d-%02d-%02d %02d:%02d"
  15364. (nth 5 final) (nth 4 final) (nth 3 final)
  15365. (nth 2 final) (nth 1 final))
  15366. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15367. (defun org-read-date-display ()
  15368. "Display the current date prompt interpretation in the minibuffer."
  15369. (when org-read-date-display-live
  15370. (when org-read-date-overlay
  15371. (delete-overlay org-read-date-overlay))
  15372. (when (minibufferp (current-buffer))
  15373. (save-excursion
  15374. (end-of-line 1)
  15375. (while (not (equal (buffer-substring
  15376. (max (point-min) (- (point) 4)) (point))
  15377. " "))
  15378. (insert " ")))
  15379. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15380. " " (or org-ans1 org-ans2)))
  15381. (org-end-time-was-given nil)
  15382. (f (org-read-date-analyze ans org-def org-defdecode))
  15383. (fmts (if org-dcst
  15384. org-time-stamp-custom-formats
  15385. org-time-stamp-formats))
  15386. (fmt (if (or org-with-time
  15387. (and (boundp 'org-time-was-given) org-time-was-given))
  15388. (cdr fmts)
  15389. (car fmts)))
  15390. (txt (format-time-string fmt (apply 'encode-time f)))
  15391. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15392. (txt (concat "=> " txt)))
  15393. (when (and org-end-time-was-given
  15394. (string-match org-plain-time-of-day-regexp txt))
  15395. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15396. org-end-time-was-given
  15397. (substring txt (match-end 0)))))
  15398. (when org-read-date-analyze-futurep
  15399. (setq txt (concat txt " (=>F)")))
  15400. (setq org-read-date-overlay
  15401. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15402. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15403. (defun org-read-date-analyze (ans def defdecode)
  15404. "Analyze the combined answer of the date prompt."
  15405. ;; FIXME: cleanup and comment
  15406. ;; Pass `current-time' result to `decode-time' (instead of calling
  15407. ;; without arguments) so that only `current-time' has to be
  15408. ;; overriden in tests.
  15409. (let ((org-def def)
  15410. (org-defdecode defdecode)
  15411. (nowdecode (decode-time (current-time)))
  15412. delta deltan deltaw deltadef year month day
  15413. hour minute second wday pm h2 m2 tl wday1
  15414. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15415. (setq org-read-date-analyze-futurep nil
  15416. org-read-date-analyze-forced-year nil)
  15417. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15418. (setq ans "+0"))
  15419. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15420. (setq ans (replace-match "" t t ans)
  15421. deltan (car delta)
  15422. deltaw (nth 1 delta)
  15423. deltadef (nth 2 delta)))
  15424. ;; Check if there is an iso week date in there. If yes, store the
  15425. ;; info and postpone interpreting it until the rest of the parsing
  15426. ;; is done.
  15427. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15428. (setq iso-year (when (match-end 1)
  15429. (org-small-year-to-year
  15430. (string-to-number (match-string 1 ans))))
  15431. iso-weekday (when (match-end 3)
  15432. (string-to-number (match-string 3 ans)))
  15433. iso-week (string-to-number (match-string 2 ans)))
  15434. (setq ans (replace-match "" t t ans)))
  15435. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15436. (when (string-match
  15437. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15438. (setq year (if (match-end 2)
  15439. (string-to-number (match-string 2 ans))
  15440. (progn (setq kill-year t)
  15441. (string-to-number (format-time-string "%Y"))))
  15442. month (string-to-number (match-string 3 ans))
  15443. day (string-to-number (match-string 4 ans)))
  15444. (setq year (org-small-year-to-year year))
  15445. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15446. t nil ans)))
  15447. ;; Help matching dotted european dates
  15448. (when (string-match
  15449. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15450. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15451. (setq kill-year t)
  15452. (string-to-number (format-time-string "%Y")))
  15453. day (string-to-number (match-string 1 ans))
  15454. month (string-to-number (match-string 2 ans))
  15455. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15456. t nil ans)))
  15457. ;; Help matching american dates, like 5/30 or 5/30/7
  15458. (when (string-match
  15459. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15460. (setq year (if (match-end 4)
  15461. (string-to-number (match-string 4 ans))
  15462. (progn (setq kill-year t)
  15463. (string-to-number (format-time-string "%Y"))))
  15464. month (string-to-number (match-string 1 ans))
  15465. day (string-to-number (match-string 2 ans)))
  15466. (setq year (org-small-year-to-year year))
  15467. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15468. t nil ans)))
  15469. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15470. ;; If there is a time with am/pm, and *no* time without it, we convert
  15471. ;; so that matching will be successful.
  15472. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15473. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15474. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15475. (setq hour (string-to-number (match-string 1 ans))
  15476. minute (if (match-end 3)
  15477. (string-to-number (match-string 3 ans))
  15478. 0)
  15479. pm (equal ?p
  15480. (string-to-char (downcase (match-string 4 ans)))))
  15481. (if (and (= hour 12) (not pm))
  15482. (setq hour 0)
  15483. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15484. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15485. t t ans))))
  15486. ;; Check if a time range is given as a duration
  15487. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15488. (setq hour (string-to-number (match-string 1 ans))
  15489. h2 (+ hour (string-to-number (match-string 3 ans)))
  15490. minute (string-to-number (match-string 2 ans))
  15491. m2 (+ minute (if (match-end 5) (string-to-number
  15492. (match-string 5 ans))0)))
  15493. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15494. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15495. t t ans)))
  15496. ;; Check if there is a time range
  15497. (when (boundp 'org-end-time-was-given)
  15498. (setq org-time-was-given nil)
  15499. (when (and (string-match org-plain-time-of-day-regexp ans)
  15500. (match-end 8))
  15501. (setq org-end-time-was-given (match-string 8 ans))
  15502. (setq ans (concat (substring ans 0 (match-beginning 7))
  15503. (substring ans (match-end 7))))))
  15504. (setq tl (parse-time-string ans)
  15505. day (or (nth 3 tl) (nth 3 org-defdecode))
  15506. month
  15507. (cond ((nth 4 tl))
  15508. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15509. ;; Day was specified. Make sure DAY+MONTH
  15510. ;; combination happens in the future.
  15511. ((nth 3 tl)
  15512. (setq futurep t)
  15513. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15514. (nth 4 nowdecode)))
  15515. (t (nth 4 org-defdecode)))
  15516. year
  15517. (cond ((and (not kill-year) (nth 5 tl)))
  15518. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15519. ;; Month was guessed in the future and is at least
  15520. ;; equal to NOWDECODE's. Fix year accordingly.
  15521. (futurep
  15522. (if (or (> month (nth 4 nowdecode))
  15523. (>= day (nth 3 nowdecode)))
  15524. (nth 5 nowdecode)
  15525. (1+ (nth 5 nowdecode))))
  15526. ;; Month was specified. Make sure MONTH+YEAR
  15527. ;; combination happens in the future.
  15528. ((nth 4 tl)
  15529. (setq futurep t)
  15530. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15531. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15532. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15533. (t (nth 5 nowdecode))))
  15534. (t (nth 5 org-defdecode)))
  15535. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15536. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15537. second (or (nth 0 tl) 0)
  15538. wday (nth 6 tl))
  15539. (when (and (eq org-read-date-prefer-future 'time)
  15540. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15541. (equal day (nth 3 nowdecode))
  15542. (equal month (nth 4 nowdecode))
  15543. (equal year (nth 5 nowdecode))
  15544. (nth 2 tl)
  15545. (or (< (nth 2 tl) (nth 2 nowdecode))
  15546. (and (= (nth 2 tl) (nth 2 nowdecode))
  15547. (nth 1 tl)
  15548. (< (nth 1 tl) (nth 1 nowdecode)))))
  15549. (setq day (1+ day)
  15550. futurep t))
  15551. ;; Special date definitions below
  15552. (cond
  15553. (iso-week
  15554. ;; There was an iso week
  15555. (require 'cal-iso)
  15556. (setq futurep nil)
  15557. (setq year (or iso-year year)
  15558. day (or iso-weekday wday 1)
  15559. wday nil ; to make sure that the trigger below does not match
  15560. iso-date (calendar-gregorian-from-absolute
  15561. (calendar-iso-to-absolute
  15562. (list iso-week day year))))
  15563. ; FIXME: Should we also push ISO weeks into the future?
  15564. ; (when (and org-read-date-prefer-future
  15565. ; (not iso-year)
  15566. ; (< (calendar-absolute-from-gregorian iso-date)
  15567. ; (time-to-days (current-time))))
  15568. ; (setq year (1+ year)
  15569. ; iso-date (calendar-gregorian-from-absolute
  15570. ; (calendar-iso-to-absolute
  15571. ; (list iso-week day year)))))
  15572. (setq month (car iso-date)
  15573. year (nth 2 iso-date)
  15574. day (nth 1 iso-date)))
  15575. (deltan
  15576. (setq futurep nil)
  15577. (unless deltadef
  15578. ;; Pass `current-time' result to `decode-time' (instead of
  15579. ;; calling without arguments) so that only `current-time' has
  15580. ;; to be overriden in tests.
  15581. (let ((now (decode-time (current-time))))
  15582. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15583. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15584. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15585. ((equal deltaw "m") (setq month (+ month deltan)))
  15586. ((equal deltaw "y") (setq year (+ year deltan)))))
  15587. ((and wday (not (nth 3 tl)))
  15588. ;; Weekday was given, but no day, so pick that day in the week
  15589. ;; on or after the derived date.
  15590. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15591. (unless (equal wday wday1)
  15592. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15593. (when (and (boundp 'org-time-was-given)
  15594. (nth 2 tl))
  15595. (setq org-time-was-given t))
  15596. (when (< year 100) (setq year (+ 2000 year)))
  15597. ;; Check of the date is representable
  15598. (if org-read-date-force-compatible-dates
  15599. (progn
  15600. (when (< year 1970)
  15601. (setq year 1970 org-read-date-analyze-forced-year t))
  15602. (when (> year 2037)
  15603. (setq year 2037 org-read-date-analyze-forced-year t)))
  15604. (condition-case nil
  15605. (ignore (encode-time second minute hour day month year))
  15606. (error
  15607. (setq year (nth 5 org-defdecode))
  15608. (setq org-read-date-analyze-forced-year t))))
  15609. (setq org-read-date-analyze-futurep futurep)
  15610. (list second minute hour day month year)))
  15611. (defvar parse-time-weekdays)
  15612. (defun org-read-date-get-relative (s today default)
  15613. "Check string S for special relative date string.
  15614. TODAY and DEFAULT are internal times, for today and for a default.
  15615. Return shift list (N what def-flag)
  15616. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15617. N is the number of WHATs to shift.
  15618. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15619. the DEFAULT date rather than TODAY."
  15620. (require 'parse-time)
  15621. (when (and
  15622. (string-match
  15623. (concat
  15624. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15625. "\\([0-9]+\\)?"
  15626. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15627. "\\([ \t]\\|$\\)") s)
  15628. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15629. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15630. (string-to-char (substring (match-string 1 s) -1))
  15631. ?+))
  15632. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15633. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15634. (what (if (match-end 3) (match-string 3 s) "d"))
  15635. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15636. (date (if rel default today))
  15637. (wday (nth 6 (decode-time date)))
  15638. delta)
  15639. (if wday1
  15640. (progn
  15641. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15642. (when (= delta 0) (setq delta 7))
  15643. (when (= dir ?-)
  15644. (setq delta (- delta 7))
  15645. (when (= delta 0) (setq delta -7)))
  15646. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15647. (list delta "d" rel))
  15648. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15649. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15650. "Turn a user-specified date into the internal representation.
  15651. The internal representation needed by the calendar is (month day year).
  15652. This is a wrapper to handle the brain-dead convention in calendar that
  15653. user function argument order change dependent on argument order."
  15654. (pcase calendar-date-style
  15655. (`american (list arg1 arg2 arg3))
  15656. (`european (list arg2 arg1 arg3))
  15657. (`iso (list arg2 arg3 arg1))))
  15658. (defun org-eval-in-calendar (form &optional keepdate)
  15659. "Eval FORM in the calendar window and return to current window.
  15660. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15661. (let ((sf (selected-frame))
  15662. (sw (selected-window)))
  15663. (select-window (get-buffer-window "*Calendar*" t))
  15664. (eval form)
  15665. (when (and (not keepdate) (calendar-cursor-to-date))
  15666. (let* ((date (calendar-cursor-to-date))
  15667. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15668. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15669. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15670. (select-window sw)
  15671. (select-frame-set-input-focus sf)))
  15672. (defun org-calendar-select ()
  15673. "Return to `org-read-date' with the date currently selected.
  15674. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15675. (interactive)
  15676. (when (calendar-cursor-to-date)
  15677. (let* ((date (calendar-cursor-to-date))
  15678. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15679. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15680. (when (active-minibuffer-window) (exit-minibuffer))))
  15681. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15682. "Insert a date stamp for the date given by the internal TIME.
  15683. See `format-time-string' for the format of TIME.
  15684. WITH-HM means use the stamp format that includes the time of the day.
  15685. INACTIVE means use square brackets instead of angular ones, so that the
  15686. stamp will not contribute to the agenda.
  15687. PRE and POST are optional strings to be inserted before and after the
  15688. stamp.
  15689. The command returns the inserted time stamp."
  15690. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15691. stamp)
  15692. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15693. (insert-before-markers (or pre ""))
  15694. (when (listp extra)
  15695. (setq extra (car extra))
  15696. (if (and (stringp extra)
  15697. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15698. (setq extra (format "-%02d:%02d"
  15699. (string-to-number (match-string 1 extra))
  15700. (string-to-number (match-string 2 extra))))
  15701. (setq extra nil)))
  15702. (when extra
  15703. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15704. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15705. (insert-before-markers (or post ""))
  15706. (setq org-last-inserted-timestamp stamp)))
  15707. (defun org-toggle-time-stamp-overlays ()
  15708. "Toggle the use of custom time stamp formats."
  15709. (interactive)
  15710. (setq org-display-custom-times (not org-display-custom-times))
  15711. (unless org-display-custom-times
  15712. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15713. (while (setq p (next-single-property-change p 'display))
  15714. (when (and (get-text-property p 'display)
  15715. (eq (get-text-property p 'face) 'org-date))
  15716. (remove-text-properties
  15717. p (setq p (next-single-property-change p 'display))
  15718. '(display t))))
  15719. (set-buffer-modified-p bmp)))
  15720. (org-restart-font-lock)
  15721. (setq org-table-may-need-update t)
  15722. (if org-display-custom-times
  15723. (message "Time stamps are overlaid with custom format")
  15724. (message "Time stamp overlays removed")))
  15725. (defun org-display-custom-time (beg end)
  15726. "Overlay modified time stamp format over timestamp between BEG and END."
  15727. (let* ((ts (buffer-substring beg end))
  15728. t1 w1 with-hm tf time str w2 (off 0))
  15729. (save-match-data
  15730. (setq t1 (org-parse-time-string ts t))
  15731. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15732. (setq off (- (match-end 0) (match-beginning 0)))))
  15733. (setq end (- end off))
  15734. (setq w1 (- end beg)
  15735. with-hm (and (nth 1 t1) (nth 2 t1))
  15736. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15737. time (org-fix-decoded-time t1)
  15738. str (org-add-props
  15739. (format-time-string
  15740. (substring tf 1 -1) (apply 'encode-time time))
  15741. nil 'mouse-face 'highlight)
  15742. w2 (length str))
  15743. (unless (= w2 w1)
  15744. (add-text-properties (1+ beg) (+ 2 beg)
  15745. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15746. (put-text-property beg end 'display str)))
  15747. (defun org-fix-decoded-time (time)
  15748. "Set 0 instead of nil for the first 6 elements of time.
  15749. Don't touch the rest."
  15750. (let ((n 0))
  15751. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15752. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15753. "Difference between TIMESTAMP-STRING and now in days.
  15754. If SECONDS is non-nil, return the difference in seconds."
  15755. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15756. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15757. (funcall fdiff (current-time)))))
  15758. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15759. "Is the time in TIMESTAMP-STRING close to the current date?"
  15760. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15761. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15762. (not (org-entry-is-done-p))))
  15763. (defun org-get-wdays (ts &optional delay zero-delay)
  15764. "Get the deadline lead time appropriate for timestring TS.
  15765. When DELAY is non-nil, get the delay time for scheduled items
  15766. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15767. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15768. don't try to find the delay cookie in the scheduled timestamp."
  15769. (let ((tv (if delay org-scheduled-delay-days
  15770. org-deadline-warning-days)))
  15771. (cond
  15772. ((or (and delay (< tv 0))
  15773. (and delay zero-delay (<= tv 0))
  15774. (and (not delay) (<= tv 0)))
  15775. ;; Enforce this value no matter what
  15776. (- tv))
  15777. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15778. ;; lead time is specified.
  15779. (floor (* (string-to-number (match-string 1 ts))
  15780. (cdr (assoc (match-string 2 ts)
  15781. '(("d" . 1) ("w" . 7)
  15782. ("m" . 30.4) ("y" . 365.25)
  15783. ("h" . 0.041667)))))))
  15784. ;; go for the default.
  15785. (t tv))))
  15786. (defun org-calendar-select-mouse (ev)
  15787. "Return to `org-read-date' with the date currently selected.
  15788. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15789. (interactive "e")
  15790. (mouse-set-point ev)
  15791. (when (calendar-cursor-to-date)
  15792. (let* ((date (calendar-cursor-to-date))
  15793. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15794. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15795. (when (active-minibuffer-window) (exit-minibuffer))))
  15796. (defun org-check-deadlines (ndays)
  15797. "Check if there are any deadlines due or past due.
  15798. A deadline is considered due if it happens within `org-deadline-warning-days'
  15799. days from today's date. If the deadline appears in an entry marked DONE,
  15800. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15801. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15802. are shown."
  15803. (interactive "P")
  15804. (let* ((org-warn-days
  15805. (cond
  15806. ((equal ndays '(4)) 100000)
  15807. (ndays (prefix-numeric-value ndays))
  15808. (t (abs org-deadline-warning-days))))
  15809. (case-fold-search nil)
  15810. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15811. (callback
  15812. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15813. (message "%d deadlines past-due or due within %d days"
  15814. (org-occur regexp nil callback)
  15815. org-warn-days)))
  15816. (defsubst org-re-timestamp (type)
  15817. "Return a regexp for timestamp TYPE.
  15818. Allowed values for TYPE are:
  15819. all: all timestamps
  15820. active: only active timestamps (<...>)
  15821. inactive: only inactive timestamps ([...])
  15822. scheduled: only scheduled timestamps
  15823. deadline: only deadline timestamps
  15824. closed: only closed time-stamps
  15825. When TYPE is nil, fall back on returning a regexp that matches
  15826. both scheduled and deadline timestamps."
  15827. (cl-case type
  15828. (all org-ts-regexp-both)
  15829. (active org-ts-regexp)
  15830. (inactive org-ts-regexp-inactive)
  15831. (scheduled org-scheduled-time-regexp)
  15832. (deadline org-deadline-time-regexp)
  15833. (closed org-closed-time-regexp)
  15834. (otherwise
  15835. (concat "\\<"
  15836. (regexp-opt (list org-deadline-string org-scheduled-string))
  15837. " *<\\([^>]+\\)>"))))
  15838. (defun org-check-before-date (d)
  15839. "Check if there are deadlines or scheduled entries before date D."
  15840. (interactive (list (org-read-date)))
  15841. (let* ((case-fold-search nil)
  15842. (regexp (org-re-timestamp org-ts-type))
  15843. (ts-type org-ts-type)
  15844. (callback
  15845. (lambda ()
  15846. (let ((match (match-string 1)))
  15847. (and (if (memq ts-type '(active inactive all))
  15848. (eq (org-element-type (save-excursion
  15849. (backward-char)
  15850. (org-element-context)))
  15851. 'timestamp)
  15852. (org-at-planning-p))
  15853. (time-less-p
  15854. (org-time-string-to-time match)
  15855. (org-time-string-to-time d)))))))
  15856. (message "%d entries before %s"
  15857. (org-occur regexp nil callback)
  15858. d)))
  15859. (defun org-check-after-date (d)
  15860. "Check if there are deadlines or scheduled entries after date D."
  15861. (interactive (list (org-read-date)))
  15862. (let* ((case-fold-search nil)
  15863. (regexp (org-re-timestamp org-ts-type))
  15864. (ts-type org-ts-type)
  15865. (callback
  15866. (lambda ()
  15867. (let ((match (match-string 1)))
  15868. (and (if (memq ts-type '(active inactive all))
  15869. (eq (org-element-type (save-excursion
  15870. (backward-char)
  15871. (org-element-context)))
  15872. 'timestamp)
  15873. (org-at-planning-p))
  15874. (not (time-less-p
  15875. (org-time-string-to-time match)
  15876. (org-time-string-to-time d))))))))
  15877. (message "%d entries after %s"
  15878. (org-occur regexp nil callback)
  15879. d)))
  15880. (defun org-check-dates-range (start-date end-date)
  15881. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15882. (interactive (list (org-read-date nil nil nil "Range starts")
  15883. (org-read-date nil nil nil "Range end")))
  15884. (let ((case-fold-search nil)
  15885. (regexp (org-re-timestamp org-ts-type))
  15886. (callback
  15887. (let ((type org-ts-type))
  15888. (lambda ()
  15889. (let ((match (match-string 1)))
  15890. (and
  15891. (if (memq type '(active inactive all))
  15892. (eq (org-element-type (save-excursion
  15893. (backward-char)
  15894. (org-element-context)))
  15895. 'timestamp)
  15896. (org-at-planning-p))
  15897. (not (time-less-p
  15898. (org-time-string-to-time match)
  15899. (org-time-string-to-time start-date)))
  15900. (time-less-p
  15901. (org-time-string-to-time match)
  15902. (org-time-string-to-time end-date))))))))
  15903. (message "%d entries between %s and %s"
  15904. (org-occur regexp nil callback) start-date end-date)))
  15905. (defun org-evaluate-time-range (&optional to-buffer)
  15906. "Evaluate a time range by computing the difference between start and end.
  15907. Normally the result is just printed in the echo area, but with prefix arg
  15908. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15909. If the time range is actually in a table, the result is inserted into the
  15910. next column.
  15911. For time difference computation, a year is assumed to be exactly 365
  15912. days in order to avoid rounding problems."
  15913. (interactive "P")
  15914. (or
  15915. (org-clock-update-time-maybe)
  15916. (save-excursion
  15917. (unless (org-at-date-range-p t)
  15918. (goto-char (point-at-bol))
  15919. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15920. (unless (org-at-date-range-p t)
  15921. (user-error "Not at a time-stamp range, and none found in current line")))
  15922. (let* ((ts1 (match-string 1))
  15923. (ts2 (match-string 2))
  15924. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15925. (match-end (match-end 0))
  15926. (time1 (org-time-string-to-time ts1))
  15927. (time2 (org-time-string-to-time ts2))
  15928. (t1 (float-time time1))
  15929. (t2 (float-time time2))
  15930. (diff (abs (- t2 t1)))
  15931. (negative (< (- t2 t1) 0))
  15932. ;; (ys (floor (* 365 24 60 60)))
  15933. (ds (* 24 60 60))
  15934. (hs (* 60 60))
  15935. (fy "%dy %dd %02d:%02d")
  15936. (fy1 "%dy %dd")
  15937. (fd "%dd %02d:%02d")
  15938. (fd1 "%dd")
  15939. (fh "%02d:%02d")
  15940. y d h m align)
  15941. (if havetime
  15942. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15943. y 0
  15944. d (floor (/ diff ds)) diff (mod diff ds)
  15945. h (floor (/ diff hs)) diff (mod diff hs)
  15946. m (floor (/ diff 60)))
  15947. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15948. y 0
  15949. d (floor (+ (/ diff ds) 0.5))
  15950. h 0 m 0))
  15951. (if (not to-buffer)
  15952. (message "%s" (org-make-tdiff-string y d h m))
  15953. (if (org-at-table-p)
  15954. (progn
  15955. (goto-char match-end)
  15956. (setq align t)
  15957. (and (looking-at " *|") (goto-char (match-end 0))))
  15958. (goto-char match-end))
  15959. (when (looking-at
  15960. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15961. (replace-match ""))
  15962. (when negative (insert " -"))
  15963. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15964. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15965. (insert " " (format fh h m))))
  15966. (when align (org-table-align))
  15967. (message "Time difference inserted")))))
  15968. (defun org-make-tdiff-string (y d h m)
  15969. (let ((fmt "")
  15970. (l nil))
  15971. (when (> y 0)
  15972. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15973. (push y l))
  15974. (when (> d 0)
  15975. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15976. (push d l))
  15977. (when (> h 0)
  15978. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15979. (push h l))
  15980. (when (> m 0)
  15981. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15982. (push m l))
  15983. (apply 'format fmt (nreverse l))))
  15984. (defun org-time-string-to-time (s &optional buffer pos)
  15985. "Convert a timestamp string into internal time."
  15986. (condition-case errdata
  15987. (apply 'encode-time (org-parse-time-string s))
  15988. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15989. s (if (not (and buffer pos))
  15990. ""
  15991. (format-message " at %d in buffer `%s'" pos buffer))
  15992. (cdr errdata)))))
  15993. (defun org-time-string-to-seconds (s)
  15994. "Convert a timestamp string to a number of seconds."
  15995. (float-time (org-time-string-to-time s)))
  15996. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15997. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15998. "Convert time stamp S to an absolute day number.
  15999. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16000. stamp, get the closest date to DAYNR. If PREFER is
  16001. `past' (respectively `future') return a date past (respectively
  16002. after) or equal to DAYNR.
  16003. POS is the location of time stamp S, as a buffer position in
  16004. BUFFER.
  16005. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16006. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16007. signalled."
  16008. (cond
  16009. ((string-match "\\`%%\\((.*)\\)" s)
  16010. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16011. ;; only able to match individual dates. If it fails, raise an
  16012. ;; error.
  16013. (if (and daynr
  16014. (org-diary-sexp-entry
  16015. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16016. daynr
  16017. (signal 'org-diary-sexp-no-match (list s))))
  16018. (daynr (org-closest-date s daynr prefer))
  16019. (t (time-to-days
  16020. (condition-case errdata
  16021. (apply #'encode-time (org-parse-time-string s))
  16022. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16023. s
  16024. (if (not (and buffer pos)) ""
  16025. (format-message " at %d in buffer `%s'" pos buffer))
  16026. (cdr errdata))))))))
  16027. (defun org-days-to-iso-week (days)
  16028. "Return the iso week number."
  16029. (require 'cal-iso)
  16030. (car (calendar-iso-from-absolute days)))
  16031. (defun org-small-year-to-year (year)
  16032. "Convert 2-digit years into 4-digit years.
  16033. YEAR is expanded into one of the 30 next years, if possible, or
  16034. into a past one. Any year larger than 99 is returned unchanged."
  16035. (if (>= year 100) year
  16036. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16037. (century (/ current 100))
  16038. (offset (- year (% current 100))))
  16039. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16040. ((> offset -70) (+ (* century 100) year))
  16041. (t (+ (* (1+ century) 100) year))))))
  16042. (defun org-time-from-absolute (d)
  16043. "Return the time corresponding to date D.
  16044. D may be an absolute day number, or a calendar-type list (month day year)."
  16045. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16046. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16047. (defvar org-agenda-current-date)
  16048. (defun org-calendar-holiday ()
  16049. "List of holidays, for Diary display in Org mode."
  16050. (require 'holidays)
  16051. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16052. (and hl (mapconcat #'identity hl "; "))))
  16053. (defun org-diary-sexp-entry (sexp entry d)
  16054. "Process a SEXP diary ENTRY for date D."
  16055. (require 'diary-lib)
  16056. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16057. ;; dynamically.
  16058. (let* ((sexp `(let ((entry ,entry)
  16059. (date ',d))
  16060. ,(car (read-from-string sexp))))
  16061. (result (if calendar-debug-sexp (eval sexp)
  16062. (condition-case nil
  16063. (eval sexp)
  16064. (error
  16065. (beep)
  16066. (message "Bad sexp at line %d in %s: %s"
  16067. (org-current-line)
  16068. (buffer-file-name) sexp)
  16069. (sleep-for 2))))))
  16070. (cond ((stringp result) (split-string result "; "))
  16071. ((and (consp result)
  16072. (not (consp (cdr result)))
  16073. (stringp (cdr result))) (cdr result))
  16074. ((and (consp result)
  16075. (stringp (car result))) result)
  16076. (result entry))))
  16077. (defun org-diary-to-ical-string (frombuf)
  16078. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16079. This uses the icalendar.el library."
  16080. (let* ((tmpdir temporary-file-directory)
  16081. (tmpfile (make-temp-name
  16082. (expand-file-name "orgics" tmpdir)))
  16083. buf rtn b e)
  16084. (with-current-buffer frombuf
  16085. (icalendar-export-region (point-min) (point-max) tmpfile)
  16086. (setq buf (find-buffer-visiting tmpfile))
  16087. (set-buffer buf)
  16088. (goto-char (point-min))
  16089. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16090. (setq b (match-beginning 0)))
  16091. (goto-char (point-max))
  16092. (when (re-search-backward "^END:VEVENT" nil t)
  16093. (setq e (match-end 0)))
  16094. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16095. (kill-buffer buf)
  16096. (delete-file tmpfile)
  16097. rtn))
  16098. (defun org-closest-date (start current prefer)
  16099. "Return closest date to CURRENT starting from START.
  16100. CURRENT and START are both time stamps.
  16101. When PREFER is `past', return a date that is either CURRENT or
  16102. past. When PREFER is `future', return a date that is either
  16103. CURRENT or future.
  16104. Only time stamps with a repeater are modified. Any other time
  16105. stamp stay unchanged. In any case, return value is an absolute
  16106. day number."
  16107. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16108. ;; No repeater. Do not shift time stamp.
  16109. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16110. (let ((value (string-to-number (match-string 1 start)))
  16111. (type (match-string 2 start)))
  16112. (if (= 0 value)
  16113. ;; Repeater with a 0-value is considered as void.
  16114. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16115. (let* ((base (org-date-to-gregorian start))
  16116. (target (org-date-to-gregorian current))
  16117. (sday (calendar-absolute-from-gregorian base))
  16118. (cday (calendar-absolute-from-gregorian target))
  16119. n1 n2)
  16120. ;; If START is already past CURRENT, just return START.
  16121. (if (<= cday sday) sday
  16122. ;; Compute closest date before (N1) and closest date past
  16123. ;; (N2) CURRENT.
  16124. (pcase type
  16125. ("h"
  16126. (let ((missing-hours
  16127. (mod (+ (- (* 24 (- cday sday))
  16128. (nth 2 (org-parse-time-string start)))
  16129. org-extend-today-until)
  16130. value)))
  16131. (setf n1 (if (= missing-hours 0) cday
  16132. (- cday (1+ (/ missing-hours 24)))))
  16133. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16134. ((or "d" "w")
  16135. (let ((value (if (equal type "w") (* 7 value) value)))
  16136. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16137. (setf n2 (+ n1 value))))
  16138. ("m"
  16139. (let* ((add-months
  16140. (lambda (d n)
  16141. ;; Add N months to gregorian date D, i.e.,
  16142. ;; a list (MONTH DAY YEAR). Return a valid
  16143. ;; gregorian date.
  16144. (let ((m (+ (nth 0 d) n)))
  16145. (list (mod m 12)
  16146. (nth 1 d)
  16147. (+ (/ m 12) (nth 2 d))))))
  16148. (months ; Complete months to TARGET.
  16149. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16150. (- (nth 0 target) (nth 0 base))
  16151. ;; If START's day is greater than
  16152. ;; TARGET's, remove incomplete month.
  16153. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16154. value)
  16155. value))
  16156. (before (funcall add-months base months)))
  16157. (setf n1 (calendar-absolute-from-gregorian before))
  16158. (setf n2
  16159. (calendar-absolute-from-gregorian
  16160. (funcall add-months before value)))))
  16161. (_
  16162. (let* ((d (nth 1 base))
  16163. (m (nth 0 base))
  16164. (y (nth 2 base))
  16165. (years ; Complete years to TARGET.
  16166. (* (/ (- (nth 2 target)
  16167. y
  16168. ;; If START's month and day are
  16169. ;; greater than TARGET's, remove
  16170. ;; incomplete year.
  16171. (if (or (> (nth 0 target) m)
  16172. (and (= (nth 0 target) m)
  16173. (> (nth 1 target) d)))
  16174. 0
  16175. 1))
  16176. value)
  16177. value))
  16178. (before (list m d (+ y years))))
  16179. (setf n1 (calendar-absolute-from-gregorian before))
  16180. (setf n2 (calendar-absolute-from-gregorian
  16181. (list m d (+ (nth 2 before) value)))))))
  16182. ;; Handle PREFER parameter, if any.
  16183. (cond
  16184. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16185. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16186. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16187. (defun org-date-to-gregorian (d)
  16188. "Turn any specification of date D into a Gregorian date for the calendar."
  16189. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16190. ((and (listp d) (= (length d) 3)) d)
  16191. ((stringp d)
  16192. (let ((d (org-parse-time-string d)))
  16193. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16194. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16195. (defun org-parse-time-string (s &optional nodefault)
  16196. "Parse the standard Org time string.
  16197. This should be a lot faster than the normal `parse-time-string'.
  16198. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16199. hour and minute fields will be nil if not given."
  16200. (cond ((string-match org-ts-regexp0 s)
  16201. (list 0
  16202. (when (or (match-beginning 8) (not nodefault))
  16203. (string-to-number (or (match-string 8 s) "0")))
  16204. (when (or (match-beginning 7) (not nodefault))
  16205. (string-to-number (or (match-string 7 s) "0")))
  16206. (string-to-number (match-string 4 s))
  16207. (string-to-number (match-string 3 s))
  16208. (string-to-number (match-string 2 s))
  16209. nil nil nil))
  16210. ((string-match "^<[^>]+>$" s)
  16211. (decode-time (seconds-to-time (org-matcher-time s))))
  16212. (t (error "Not a standard Org time string: %s" s))))
  16213. (defun org-timestamp-up (&optional arg)
  16214. "Increase the date item at the cursor by one.
  16215. If the cursor is on the year, change the year. If it is on the month,
  16216. the day or the time, change that.
  16217. With prefix ARG, change by that many units."
  16218. (interactive "p")
  16219. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16220. (defun org-timestamp-down (&optional arg)
  16221. "Decrease the date item at the cursor by one.
  16222. If the cursor is on the year, change the year. If it is on the month,
  16223. the day or the time, change that.
  16224. With prefix ARG, change by that many units."
  16225. (interactive "p")
  16226. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16227. (defun org-timestamp-up-day (&optional arg)
  16228. "Increase the date in the time stamp by one day.
  16229. With prefix ARG, change that many days."
  16230. (interactive "p")
  16231. (if (and (not (org-at-timestamp-p 'lax))
  16232. (org-at-heading-p))
  16233. (org-todo 'up)
  16234. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16235. (defun org-timestamp-down-day (&optional arg)
  16236. "Decrease the date in the time stamp by one day.
  16237. With prefix ARG, change that many days."
  16238. (interactive "p")
  16239. (if (and (not (org-at-timestamp-p 'lax))
  16240. (org-at-heading-p))
  16241. (org-todo 'down)
  16242. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16243. (defun org-at-timestamp-p (&optional extended)
  16244. "Non-nil if point is inside a timestamp.
  16245. By default, the function only consider syntactically valid active
  16246. timestamps. However, the caller may have a broader definition
  16247. for timestamps. As a consequence, optional argument EXTENDED can
  16248. be set to the following values
  16249. `inactive'
  16250. Include also syntactically valid inactive timestamps.
  16251. `agenda'
  16252. Include timestamps allowed in Agenda, i.e., those in
  16253. properties drawers, planning lines and clock lines.
  16254. `lax'
  16255. Ignore context. The function matches any part of the
  16256. document looking like a timestamp. This includes comments,
  16257. example blocks...
  16258. For backward-compatibility with Org 9.0, every other non-nil
  16259. value is equivalent to `inactive'.
  16260. When at a timestamp, return the position of the point as a symbol
  16261. among `bracket', `after', `year', `month', `hour', `minute',
  16262. `day' or a number of character from the last know part of the
  16263. time stamp.
  16264. When matching, the match groups are the following:
  16265. group 1: year
  16266. group 2: month
  16267. group 3: day number
  16268. group 4: day name
  16269. group 5: hours, if any
  16270. group 6: minutes, if any"
  16271. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16272. (pos (point))
  16273. (match?
  16274. (let ((boundaries (org-in-regexp regexp)))
  16275. (save-match-data
  16276. (cond ((null boundaries) nil)
  16277. ((eq extended 'lax) t)
  16278. (t
  16279. (or (and (eq extended 'agenda)
  16280. (or (org-at-planning-p)
  16281. (org-at-property-p)
  16282. (and (bound-and-true-p
  16283. org-agenda-include-inactive-timestamps)
  16284. (org-at-clock-log-p))))
  16285. (eq 'timestamp
  16286. (save-excursion
  16287. (when (= pos (cdr boundaries)) (forward-char -1))
  16288. (org-element-type (org-element-context)))))))))))
  16289. (cond
  16290. ((not match?) nil)
  16291. ((= pos (match-beginning 0)) 'bracket)
  16292. ;; Distinguish location right before the closing bracket from
  16293. ;; right after it.
  16294. ((= pos (1- (match-end 0))) 'bracket)
  16295. ((= pos (match-end 0)) 'after)
  16296. ((org-pos-in-match-range pos 2) 'year)
  16297. ((org-pos-in-match-range pos 3) 'month)
  16298. ((org-pos-in-match-range pos 7) 'hour)
  16299. ((org-pos-in-match-range pos 8) 'minute)
  16300. ((or (org-pos-in-match-range pos 4)
  16301. (org-pos-in-match-range pos 5)) 'day)
  16302. ((and (> pos (or (match-end 8) (match-end 5)))
  16303. (< pos (match-end 0)))
  16304. (- pos (or (match-end 8) (match-end 5))))
  16305. (t 'day))))
  16306. (defun org-toggle-timestamp-type ()
  16307. "Toggle the type (<active> or [inactive]) of a time stamp."
  16308. (interactive)
  16309. (when (org-at-timestamp-p 'lax)
  16310. (let ((beg (match-beginning 0)) (end (match-end 0))
  16311. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16312. (save-excursion
  16313. (goto-char beg)
  16314. (while (re-search-forward "[][<>]" end t)
  16315. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16316. t t)))
  16317. (message "Timestamp is now %sactive"
  16318. (if (equal (char-after beg) ?<) "" "in")))))
  16319. (defun org-at-clock-log-p ()
  16320. "Non-nil if point is on a clock log line."
  16321. (and (org-match-line org-clock-line-re)
  16322. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16323. (defvar org-clock-history) ; defined in org-clock.el
  16324. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16325. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16326. "Change the date in the time stamp at point.
  16327. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16328. `year', `minute', `second'. If WHAT is not given, the cursor position
  16329. in the timestamp determines what will be changed.
  16330. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16331. (let ((origin (point))
  16332. (timestamp? (org-at-timestamp-p 'lax))
  16333. origin-cat
  16334. with-hm inactive
  16335. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16336. extra rem
  16337. ts time time0 fixnext clrgx)
  16338. (unless timestamp? (user-error "Not at a timestamp"))
  16339. (if (and (not what) (eq timestamp? 'bracket))
  16340. (org-toggle-timestamp-type)
  16341. ;; Point isn't on brackets. Remember the part of the time-stamp
  16342. ;; the point was in. Indeed, size of time-stamps may change,
  16343. ;; but point must be kept in the same category nonetheless.
  16344. (setq origin-cat timestamp?)
  16345. (when (and (not what) (not (eq timestamp? 'day))
  16346. org-display-custom-times
  16347. (get-text-property (point) 'display)
  16348. (not (get-text-property (1- (point)) 'display)))
  16349. (setq timestamp? 'day))
  16350. (setq timestamp? (or what timestamp?)
  16351. inactive (= (char-after (match-beginning 0)) ?\[)
  16352. ts (match-string 0))
  16353. (replace-match "")
  16354. (when (string-match
  16355. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16356. ts)
  16357. (setq extra (match-string 1 ts))
  16358. (when suppress-tmp-delay
  16359. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16360. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16361. (setq with-hm t))
  16362. (setq time0 (org-parse-time-string ts))
  16363. (when (and updown
  16364. (eq timestamp? 'minute)
  16365. (not current-prefix-arg))
  16366. ;; This looks like s-up and s-down. Change by one rounding step.
  16367. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16368. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16369. (setcar (cdr time0) (+ (nth 1 time0)
  16370. (if (> n 0) (- rem) (- dm rem))))))
  16371. (setq time
  16372. (apply #'encode-time
  16373. (or (car time0) 0)
  16374. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16375. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16376. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16377. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16378. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16379. (nthcdr 6 time0)))
  16380. (when (and (memq timestamp? '(hour minute))
  16381. extra
  16382. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16383. (setq extra (org-modify-ts-extra
  16384. extra
  16385. (if (eq timestamp? 'hour) 2 5)
  16386. n dm)))
  16387. (when (integerp timestamp?)
  16388. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16389. (when (eq what 'calendar)
  16390. (let ((cal-date (org-get-date-from-calendar)))
  16391. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16392. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16393. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16394. (setcar time0 (or (car time0) 0))
  16395. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16396. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16397. (setq time (apply 'encode-time time0))))
  16398. ;; Insert the new time-stamp, and ensure point stays in the same
  16399. ;; category as before (i.e. not after the last position in that
  16400. ;; category).
  16401. (let ((pos (point)))
  16402. ;; Stay before inserted string. `save-excursion' is of no use.
  16403. (setq org-last-changed-timestamp
  16404. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16405. (goto-char pos))
  16406. (save-match-data
  16407. (looking-at org-ts-regexp3)
  16408. (goto-char
  16409. (pcase origin-cat
  16410. ;; `day' category ends before `hour' if any, or at the end
  16411. ;; of the day name.
  16412. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16413. (`hour (min (match-end 7) origin))
  16414. (`minute (min (1- (match-end 8)) origin))
  16415. ((pred integerp) (min (1- (match-end 0)) origin))
  16416. ;; Point was right after the time-stamp. However, the
  16417. ;; time-stamp length might have changed, so refer to
  16418. ;; (match-end 0) instead.
  16419. (`after (match-end 0))
  16420. ;; `year' and `month' have both fixed size: point couldn't
  16421. ;; have moved into another part.
  16422. (_ origin))))
  16423. ;; Update clock if on a CLOCK line.
  16424. (org-clock-update-time-maybe)
  16425. ;; Maybe adjust the closest clock in `org-clock-history'
  16426. (when org-clock-adjust-closest
  16427. (if (not (and (org-at-clock-log-p)
  16428. (< 1 (length (delq nil (mapcar 'marker-position
  16429. org-clock-history))))))
  16430. (message "No clock to adjust")
  16431. (cond ((save-excursion ; fix previous clock?
  16432. (re-search-backward org-ts-regexp0 nil t)
  16433. (looking-back (concat org-clock-string " \\[")
  16434. (line-beginning-position)))
  16435. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16436. ((save-excursion ; fix next clock?
  16437. (re-search-backward org-ts-regexp0 nil t)
  16438. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16439. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16440. (save-window-excursion
  16441. ;; Find closest clock to point, adjust the previous/next one in history
  16442. (let* ((p (save-excursion (org-back-to-heading t)))
  16443. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16444. (clfixnth
  16445. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16446. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16447. (if (not clfixpos)
  16448. (message "No clock to adjust")
  16449. (save-excursion
  16450. (org-goto-marker-or-bmk clfixpos)
  16451. (org-show-subtree)
  16452. (when (re-search-forward clrgx nil t)
  16453. (goto-char (match-beginning 1))
  16454. (let (org-clock-adjust-closest)
  16455. (org-timestamp-change n timestamp? updown))
  16456. (message "Clock adjusted in %s for heading: %s"
  16457. (file-name-nondirectory (buffer-file-name))
  16458. (org-get-heading t t)))))))))
  16459. ;; Try to recenter the calendar window, if any.
  16460. (when (and org-calendar-follow-timestamp-change
  16461. (get-buffer-window "*Calendar*" t)
  16462. (memq timestamp? '(day month year)))
  16463. (org-recenter-calendar (time-to-days time))))))
  16464. (defun org-modify-ts-extra (s pos n dm)
  16465. "Change the different parts of the lead-time and repeat fields in timestamp."
  16466. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16467. ng h m new rem)
  16468. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16469. (cond
  16470. ((or (org-pos-in-match-range pos 2)
  16471. (org-pos-in-match-range pos 3))
  16472. (setq m (string-to-number (match-string 3 s))
  16473. h (string-to-number (match-string 2 s)))
  16474. (if (org-pos-in-match-range pos 2)
  16475. (setq h (+ h n))
  16476. (setq n (* dm (with-no-warnings (signum n))))
  16477. (unless (= 0 (setq rem (% m dm)))
  16478. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16479. (setq m (+ m n)))
  16480. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16481. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16482. (setq h (mod h 24))
  16483. (setq ng 1 new (format "-%02d:%02d" h m)))
  16484. ((org-pos-in-match-range pos 6)
  16485. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16486. ((org-pos-in-match-range pos 5)
  16487. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16488. ((org-pos-in-match-range pos 9)
  16489. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16490. ((org-pos-in-match-range pos 8)
  16491. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16492. (when ng
  16493. (setq s (concat
  16494. (substring s 0 (match-beginning ng))
  16495. new
  16496. (substring s (match-end ng))))))
  16497. s))
  16498. (defun org-recenter-calendar (d)
  16499. "If the calendar is visible, recenter it to date D."
  16500. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16501. (when cwin
  16502. (let ((calendar-move-hook nil))
  16503. (with-selected-window cwin
  16504. (calendar-goto-date
  16505. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16506. (defun org-goto-calendar (&optional arg)
  16507. "Go to the Emacs calendar at the current date.
  16508. If there is a time stamp in the current line, go to that date.
  16509. A prefix ARG can be used to force the current date."
  16510. (interactive "P")
  16511. (let ((calendar-move-hook nil)
  16512. (calendar-view-holidays-initially-flag nil)
  16513. (calendar-view-diary-initially-flag nil)
  16514. diff)
  16515. (when (or (org-at-timestamp-p 'lax)
  16516. (org-match-line (concat ".*" org-ts-regexp)))
  16517. (let ((d1 (time-to-days (current-time)))
  16518. (d2 (time-to-days
  16519. (org-time-string-to-time (match-string 1)))))
  16520. (setq diff (- d2 d1))))
  16521. (calendar)
  16522. (calendar-goto-today)
  16523. (when (and diff (not arg)) (calendar-forward-day diff))))
  16524. (defun org-get-date-from-calendar ()
  16525. "Return a list (month day year) of date at point in calendar."
  16526. (with-current-buffer "*Calendar*"
  16527. (save-match-data
  16528. (calendar-cursor-to-date))))
  16529. (defun org-date-from-calendar ()
  16530. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16531. If there is already a time stamp at the cursor position, update it."
  16532. (interactive)
  16533. (if (org-at-timestamp-p 'lax)
  16534. (org-timestamp-change 0 'calendar)
  16535. (let ((cal-date (org-get-date-from-calendar)))
  16536. (org-insert-time-stamp
  16537. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16538. (defcustom org-effort-durations
  16539. `(("min" . 1)
  16540. ("h" . 60)
  16541. ("d" . ,(* 60 8))
  16542. ("w" . ,(* 60 8 5))
  16543. ("m" . ,(* 60 8 5 4))
  16544. ("y" . ,(* 60 8 5 40)))
  16545. "Conversion factor to minutes for an effort modifier.
  16546. Each entry has the form (MODIFIER . MINUTES).
  16547. In an effort string, a number followed by MODIFIER is multiplied
  16548. by the specified number of MINUTES to obtain an effort in
  16549. minutes.
  16550. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16551. effort string \"2hours\" is equivalent to 120 minutes."
  16552. :group 'org-agenda
  16553. :version "26.1"
  16554. :package-version '(Org . "8.3")
  16555. :type '(alist :key-type (string :tag "Modifier")
  16556. :value-type (number :tag "Minutes")))
  16557. (defcustom org-image-actual-width t
  16558. "Should we use the actual width of images when inlining them?
  16559. When set to t, always use the image width.
  16560. When set to a number, use imagemagick (when available) to set
  16561. the image's width to this value.
  16562. When set to a number in a list, try to get the width from any
  16563. #+ATTR.* keyword if it matches a width specification like
  16564. #+ATTR_HTML: :width 300px
  16565. and fall back on that number if none is found.
  16566. When set to nil, try to get the width from an #+ATTR.* keyword
  16567. and fall back on the original width if none is found.
  16568. This requires Emacs >= 24.1, build with imagemagick support."
  16569. :group 'org-appearance
  16570. :version "24.4"
  16571. :package-version '(Org . "8.0")
  16572. :type '(choice
  16573. (const :tag "Use the image width" t)
  16574. (integer :tag "Use a number of pixels")
  16575. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16576. (const :tag "Use #+ATTR* or don't resize" nil)))
  16577. (defcustom org-agenda-inhibit-startup nil
  16578. "Inhibit startup when preparing agenda buffers.
  16579. When this variable is t, the initialization of the Org agenda
  16580. buffers is inhibited: e.g. the visibility state is not set, the
  16581. tables are not re-aligned, etc."
  16582. :type 'boolean
  16583. :version "24.3"
  16584. :group 'org-agenda)
  16585. (defcustom org-agenda-ignore-properties nil
  16586. "Avoid updating text properties when building the agenda.
  16587. Properties are used to prepare buffers for effort estimates,
  16588. appointments, statistics and subtree-local categories.
  16589. If you don't use these in the agenda, you can add them to this
  16590. list and agenda building will be a bit faster.
  16591. The value is a list, with zero or more of the symbols `effort', `appt',
  16592. `stats' or `category'."
  16593. :type '(set :greedy t
  16594. (const effort)
  16595. (const appt)
  16596. (const stats)
  16597. (const category))
  16598. :version "26.1"
  16599. :package-version '(Org . "8.3")
  16600. :group 'org-agenda)
  16601. ;;;; Files
  16602. (defun org-save-all-org-buffers ()
  16603. "Save all Org buffers without user confirmation."
  16604. (interactive)
  16605. (message "Saving all Org buffers...")
  16606. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16607. (when (featurep 'org-id) (org-id-locations-save))
  16608. (message "Saving all Org buffers... done"))
  16609. (defun org-revert-all-org-buffers ()
  16610. "Revert all Org buffers.
  16611. Prompt for confirmation when there are unsaved changes.
  16612. Be sure you know what you are doing before letting this function
  16613. overwrite your changes.
  16614. This function is useful in a setup where one tracks org files
  16615. with a version control system, to revert on one machine after pulling
  16616. changes from another. I believe the procedure must be like this:
  16617. 1. M-x org-save-all-org-buffers
  16618. 2. Pull changes from the other machine, resolve conflicts
  16619. 3. M-x org-revert-all-org-buffers"
  16620. (interactive)
  16621. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16622. (user-error "Abort"))
  16623. (save-excursion
  16624. (save-window-excursion
  16625. (dolist (b (buffer-list))
  16626. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16627. (with-current-buffer b buffer-file-name))
  16628. (pop-to-buffer-same-window b)
  16629. (revert-buffer t 'no-confirm)))
  16630. (when (and (featurep 'org-id) org-id-track-globally)
  16631. (org-id-locations-load)))))
  16632. ;;;; Agenda files
  16633. ;;;###autoload
  16634. (defun org-switchb (&optional arg)
  16635. "Switch between Org buffers.
  16636. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16637. With `\\[universal-argument] \\[universal-argument]' \
  16638. prefix, restrict available buffers to agenda files."
  16639. (interactive "P")
  16640. (let ((blist (org-buffer-list
  16641. (cond ((equal arg '(4)) 'files)
  16642. ((equal arg '(16)) 'agenda)))))
  16643. (pop-to-buffer-same-window
  16644. (completing-read "Org buffer: "
  16645. (mapcar #'list (mapcar #'buffer-name blist))
  16646. nil t))))
  16647. (defun org-buffer-list (&optional predicate exclude-tmp)
  16648. "Return a list of Org buffers.
  16649. PREDICATE can be `export', `files' or `agenda'.
  16650. export restrict the list to Export buffers.
  16651. files restrict the list to buffers visiting Org files.
  16652. agenda restrict the list to buffers visiting agenda files.
  16653. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16654. (let* ((bfn nil)
  16655. (agenda-files (and (eq predicate 'agenda)
  16656. (mapcar 'file-truename (org-agenda-files t))))
  16657. (filter
  16658. (cond
  16659. ((eq predicate 'files)
  16660. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16661. ((eq predicate 'export)
  16662. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16663. ((eq predicate 'agenda)
  16664. (lambda (b)
  16665. (with-current-buffer b
  16666. (and (derived-mode-p 'org-mode)
  16667. (setq bfn (buffer-file-name b))
  16668. (member (file-truename bfn) agenda-files)))))
  16669. (t (lambda (b) (with-current-buffer b
  16670. (or (derived-mode-p 'org-mode)
  16671. (string-match "\\*Org .*Export"
  16672. (buffer-name b)))))))))
  16673. (delq nil
  16674. (mapcar
  16675. (lambda(b)
  16676. (if (and (funcall filter b)
  16677. (or (not exclude-tmp)
  16678. (not (string-match "tmp" (buffer-name b)))))
  16679. b
  16680. nil))
  16681. (buffer-list)))))
  16682. (defun org-agenda-files (&optional unrestricted archives)
  16683. "Get the list of agenda files.
  16684. Optional UNRESTRICTED means return the full list even if a restriction
  16685. is currently in place.
  16686. When ARCHIVES is t, include all archive files that are really being
  16687. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16688. `org-agenda-archives-mode' is t."
  16689. (let ((files
  16690. (cond
  16691. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16692. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16693. ((listp org-agenda-files) org-agenda-files)
  16694. (t (error "Invalid value of `org-agenda-files'")))))
  16695. (setq files (apply 'append
  16696. (mapcar (lambda (f)
  16697. (if (file-directory-p f)
  16698. (directory-files
  16699. f t org-agenda-file-regexp)
  16700. (list f)))
  16701. files)))
  16702. (when org-agenda-skip-unavailable-files
  16703. (setq files (delq nil
  16704. (mapcar (function
  16705. (lambda (file)
  16706. (and (file-readable-p file) file)))
  16707. files))))
  16708. (when (or (eq archives t)
  16709. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16710. (setq files (org-add-archive-files files)))
  16711. files))
  16712. (defun org-agenda-file-p (&optional file)
  16713. "Return non-nil, if FILE is an agenda file.
  16714. If FILE is omitted, use the file associated with the current
  16715. buffer."
  16716. (let ((fname (or file (buffer-file-name))))
  16717. (and fname
  16718. (member (file-truename fname)
  16719. (mapcar #'file-truename (org-agenda-files t))))))
  16720. (defun org-edit-agenda-file-list ()
  16721. "Edit the list of agenda files.
  16722. Depending on setup, this either uses customize to edit the variable
  16723. `org-agenda-files', or it visits the file that is holding the list. In the
  16724. latter case, the buffer is set up in a way that saving it automatically kills
  16725. the buffer and restores the previous window configuration."
  16726. (interactive)
  16727. (if (stringp org-agenda-files)
  16728. (let ((cw (current-window-configuration)))
  16729. (find-file org-agenda-files)
  16730. (setq-local org-window-configuration cw)
  16731. (add-hook 'after-save-hook
  16732. (lambda ()
  16733. (set-window-configuration
  16734. (prog1 org-window-configuration
  16735. (kill-buffer (current-buffer))))
  16736. (org-install-agenda-files-menu)
  16737. (message "New agenda file list installed"))
  16738. nil 'local)
  16739. (message "%s" (substitute-command-keys
  16740. "Edit list and finish with \\[save-buffer]")))
  16741. (customize-variable 'org-agenda-files)))
  16742. (defun org-store-new-agenda-file-list (list)
  16743. "Set new value for the agenda file list and save it correctly."
  16744. (if (stringp org-agenda-files)
  16745. (let ((fe (org-read-agenda-file-list t)) b u)
  16746. (while (setq b (find-buffer-visiting org-agenda-files))
  16747. (kill-buffer b))
  16748. (with-temp-file org-agenda-files
  16749. (insert
  16750. (mapconcat
  16751. (lambda (f) ;; Keep un-expanded entries.
  16752. (if (setq u (assoc f fe))
  16753. (cdr u)
  16754. f))
  16755. list "\n")
  16756. "\n")))
  16757. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16758. (org-insert-mode-line-in-empty-file nil))
  16759. (setq org-agenda-files list)
  16760. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16761. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16762. "Read the list of agenda files from a file.
  16763. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16764. filenames, used by `org-store-new-agenda-file-list' to write back
  16765. un-expanded file names."
  16766. (when (file-directory-p org-agenda-files)
  16767. (error "`org-agenda-files' cannot be a single directory"))
  16768. (when (stringp org-agenda-files)
  16769. (with-temp-buffer
  16770. (insert-file-contents org-agenda-files)
  16771. (mapcar
  16772. (lambda (f)
  16773. (let ((e (expand-file-name (substitute-in-file-name f)
  16774. org-directory)))
  16775. (if pair-with-expansion
  16776. (cons e f)
  16777. e)))
  16778. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16779. ;;;###autoload
  16780. (defun org-cycle-agenda-files ()
  16781. "Cycle through the files in `org-agenda-files'.
  16782. If the current buffer visits an agenda file, find the next one in the list.
  16783. If the current buffer does not, find the first agenda file."
  16784. (interactive)
  16785. (let* ((fs (or (org-agenda-files t)
  16786. (user-error "No agenda files")))
  16787. (files (copy-sequence fs))
  16788. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16789. file)
  16790. (when tcf
  16791. (while (and (setq file (pop files))
  16792. (not (equal (file-truename file) tcf)))))
  16793. (find-file (car (or files fs)))
  16794. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16795. (defun org-agenda-file-to-front (&optional to-end)
  16796. "Move/add the current file to the top of the agenda file list.
  16797. If the file is not present in the list, it is added to the front. If it is
  16798. present, it is moved there. With optional argument TO-END, add/move to the
  16799. end of the list."
  16800. (interactive "P")
  16801. (let ((org-agenda-skip-unavailable-files nil)
  16802. (file-alist (mapcar (lambda (x)
  16803. (cons (file-truename x) x))
  16804. (org-agenda-files t)))
  16805. (ctf (file-truename
  16806. (or buffer-file-name
  16807. (user-error "Please save the current buffer to a file"))))
  16808. x had)
  16809. (setq x (assoc ctf file-alist) had x)
  16810. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16811. (if to-end
  16812. (setq file-alist (append (delq x file-alist) (list x)))
  16813. (setq file-alist (cons x (delq x file-alist))))
  16814. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16815. (org-install-agenda-files-menu)
  16816. (message "File %s to %s of agenda file list"
  16817. (if had "moved" "added") (if to-end "end" "front"))))
  16818. (defun org-remove-file (&optional file)
  16819. "Remove current file from the list of files in variable `org-agenda-files'.
  16820. These are the files which are being checked for agenda entries.
  16821. Optional argument FILE means use this file instead of the current."
  16822. (interactive)
  16823. (let* ((org-agenda-skip-unavailable-files nil)
  16824. (file (or file buffer-file-name
  16825. (user-error "Current buffer does not visit a file")))
  16826. (true-file (file-truename file))
  16827. (afile (abbreviate-file-name file))
  16828. (files (delq nil (mapcar
  16829. (lambda (x)
  16830. (unless (equal true-file
  16831. (file-truename x))
  16832. x))
  16833. (org-agenda-files t)))))
  16834. (if (not (= (length files) (length (org-agenda-files t))))
  16835. (progn
  16836. (org-store-new-agenda-file-list files)
  16837. (org-install-agenda-files-menu)
  16838. (message "Removed from Org Agenda list: %s" afile))
  16839. (message "File was not in list: %s (not removed)" afile))))
  16840. (defun org-file-menu-entry (file)
  16841. (vector file (list 'find-file file) t))
  16842. (defun org-check-agenda-file (file)
  16843. "Make sure FILE exists. If not, ask user what to do."
  16844. (unless (file-exists-p file)
  16845. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16846. (abbreviate-file-name file))
  16847. (let ((r (downcase (read-char-exclusive))))
  16848. (cond
  16849. ((equal r ?r)
  16850. (org-remove-file file)
  16851. (throw 'nextfile t))
  16852. (t (user-error "Abort"))))))
  16853. (defun org-get-agenda-file-buffer (file)
  16854. "Get an agenda buffer visiting FILE.
  16855. If the buffer needs to be created, add it to the list of buffers
  16856. which might be released later."
  16857. (let ((buf (org-find-base-buffer-visiting file)))
  16858. (if buf
  16859. buf ; just return it
  16860. ;; Make a new buffer and remember it
  16861. (setq buf (find-file-noselect file))
  16862. (when buf (push buf org-agenda-new-buffers))
  16863. buf)))
  16864. (defun org-release-buffers (blist)
  16865. "Release all buffers in list, asking the user for confirmation when needed.
  16866. When a buffer is unmodified, it is just killed. When modified, it is saved
  16867. \(if the user agrees) and then killed."
  16868. (let (file)
  16869. (dolist (buf blist)
  16870. (setq file (buffer-file-name buf))
  16871. (when (and (buffer-modified-p buf)
  16872. file
  16873. (y-or-n-p (format "Save file %s? " file)))
  16874. (with-current-buffer buf (save-buffer)))
  16875. (kill-buffer buf))))
  16876. (defun org-agenda-prepare-buffers (files)
  16877. "Create buffers for all agenda files, protect archived trees and comments."
  16878. (interactive)
  16879. (let ((pa '(:org-archived t))
  16880. (pc '(:org-comment t))
  16881. (pall '(:org-archived t :org-comment t))
  16882. (inhibit-read-only t)
  16883. (org-inhibit-startup org-agenda-inhibit-startup)
  16884. (rea (concat ":" org-archive-tag ":"))
  16885. re pos)
  16886. (setq org-tag-alist-for-agenda nil
  16887. org-tag-groups-alist-for-agenda nil)
  16888. (save-excursion
  16889. (save-restriction
  16890. (dolist (file files)
  16891. (catch 'nextfile
  16892. (if (bufferp file)
  16893. (set-buffer file)
  16894. (org-check-agenda-file file)
  16895. (set-buffer (org-get-agenda-file-buffer file)))
  16896. (widen)
  16897. (org-set-regexps-and-options 'tags-only)
  16898. (setq pos (point))
  16899. (or (memq 'category org-agenda-ignore-properties)
  16900. (org-refresh-category-properties))
  16901. (or (memq 'stats org-agenda-ignore-properties)
  16902. (org-refresh-stats-properties))
  16903. (or (memq 'effort org-agenda-ignore-properties)
  16904. (org-refresh-effort-properties))
  16905. (or (memq 'appt org-agenda-ignore-properties)
  16906. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16907. (setq org-todo-keywords-for-agenda
  16908. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16909. (setq org-done-keywords-for-agenda
  16910. (append org-done-keywords-for-agenda org-done-keywords))
  16911. (setq org-todo-keyword-alist-for-agenda
  16912. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16913. (setq org-tag-alist-for-agenda
  16914. (org-uniquify
  16915. (append org-tag-alist-for-agenda
  16916. org-current-tag-alist)))
  16917. ;; Merge current file's tag groups into global
  16918. ;; `org-tag-groups-alist-for-agenda'.
  16919. (when org-group-tags
  16920. (dolist (alist org-tag-groups-alist)
  16921. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16922. (if old
  16923. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16924. (push alist org-tag-groups-alist-for-agenda)))))
  16925. (org-with-silent-modifications
  16926. (save-excursion
  16927. (remove-text-properties (point-min) (point-max) pall)
  16928. (when org-agenda-skip-archived-trees
  16929. (goto-char (point-min))
  16930. (while (re-search-forward rea nil t)
  16931. (when (org-at-heading-p t)
  16932. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16933. (goto-char (point-min))
  16934. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16935. (while (re-search-forward re nil t)
  16936. (when (save-match-data (org-in-commented-heading-p t))
  16937. (add-text-properties
  16938. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16939. (goto-char pos)))))
  16940. (setq org-todo-keywords-for-agenda
  16941. (org-uniquify org-todo-keywords-for-agenda))
  16942. (setq org-todo-keyword-alist-for-agenda
  16943. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16944. ;;;; CDLaTeX minor mode
  16945. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16946. "Keymap for the minor `org-cdlatex-mode'.")
  16947. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16948. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16949. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16950. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16951. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16952. (defvar org-cdlatex-texmathp-advice-is-done nil
  16953. "Flag remembering if we have applied the advice to texmathp already.")
  16954. (define-minor-mode org-cdlatex-mode
  16955. "Toggle the minor `org-cdlatex-mode'.
  16956. This mode supports entering LaTeX environment and math in LaTeX fragments
  16957. in Org mode.
  16958. \\{org-cdlatex-mode-map}"
  16959. nil " OCDL" nil
  16960. (when org-cdlatex-mode
  16961. (require 'cdlatex)
  16962. (run-hooks 'cdlatex-mode-hook)
  16963. (cdlatex-compute-tables))
  16964. (unless org-cdlatex-texmathp-advice-is-done
  16965. (setq org-cdlatex-texmathp-advice-is-done t)
  16966. (defadvice texmathp (around org-math-always-on activate)
  16967. "Always return t in Org buffers.
  16968. This is because we want to insert math symbols without dollars even outside
  16969. the LaTeX math segments. If Org mode thinks that point is actually inside
  16970. an embedded LaTeX fragment, let `texmathp' do its job.
  16971. `\\[org-cdlatex-mode-map]'"
  16972. (interactive)
  16973. (let (p)
  16974. (cond
  16975. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16976. ((eq this-command 'cdlatex-math-symbol)
  16977. (setq ad-return-value t
  16978. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16979. (t
  16980. (let ((p (org-inside-LaTeX-fragment-p)))
  16981. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16982. (setq ad-return-value t
  16983. texmathp-why '("Org mode embedded math" . 0))
  16984. (when p ad-do-it)))))))))
  16985. (defun turn-on-org-cdlatex ()
  16986. "Unconditionally turn on `org-cdlatex-mode'."
  16987. (org-cdlatex-mode 1))
  16988. (defun org-try-cdlatex-tab ()
  16989. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16990. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16991. - inside a LaTeX fragment, or
  16992. - after the first word in a line, where an abbreviation expansion could
  16993. insert a LaTeX environment."
  16994. (when org-cdlatex-mode
  16995. (cond
  16996. ;; Before any word on the line: No expansion possible.
  16997. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16998. ;; Just after first word on the line: Expand it. Make sure it
  16999. ;; cannot happen on headlines, though.
  17000. ((save-excursion
  17001. (skip-chars-backward "a-zA-Z0-9*")
  17002. (skip-chars-backward " \t")
  17003. (and (bolp) (not (org-at-heading-p))))
  17004. (cdlatex-tab) t)
  17005. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17006. (defun org-cdlatex-underscore-caret (&optional _arg)
  17007. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17008. Revert to the normal definition outside of these fragments."
  17009. (interactive "P")
  17010. (if (org-inside-LaTeX-fragment-p)
  17011. (call-interactively 'cdlatex-sub-superscript)
  17012. (let (org-cdlatex-mode)
  17013. (call-interactively (key-binding (vector last-input-event))))))
  17014. (defun org-cdlatex-math-modify (&optional _arg)
  17015. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17016. Revert to the normal definition outside of these fragments."
  17017. (interactive "P")
  17018. (if (org-inside-LaTeX-fragment-p)
  17019. (call-interactively 'cdlatex-math-modify)
  17020. (let (org-cdlatex-mode)
  17021. (call-interactively (key-binding (vector last-input-event))))))
  17022. (defun org-cdlatex-environment-indent (&optional environment item)
  17023. "Execute `cdlatex-environment' and indent the inserted environment.
  17024. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17025. The inserted environment is indented to current indentation
  17026. unless point is at the beginning of the line, in which the
  17027. environment remains unintended."
  17028. (interactive)
  17029. ;; cdlatex-environment always return nil. Therefore, capture output
  17030. ;; first and determine if an environment was selected.
  17031. (let* ((beg (point-marker))
  17032. (end (copy-marker (point) t))
  17033. (inserted (progn
  17034. (ignore-errors (cdlatex-environment environment item))
  17035. (< beg end)))
  17036. ;; Figure out how many lines to move forward after the
  17037. ;; environment has been inserted.
  17038. (lines (when inserted
  17039. (save-excursion
  17040. (- (cl-loop while (< beg (point))
  17041. with x = 0
  17042. do (forward-line -1)
  17043. (cl-incf x)
  17044. finally return x)
  17045. (if (progn (goto-char beg)
  17046. (and (progn (skip-chars-forward " \t") (eolp))
  17047. (progn (skip-chars-backward " \t") (bolp))))
  17048. 1 0)))))
  17049. (env (org-trim (delete-and-extract-region beg end))))
  17050. (when inserted
  17051. ;; Get indentation of next line unless at column 0.
  17052. (let ((ind (if (bolp) 0
  17053. (save-excursion
  17054. (org-return-indent)
  17055. (prog1 (org-get-indentation)
  17056. (when (progn (skip-chars-forward " \t") (eolp))
  17057. (delete-region beg (point)))))))
  17058. (bol (progn (skip-chars-backward " \t") (bolp))))
  17059. ;; Insert a newline before environment unless at column zero
  17060. ;; to "escape" the current line. Insert a newline if
  17061. ;; something is one the same line as \end{ENVIRONMENT}.
  17062. (insert
  17063. (concat (unless bol "\n") env
  17064. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17065. (unless (zerop ind)
  17066. (save-excursion
  17067. (goto-char beg)
  17068. (while (< (point) end)
  17069. (unless (eolp) (indent-line-to ind))
  17070. (forward-line))))
  17071. (goto-char beg)
  17072. (forward-line lines)
  17073. (indent-line-to ind)))
  17074. (set-marker beg nil)
  17075. (set-marker end nil)))
  17076. ;;;; LaTeX fragments
  17077. (defun org-inside-LaTeX-fragment-p ()
  17078. "Test if point is inside a LaTeX fragment.
  17079. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17080. sequence appearing also before point.
  17081. Even though the matchers for math are configurable, this function assumes
  17082. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17083. delimiters are skipped when they have been removed by customization.
  17084. The return value is nil, or a cons cell with the delimiter and the
  17085. position of this delimiter.
  17086. This function does a reasonably good job, but can locally be fooled by
  17087. for example currency specifications. For example it will assume being in
  17088. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17089. fragments that are properly closed, but during editing, we have to live
  17090. with the uncertainty caused by missing closing delimiters. This function
  17091. looks only before point, not after."
  17092. (catch 'exit
  17093. (let ((pos (point))
  17094. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17095. (lim (progn
  17096. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17097. (point)))
  17098. dd-on str (start 0) m re)
  17099. (goto-char pos)
  17100. (when dodollar
  17101. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17102. re (nth 1 (assoc "$" org-latex-regexps)))
  17103. (while (string-match re str start)
  17104. (cond
  17105. ((= (match-end 0) (length str))
  17106. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17107. ((= (match-end 0) (- (length str) 5))
  17108. (throw 'exit nil))
  17109. (t (setq start (match-end 0))))))
  17110. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17111. (goto-char pos)
  17112. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17113. (and (match-beginning 2) (throw 'exit nil))
  17114. ;; count $$
  17115. (while (re-search-backward "\\$\\$" lim t)
  17116. (setq dd-on (not dd-on)))
  17117. (goto-char pos)
  17118. (when dd-on (cons "$$" m))))))
  17119. (defun org-inside-latex-macro-p ()
  17120. "Is point inside a LaTeX macro or its arguments?"
  17121. (save-match-data
  17122. (org-in-regexp
  17123. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17124. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17125. "Build an overlay between BEG and END using IMAGE file.
  17126. Argument IMAGETYPE is the extension of the displayed image,
  17127. as a string. It defaults to \"png\"."
  17128. (let ((ov (make-overlay beg end))
  17129. (imagetype (or (intern imagetype) 'png)))
  17130. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17131. (overlay-put ov 'evaporate t)
  17132. (overlay-put ov
  17133. 'modification-hooks
  17134. (list (lambda (o _flag _beg _end &optional _l)
  17135. (delete-overlay o))))
  17136. (overlay-put ov
  17137. 'display
  17138. (list 'image :type imagetype :file image :ascent 'center))))
  17139. (defun org--list-latex-overlays (&optional beg end)
  17140. "List all Org LaTeX overlays in current buffer.
  17141. Limit to overlays between BEG and END when those are provided."
  17142. (cl-remove-if-not
  17143. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17144. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17145. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17146. "Remove all overlays with LaTeX fragment images in current buffer.
  17147. When optional arguments BEG and END are non-nil, remove all
  17148. overlays between them instead. Return a non-nil value when some
  17149. overlays were removed, nil otherwise."
  17150. (let ((overlays (org--list-latex-overlays beg end)))
  17151. (mapc #'delete-overlay overlays)
  17152. overlays))
  17153. (defun org-toggle-latex-fragment (&optional arg)
  17154. "Preview the LaTeX fragment at point, or all locally or globally.
  17155. If the cursor is on a LaTeX fragment, create the image and overlay
  17156. it over the source code, if there is none. Remove it otherwise.
  17157. If there is no fragment at point, display all fragments in the
  17158. current section.
  17159. With prefix ARG, preview or clear image for all fragments in the
  17160. current subtree or in the whole buffer when used before the first
  17161. headline. With a prefix ARG `\\[universal-argument] \
  17162. \\[universal-argument]' preview or clear images
  17163. for all fragments in the buffer."
  17164. (interactive "P")
  17165. (when (display-graphic-p)
  17166. (catch 'exit
  17167. (save-excursion
  17168. (let (beg end msg)
  17169. (cond
  17170. ((or (equal arg '(16))
  17171. (and (equal arg '(4))
  17172. (org-with-limited-levels (org-before-first-heading-p))))
  17173. (if (org-remove-latex-fragment-image-overlays)
  17174. (progn (message "LaTeX fragments images removed from buffer")
  17175. (throw 'exit nil))
  17176. (setq msg "Creating images for buffer...")))
  17177. ((equal arg '(4))
  17178. (org-with-limited-levels (org-back-to-heading t))
  17179. (setq beg (point))
  17180. (setq end (progn (org-end-of-subtree t) (point)))
  17181. (if (org-remove-latex-fragment-image-overlays beg end)
  17182. (progn
  17183. (message "LaTeX fragment images removed from subtree")
  17184. (throw 'exit nil))
  17185. (setq msg "Creating images for subtree...")))
  17186. ((let ((datum (org-element-context)))
  17187. (when (memq (org-element-type datum)
  17188. '(latex-environment latex-fragment))
  17189. (setq beg (org-element-property :begin datum))
  17190. (setq end (org-element-property :end datum))
  17191. (if (org-remove-latex-fragment-image-overlays beg end)
  17192. (progn (message "LaTeX fragment image removed")
  17193. (throw 'exit nil))
  17194. (setq msg "Creating image...")))))
  17195. (t
  17196. (org-with-limited-levels
  17197. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17198. (outline-previous-heading)
  17199. (point)))
  17200. (setq end (progn (outline-next-heading) (point)))
  17201. (if (org-remove-latex-fragment-image-overlays beg end)
  17202. (progn
  17203. (message "LaTeX fragment images removed from section")
  17204. (throw 'exit nil))
  17205. (setq msg "Creating images for section...")))))
  17206. (let ((file (buffer-file-name (buffer-base-buffer))))
  17207. (org-format-latex
  17208. (concat org-preview-latex-image-directory "org-ltximg")
  17209. beg end
  17210. ;; Emacs cannot overlay images from remote hosts. Create
  17211. ;; it in `temporary-file-directory' instead.
  17212. (if (or (not file) (file-remote-p file))
  17213. temporary-file-directory
  17214. default-directory)
  17215. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17216. (message (concat msg "done")))))))
  17217. (defun org-format-latex
  17218. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17219. "Replace LaTeX fragments with links to an image.
  17220. The function takes care of creating the replacement image.
  17221. Only consider fragments between BEG and END when those are
  17222. provided.
  17223. When optional argument OVERLAYS is non-nil, display the image on
  17224. top of the fragment instead of replacing it.
  17225. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17226. Some of the options can be changed using the variable
  17227. `org-format-latex-options', which see."
  17228. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17229. (unless (eq processing-type 'verbatim)
  17230. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17231. (cnt 0)
  17232. checkdir-flag)
  17233. (goto-char (or beg (point-min)))
  17234. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17235. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17236. (overlay-recenter (or end (point-max))))
  17237. (while (re-search-forward math-regexp end t)
  17238. (unless (and overlays
  17239. (eq (get-char-property (point) 'org-overlay-type)
  17240. 'org-latex-overlay))
  17241. (let* ((context (org-element-context))
  17242. (type (org-element-type context)))
  17243. (when (memq type '(latex-environment latex-fragment))
  17244. (let ((block-type (eq type 'latex-environment))
  17245. (value (org-element-property :value context))
  17246. (beg (org-element-property :begin context))
  17247. (end (save-excursion
  17248. (goto-char (org-element-property :end context))
  17249. (skip-chars-backward " \r\t\n")
  17250. (point))))
  17251. (cond
  17252. ((eq processing-type 'mathjax)
  17253. ;; Prepare for MathJax processing.
  17254. (if (not (string-match "\\`\\$\\$?" value))
  17255. (goto-char end)
  17256. (delete-region beg end)
  17257. (if (string= (match-string 0 value) "$$")
  17258. (insert "\\[" (substring value 2 -2) "\\]")
  17259. (insert "\\(" (substring value 1 -1) "\\)"))))
  17260. ((assq processing-type org-preview-latex-process-alist)
  17261. ;; Process to an image.
  17262. (cl-incf cnt)
  17263. (goto-char beg)
  17264. (let* ((processing-info
  17265. (cdr (assq processing-type org-preview-latex-process-alist)))
  17266. (face (face-at-point))
  17267. ;; Get the colors from the face at point.
  17268. (fg
  17269. (let ((color (plist-get org-format-latex-options
  17270. :foreground)))
  17271. (if (and forbuffer (eq color 'auto))
  17272. (face-attribute face :foreground nil 'default)
  17273. color)))
  17274. (bg
  17275. (let ((color (plist-get org-format-latex-options
  17276. :background)))
  17277. (if (and forbuffer (eq color 'auto))
  17278. (face-attribute face :background nil 'default)
  17279. color)))
  17280. (hash (sha1 (prin1-to-string
  17281. (list org-format-latex-header
  17282. org-latex-default-packages-alist
  17283. org-latex-packages-alist
  17284. org-format-latex-options
  17285. forbuffer value fg bg))))
  17286. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17287. (absprefix (expand-file-name prefix dir))
  17288. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17289. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17290. (sep (and block-type "\n\n"))
  17291. (link (concat sep "[[file:" linkfile "]]" sep))
  17292. (options
  17293. (org-combine-plists
  17294. org-format-latex-options
  17295. `(:foreground ,fg :background ,bg))))
  17296. (when msg (message msg cnt))
  17297. (unless checkdir-flag ; Ensure the directory exists.
  17298. (setq checkdir-flag t)
  17299. (let ((todir (file-name-directory absprefix)))
  17300. (unless (file-directory-p todir)
  17301. (make-directory todir t))))
  17302. (unless (file-exists-p movefile)
  17303. (org-create-formula-image
  17304. value movefile options forbuffer processing-type))
  17305. (if overlays
  17306. (progn
  17307. (dolist (o (overlays-in beg end))
  17308. (when (eq (overlay-get o 'org-overlay-type)
  17309. 'org-latex-overlay)
  17310. (delete-overlay o)))
  17311. (org--format-latex-make-overlay beg end movefile imagetype)
  17312. (goto-char end))
  17313. (delete-region beg end)
  17314. (insert
  17315. (org-add-props link
  17316. (list 'org-latex-src
  17317. (replace-regexp-in-string "\"" "" value)
  17318. 'org-latex-src-embed-type
  17319. (if block-type 'paragraph 'character)))))))
  17320. ((eq processing-type 'mathml)
  17321. ;; Process to MathML.
  17322. (unless (org-format-latex-mathml-available-p)
  17323. (user-error "LaTeX to MathML converter not configured"))
  17324. (cl-incf cnt)
  17325. (when msg (message msg cnt))
  17326. (goto-char beg)
  17327. (delete-region beg end)
  17328. (insert (org-format-latex-as-mathml
  17329. value block-type prefix dir)))
  17330. (t
  17331. (error "Unknown conversion process %s for LaTeX fragments"
  17332. processing-type)))))))))))
  17333. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17334. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17335. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17336. sucessful, return the portion between \"<math...> </math>\"
  17337. elements otherwise return nil. When MATHML-FILE is specified,
  17338. write the results in to that file. When invoked as an
  17339. interactive command, prompt for LATEX-FRAG, with initial value
  17340. set to the current active region and echo the results for user
  17341. inspection."
  17342. (interactive (list (let ((frag (when (org-region-active-p)
  17343. (buffer-substring-no-properties
  17344. (region-beginning) (region-end)))))
  17345. (read-string "LaTeX Fragment: " frag nil frag))))
  17346. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17347. (let* ((tmp-in-file
  17348. (let ((file (file-relative-name
  17349. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17350. (write-region latex-frag nil file)
  17351. file))
  17352. (tmp-out-file (file-relative-name
  17353. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17354. (cmd (format-spec
  17355. org-latex-to-mathml-convert-command
  17356. `((?j . ,(and org-latex-to-mathml-jar-file
  17357. (shell-quote-argument
  17358. (expand-file-name
  17359. org-latex-to-mathml-jar-file))))
  17360. (?I . ,(shell-quote-argument tmp-in-file))
  17361. (?i . ,latex-frag)
  17362. (?o . ,(shell-quote-argument tmp-out-file)))))
  17363. mathml shell-command-output)
  17364. (when (called-interactively-p 'any)
  17365. (unless (org-format-latex-mathml-available-p)
  17366. (user-error "LaTeX to MathML converter not configured")))
  17367. (message "Running %s" cmd)
  17368. (setq shell-command-output (shell-command-to-string cmd))
  17369. (setq mathml
  17370. (when (file-readable-p tmp-out-file)
  17371. (with-current-buffer (find-file-noselect tmp-out-file t)
  17372. (goto-char (point-min))
  17373. (when (re-search-forward
  17374. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17375. (regexp-quote
  17376. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17377. nil t)
  17378. (prog1 (match-string 0) (kill-buffer))))))
  17379. (cond
  17380. (mathml
  17381. (setq mathml
  17382. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17383. (when mathml-file
  17384. (write-region mathml nil mathml-file))
  17385. (when (called-interactively-p 'any)
  17386. (message mathml)))
  17387. ((message "LaTeX to MathML conversion failed")
  17388. (message shell-command-output)))
  17389. (delete-file tmp-in-file)
  17390. (when (file-exists-p tmp-out-file)
  17391. (delete-file tmp-out-file))
  17392. mathml))
  17393. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17394. prefix &optional dir)
  17395. "Use `org-create-math-formula' but check local cache first."
  17396. (let* ((absprefix (expand-file-name prefix dir))
  17397. (print-length nil) (print-level nil)
  17398. (formula-id (concat
  17399. "formula-"
  17400. (sha1
  17401. (prin1-to-string
  17402. (list latex-frag
  17403. org-latex-to-mathml-convert-command)))))
  17404. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17405. (formula-cache-dir (file-name-directory formula-cache)))
  17406. (unless (file-directory-p formula-cache-dir)
  17407. (make-directory formula-cache-dir t))
  17408. (unless (file-exists-p formula-cache)
  17409. (org-create-math-formula latex-frag formula-cache))
  17410. (if (file-exists-p formula-cache)
  17411. ;; Successful conversion. Return the link to MathML file.
  17412. (org-add-props
  17413. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17414. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17415. 'org-latex-src-embed-type (if latex-frag-type
  17416. 'paragraph 'character)))
  17417. ;; Failed conversion. Return the LaTeX fragment verbatim
  17418. latex-frag)))
  17419. (defun org--get-display-dpi ()
  17420. "Get the DPI of the display.
  17421. The function assumes that the display has the same pixel width in
  17422. the horizontal and vertical directions."
  17423. (if (display-graphic-p)
  17424. (round (/ (display-pixel-height)
  17425. (/ (display-mm-height) 25.4)))
  17426. (error "Attempt to calculate the dpi of a non-graphic display")))
  17427. (defun org-create-formula-image
  17428. (string tofile options buffer &optional processing-type)
  17429. "Create an image from LaTeX source using external processes.
  17430. The LaTeX STRING is saved to a temporary LaTeX file, then
  17431. converted to an image file by process PROCESSING-TYPE defined in
  17432. `org-preview-latex-process-alist'. A nil value defaults to
  17433. `org-preview-latex-default-process'.
  17434. The generated image file is eventually moved to TOFILE.
  17435. The OPTIONS argument controls the size, foreground color and
  17436. background color of the generated image.
  17437. When BUFFER non-nil, this function is used for LaTeX previewing.
  17438. Otherwise, it is used to deal with LaTeX snippets showed in
  17439. a HTML file."
  17440. (let* ((processing-type (or processing-type
  17441. org-preview-latex-default-process))
  17442. (processing-info
  17443. (cdr (assq processing-type org-preview-latex-process-alist)))
  17444. (programs (plist-get processing-info :programs))
  17445. (error-message (or (plist-get processing-info :message) ""))
  17446. (use-xcolor (plist-get processing-info :use-xcolor))
  17447. (image-input-type (plist-get processing-info :image-input-type))
  17448. (image-output-type (plist-get processing-info :image-output-type))
  17449. (post-clean (or (plist-get processing-info :post-clean)
  17450. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17451. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17452. (latex-header
  17453. (or (plist-get processing-info :latex-header)
  17454. (org-latex-make-preamble
  17455. (org-export-get-environment (org-export-get-backend 'latex))
  17456. org-format-latex-header
  17457. 'snippet)))
  17458. (latex-compiler (plist-get processing-info :latex-compiler))
  17459. (image-converter (plist-get processing-info :image-converter))
  17460. (tmpdir temporary-file-directory)
  17461. (texfilebase (make-temp-name
  17462. (expand-file-name "orgtex" tmpdir)))
  17463. (texfile (concat texfilebase ".tex"))
  17464. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17465. '(1.0 . 1.0)))
  17466. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17467. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17468. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17469. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17470. "Black"))
  17471. (bg (or (plist-get options (if buffer :background :html-background))
  17472. "Transparent"))
  17473. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17474. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17475. (dolist (program programs)
  17476. (org-check-external-command program error-message))
  17477. (if use-xcolor
  17478. (progn (if (eq fg 'default)
  17479. (setq fg (org-latex-color :foreground))
  17480. (setq fg (org-latex-color-format fg)))
  17481. (if (eq bg 'default)
  17482. (setq bg (org-latex-color :background))
  17483. (setq bg (org-latex-color-format
  17484. (if (string= bg "Transparent") "white" bg))))
  17485. (with-temp-file texfile
  17486. (insert latex-header)
  17487. (insert "\n\\begin{document}\n"
  17488. "\\definecolor{fg}{rgb}{" fg "}\n"
  17489. "\\definecolor{bg}{rgb}{" bg "}\n"
  17490. "\n\\pagecolor{bg}\n"
  17491. "\n{\\color{fg}\n"
  17492. string
  17493. "\n}\n"
  17494. "\n\\end{document}\n")))
  17495. (if (eq fg 'default)
  17496. (setq fg (org-dvipng-color :foreground))
  17497. (unless (string= fg "Transparent")
  17498. (setq fg (org-dvipng-color-format fg))))
  17499. (if (eq bg 'default)
  17500. (setq bg (org-dvipng-color :background))
  17501. (unless (string= bg "Transparent")
  17502. (setq bg (org-dvipng-color-format bg))))
  17503. (with-temp-file texfile
  17504. (insert latex-header)
  17505. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17506. (let* ((err-msg (format "Please adjust '%s' part of \
  17507. `org-preview-latex-process-alist'."
  17508. processing-type))
  17509. (image-input-file
  17510. (org-compile-file
  17511. texfile latex-compiler image-input-type err-msg log-buf))
  17512. (image-output-file
  17513. (org-compile-file
  17514. image-input-file image-converter image-output-type err-msg log-buf
  17515. `((?F . ,(shell-quote-argument fg))
  17516. (?B . ,(shell-quote-argument bg))
  17517. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17518. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17519. (copy-file image-output-file tofile 'replace)
  17520. (dolist (e post-clean)
  17521. (when (file-exists-p (concat texfilebase e))
  17522. (delete-file (concat texfilebase e))))
  17523. image-output-file)))
  17524. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17525. "Fill a LaTeX header template TPL.
  17526. In the template, the following place holders will be recognized:
  17527. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17528. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17529. [PACKAGES] \\usepackage statements for PKG
  17530. [NO-PACKAGES] do not include PKG
  17531. [EXTRA] the string EXTRA
  17532. [NO-EXTRA] do not include EXTRA
  17533. For backward compatibility, if both the positive and the negative place
  17534. holder is missing, the positive one (without the \"NO-\") will be
  17535. assumed to be present at the end of the template.
  17536. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17537. EXTRA is a string.
  17538. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17539. (let (rpl (end ""))
  17540. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17541. (setq rpl (if (or (match-end 1) (not def-pkg))
  17542. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17543. tpl (replace-match rpl t t tpl))
  17544. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17545. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17546. (setq rpl (if (or (match-end 1) (not pkg))
  17547. "" (org-latex-packages-to-string pkg snippets-p t))
  17548. tpl (replace-match rpl t t tpl))
  17549. (when pkg (setq end
  17550. (concat end "\n"
  17551. (org-latex-packages-to-string pkg snippets-p)))))
  17552. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17553. (setq rpl (if (or (match-end 1) (not extra))
  17554. "" (concat extra "\n"))
  17555. tpl (replace-match rpl t t tpl))
  17556. (when (and extra (string-match "\\S-" extra))
  17557. (setq end (concat end "\n" extra))))
  17558. (if (string-match "\\S-" end)
  17559. (concat tpl "\n" end)
  17560. tpl)))
  17561. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17562. "Turn an alist of packages into a string with the \\usepackage macros."
  17563. (setq pkg (mapconcat (lambda(p)
  17564. (cond
  17565. ((stringp p) p)
  17566. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17567. (format "%% Package %s omitted" (cadr p)))
  17568. ((equal "" (car p))
  17569. (format "\\usepackage{%s}" (cadr p)))
  17570. (t
  17571. (format "\\usepackage[%s]{%s}"
  17572. (car p) (cadr p)))))
  17573. pkg
  17574. "\n"))
  17575. (if newline (concat pkg "\n") pkg))
  17576. (defun org-dvipng-color (attr)
  17577. "Return a RGB color specification for dvipng."
  17578. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17579. (defun org-dvipng-color-format (color-name)
  17580. "Convert COLOR-NAME to a RGB color value for dvipng."
  17581. (apply #'format "rgb %s %s %s"
  17582. (mapcar 'org-normalize-color
  17583. (color-values color-name))))
  17584. (defun org-latex-color (attr)
  17585. "Return a RGB color for the LaTeX color package."
  17586. (org-latex-color-format (face-attribute 'default attr nil)))
  17587. (defun org-latex-color-format (color-name)
  17588. "Convert COLOR-NAME to a RGB color value."
  17589. (apply #'format "%s,%s,%s"
  17590. (mapcar 'org-normalize-color
  17591. (color-values color-name))))
  17592. (defun org-normalize-color (value)
  17593. "Return string to be used as color value for an RGB component."
  17594. (format "%g" (/ value 65535.0)))
  17595. ;; Image display
  17596. (defvar-local org-inline-image-overlays nil)
  17597. (defun org-toggle-inline-images (&optional include-linked)
  17598. "Toggle the display of inline images.
  17599. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17600. (interactive "P")
  17601. (if org-inline-image-overlays
  17602. (progn
  17603. (org-remove-inline-images)
  17604. (when (called-interactively-p 'interactive)
  17605. (message "Inline image display turned off")))
  17606. (org-display-inline-images include-linked)
  17607. (when (called-interactively-p 'interactive)
  17608. (message (if org-inline-image-overlays
  17609. (format "%d images displayed inline"
  17610. (length org-inline-image-overlays))
  17611. "No images to display inline")))))
  17612. (defun org-redisplay-inline-images ()
  17613. "Refresh the display of inline images."
  17614. (interactive)
  17615. (if (not org-inline-image-overlays)
  17616. (org-toggle-inline-images)
  17617. (org-toggle-inline-images)
  17618. (org-toggle-inline-images)))
  17619. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17620. "Display inline images.
  17621. An inline image is a link which follows either of these
  17622. conventions:
  17623. 1. Its path is a file with an extension matching return value
  17624. from `image-file-name-regexp' and it has no contents.
  17625. 2. Its description consists in a single link of the previous
  17626. type.
  17627. When optional argument INCLUDE-LINKED is non-nil, also links with
  17628. a text description part will be inlined. This can be nice for
  17629. a quick look at those images, but it does not reflect what
  17630. exported files will look like.
  17631. When optional argument REFRESH is non-nil, refresh existing
  17632. images between BEG and END. This will create new image displays
  17633. only if necessary. BEG and END default to the buffer
  17634. boundaries."
  17635. (interactive "P")
  17636. (when (display-graphic-p)
  17637. (unless refresh
  17638. (org-remove-inline-images)
  17639. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17640. (org-with-wide-buffer
  17641. (goto-char (or beg (point-min)))
  17642. (let ((case-fold-search t)
  17643. (file-extension-re (image-file-name-regexp)))
  17644. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17645. (let ((link (save-match-data (org-element-context))))
  17646. ;; Check if we're at an inline image.
  17647. (when (and (equal (org-element-property :type link) "file")
  17648. (or include-linked
  17649. (not (org-element-property :contents-begin link)))
  17650. (let ((parent (org-element-property :parent link)))
  17651. (or (not (eq (org-element-type parent) 'link))
  17652. (not (cdr (org-element-contents parent)))))
  17653. (string-match-p file-extension-re
  17654. (org-element-property :path link)))
  17655. (let ((file (expand-file-name
  17656. (org-link-unescape
  17657. (org-element-property :path link)))))
  17658. (when (file-exists-p file)
  17659. (let ((width
  17660. ;; Apply `org-image-actual-width' specifications.
  17661. (cond
  17662. ((not (image-type-available-p 'imagemagick)) nil)
  17663. ((eq org-image-actual-width t) nil)
  17664. ((listp org-image-actual-width)
  17665. (or
  17666. ;; First try to find a width among
  17667. ;; attributes associated to the paragraph
  17668. ;; containing link.
  17669. (let ((paragraph
  17670. (let ((e link))
  17671. (while (and (setq e (org-element-property
  17672. :parent e))
  17673. (not (eq (org-element-type e)
  17674. 'paragraph))))
  17675. e)))
  17676. (when paragraph
  17677. (save-excursion
  17678. (goto-char (org-element-property :begin paragraph))
  17679. (when
  17680. (re-search-forward
  17681. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17682. (org-element-property
  17683. :post-affiliated paragraph)
  17684. t)
  17685. (string-to-number (match-string 1))))))
  17686. ;; Otherwise, fall-back to provided number.
  17687. (car org-image-actual-width)))
  17688. ((numberp org-image-actual-width)
  17689. org-image-actual-width)))
  17690. (old (get-char-property-and-overlay
  17691. (org-element-property :begin link)
  17692. 'org-image-overlay)))
  17693. (if (and (car-safe old) refresh)
  17694. (image-refresh (overlay-get (cdr old) 'display))
  17695. (let ((image (create-image file
  17696. (and width 'imagemagick)
  17697. nil
  17698. :width width)))
  17699. (when image
  17700. (let* ((link
  17701. ;; If inline image is the description
  17702. ;; of another link, be sure to
  17703. ;; consider the latter as the one to
  17704. ;; apply the overlay on.
  17705. (let ((parent
  17706. (org-element-property :parent link)))
  17707. (if (eq (org-element-type parent) 'link)
  17708. parent
  17709. link)))
  17710. (ov (make-overlay
  17711. (org-element-property :begin link)
  17712. (progn
  17713. (goto-char
  17714. (org-element-property :end link))
  17715. (skip-chars-backward " \t")
  17716. (point)))))
  17717. (overlay-put ov 'display image)
  17718. (overlay-put ov 'face 'default)
  17719. (overlay-put ov 'org-image-overlay t)
  17720. (overlay-put
  17721. ov 'modification-hooks
  17722. (list 'org-display-inline-remove-overlay))
  17723. (push ov org-inline-image-overlays)))))))))))))))
  17724. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17725. "Remove inline-display overlay if a corresponding region is modified."
  17726. (let ((inhibit-modification-hooks t))
  17727. (when (and ov after)
  17728. (delete ov org-inline-image-overlays)
  17729. (delete-overlay ov))))
  17730. (defun org-remove-inline-images ()
  17731. "Remove inline display of images."
  17732. (interactive)
  17733. (mapc #'delete-overlay org-inline-image-overlays)
  17734. (setq org-inline-image-overlays nil))
  17735. ;;;; Key bindings
  17736. ;; Outline functions from `outline-mode-prefix-map'
  17737. ;; that can be remapped in Org:
  17738. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17739. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17740. (define-key org-mode-map [remap outline-forward-same-level]
  17741. 'org-forward-heading-same-level)
  17742. (define-key org-mode-map [remap outline-backward-same-level]
  17743. 'org-backward-heading-same-level)
  17744. (define-key org-mode-map [remap outline-show-branches]
  17745. 'org-kill-note-or-show-branches)
  17746. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17747. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17748. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17749. (define-key org-mode-map [remap outline-next-visible-heading]
  17750. 'org-next-visible-heading)
  17751. (define-key org-mode-map [remap outline-previous-visible-heading]
  17752. 'org-previous-visible-heading)
  17753. (define-key org-mode-map [remap show-children] 'org-show-children)
  17754. ;; Outline functions from `outline-mode-prefix-map' that can not
  17755. ;; be remapped in Org:
  17756. ;; - the column "key binding" shows whether the Outline function is still
  17757. ;; available in Org mode on the same key that it has been bound to in
  17758. ;; Outline mode:
  17759. ;; - "overridden": key used for a different functionality in Org mode
  17760. ;; - else: key still bound to the same Outline function in Org mode
  17761. ;; | Outline function | key binding | Org replacement |
  17762. ;; |------------------------------------+-------------+--------------------------|
  17763. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17764. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17765. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17766. ;; | `show-entry' | overridden | no replacement |
  17767. ;; | `show-branches' | `C-c C-k' | still same function |
  17768. ;; | `show-subtree' | overridden | visibility cycling |
  17769. ;; | `show-all' | overridden | no replacement |
  17770. ;; | `hide-subtree' | overridden | visibility cycling |
  17771. ;; | `hide-body' | overridden | no replacement |
  17772. ;; | `hide-entry' | overridden | visibility cycling |
  17773. ;; | `hide-leaves' | overridden | no replacement |
  17774. ;; | `hide-sublevels' | overridden | no replacement |
  17775. ;; | `hide-other' | overridden | no replacement |
  17776. ;; Make `C-c C-x' a prefix key
  17777. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17778. ;; TAB key with modifiers
  17779. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17780. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17781. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17782. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17783. ;; The following line is necessary under Suse GNU/Linux
  17784. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17785. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17786. (define-key org-mode-map [backtab] 'org-shifttab)
  17787. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17788. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17789. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  17790. ;; Cursor keys with modifiers
  17791. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17792. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17793. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17794. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17795. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17796. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17797. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17798. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17799. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17800. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17801. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17802. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17803. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17804. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17805. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17806. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17807. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17808. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17809. ;; Babel keys
  17810. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17811. (dolist (pair org-babel-key-bindings)
  17812. (define-key org-babel-map (car pair) (cdr pair)))
  17813. ;;; Extra keys for tty access.
  17814. ;; We only set them when really needed because otherwise the
  17815. ;; menus don't show the simple keys
  17816. (when (or org-use-extra-keys (not window-system))
  17817. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17818. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17819. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17820. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17821. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17822. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17823. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17824. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17825. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17826. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17827. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17828. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17829. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17830. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17831. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17832. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17833. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17834. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17835. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17836. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17837. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17838. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17839. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17840. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17841. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17842. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17843. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17844. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17845. ;; All the other keys
  17846. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17847. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17848. (if (boundp 'narrow-map)
  17849. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17850. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17851. (if (boundp 'narrow-map)
  17852. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17853. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17854. (if (boundp 'narrow-map)
  17855. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17856. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17857. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17858. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17859. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17860. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17861. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17862. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17863. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17864. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17865. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17866. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17867. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17868. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17869. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17870. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17871. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17872. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17873. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17874. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17875. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17876. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17877. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17878. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17879. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17880. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17881. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17882. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17883. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17884. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17885. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17886. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17887. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17888. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17889. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17890. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17891. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17892. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17893. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17894. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17895. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17896. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17897. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17898. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17899. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17900. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17901. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17902. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17903. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17904. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17905. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17906. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17907. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17908. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17909. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17910. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17911. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17912. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17913. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17914. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17915. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17916. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17917. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17918. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17919. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17920. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17921. (org-defkey org-mode-map "\C-m" 'org-return)
  17922. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17923. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17924. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17925. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17926. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17927. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17928. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17929. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17930. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17931. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17932. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17933. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17934. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17935. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17936. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17937. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17938. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17939. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17940. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17941. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17942. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17943. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17944. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17945. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17946. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17947. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17948. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17949. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17950. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17951. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17952. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17953. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17954. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17955. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17956. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17957. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17958. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17959. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17960. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17961. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17962. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17963. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17964. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17965. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17966. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17967. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17968. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17969. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17970. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17971. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17972. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17973. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17974. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17975. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17976. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17977. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17978. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17979. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17980. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17981. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17982. (defconst org-speed-commands-default
  17983. '(
  17984. ("Outline Navigation")
  17985. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17986. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17987. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17988. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17989. ("F" . org-next-block)
  17990. ("B" . org-previous-block)
  17991. ("u" . (org-speed-move-safe 'outline-up-heading))
  17992. ("j" . org-goto)
  17993. ("g" . (org-refile t))
  17994. ("Outline Visibility")
  17995. ("c" . org-cycle)
  17996. ("C" . org-shifttab)
  17997. (" " . org-display-outline-path)
  17998. ("s" . org-narrow-to-subtree)
  17999. ("=" . org-columns)
  18000. ("Outline Structure Editing")
  18001. ("U" . org-metaup)
  18002. ("D" . org-metadown)
  18003. ("r" . org-metaright)
  18004. ("l" . org-metaleft)
  18005. ("R" . org-shiftmetaright)
  18006. ("L" . org-shiftmetaleft)
  18007. ("i" . (progn (forward-char 1) (call-interactively
  18008. 'org-insert-heading-respect-content)))
  18009. ("^" . org-sort)
  18010. ("w" . org-refile)
  18011. ("a" . org-archive-subtree-default-with-confirmation)
  18012. ("@" . org-mark-subtree)
  18013. ("#" . org-toggle-comment)
  18014. ("Clock Commands")
  18015. ("I" . org-clock-in)
  18016. ("O" . org-clock-out)
  18017. ("Meta Data Editing")
  18018. ("t" . org-todo)
  18019. ("," . (org-priority))
  18020. ("0" . (org-priority ?\ ))
  18021. ("1" . (org-priority ?A))
  18022. ("2" . (org-priority ?B))
  18023. ("3" . (org-priority ?C))
  18024. (":" . org-set-tags-command)
  18025. ("e" . org-set-effort)
  18026. ("E" . org-inc-effort)
  18027. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18028. (org-entry-put (point) "APPT_WARNTIME" m)))
  18029. ("Agenda Views etc")
  18030. ("v" . org-agenda)
  18031. ("/" . org-sparse-tree)
  18032. ("Misc")
  18033. ("o" . org-open-at-point)
  18034. ("?" . org-speed-command-help)
  18035. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18036. (">" . (org-agenda-remove-restriction-lock))
  18037. )
  18038. "The default speed commands.")
  18039. (defun org-print-speed-command (e)
  18040. (if (> (length (car e)) 1)
  18041. (progn
  18042. (princ "\n")
  18043. (princ (car e))
  18044. (princ "\n")
  18045. (princ (make-string (length (car e)) ?-))
  18046. (princ "\n"))
  18047. (princ (car e))
  18048. (princ " ")
  18049. (if (symbolp (cdr e))
  18050. (princ (symbol-name (cdr e)))
  18051. (prin1 (cdr e)))
  18052. (princ "\n")))
  18053. (defun org-speed-command-help ()
  18054. "Show the available speed commands."
  18055. (interactive)
  18056. (if (not org-use-speed-commands)
  18057. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18058. (with-output-to-temp-buffer "*Help*"
  18059. (princ "User-defined Speed commands\n===========================\n")
  18060. (mapc #'org-print-speed-command org-speed-commands-user)
  18061. (princ "\n")
  18062. (princ "Built-in Speed commands\n=======================\n")
  18063. (mapc #'org-print-speed-command org-speed-commands-default))
  18064. (with-current-buffer "*Help*"
  18065. (setq truncate-lines t))))
  18066. (defun org-speed-move-safe (cmd)
  18067. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18068. If not, return to the original position and throw an error."
  18069. (interactive)
  18070. (let ((pos (point)))
  18071. (call-interactively cmd)
  18072. (unless (and (bolp) (org-at-heading-p))
  18073. (goto-char pos)
  18074. (error "Boundary reached while executing %s" cmd))))
  18075. (defvar org-self-insert-command-undo-counter 0)
  18076. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18077. (defvar org-speed-command nil)
  18078. (defun org-speed-command-activate (keys)
  18079. "Hook for activating single-letter speed commands.
  18080. `org-speed-commands-default' specifies a minimal command set.
  18081. Use `org-speed-commands-user' for further customization."
  18082. (when (or (and (bolp) (looking-at org-outline-regexp))
  18083. (and (functionp org-use-speed-commands)
  18084. (funcall org-use-speed-commands)))
  18085. (cdr (assoc keys (append org-speed-commands-user
  18086. org-speed-commands-default)))))
  18087. (defun org-babel-speed-command-activate (keys)
  18088. "Hook for activating single-letter code block commands."
  18089. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18090. (cdr (assoc keys org-babel-key-bindings))))
  18091. (defcustom org-speed-command-hook
  18092. '(org-speed-command-activate org-babel-speed-command-activate)
  18093. "Hook for activating speed commands at strategic locations.
  18094. Hook functions are called in sequence until a valid handler is
  18095. found.
  18096. Each hook takes a single argument, a user-pressed command key
  18097. which is also a `self-insert-command' from the global map.
  18098. Within the hook, examine the cursor position and the command key
  18099. and return nil or a valid handler as appropriate. Handler could
  18100. be one of an interactive command, a function, or a form.
  18101. Set `org-use-speed-commands' to non-nil value to enable this
  18102. hook. The default setting is `org-speed-command-activate'."
  18103. :group 'org-structure
  18104. :version "24.1"
  18105. :type 'hook)
  18106. (defun org-self-insert-command (N)
  18107. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18108. If the cursor is in a table looking at whitespace, the whitespace is
  18109. overwritten, and the table is not marked as requiring realignment."
  18110. (interactive "p")
  18111. (org-check-before-invisible-edit 'insert)
  18112. (cond
  18113. ((and org-use-speed-commands
  18114. (let ((kv (this-command-keys-vector)))
  18115. (setq org-speed-command
  18116. (run-hook-with-args-until-success
  18117. 'org-speed-command-hook
  18118. (make-string 1 (aref kv (1- (length kv))))))))
  18119. (cond
  18120. ((commandp org-speed-command)
  18121. (setq this-command org-speed-command)
  18122. (call-interactively org-speed-command))
  18123. ((functionp org-speed-command)
  18124. (funcall org-speed-command))
  18125. ((and org-speed-command (listp org-speed-command))
  18126. (eval org-speed-command))
  18127. (t (let (org-use-speed-commands)
  18128. (call-interactively 'org-self-insert-command)))))
  18129. ((and
  18130. (org-at-table-p)
  18131. (progn
  18132. ;; Check if we blank the field, and if that triggers align.
  18133. (and (featurep 'org-table) org-table-auto-blank-field
  18134. (memq last-command
  18135. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18136. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18137. ;; Got extra space, this field does not determine
  18138. ;; column width.
  18139. (let (org-table-may-need-update) (org-table-blank-field))
  18140. ;; No extra space, this field may determine column
  18141. ;; width.
  18142. (org-table-blank-field)))
  18143. t)
  18144. (eq N 1)
  18145. (looking-at "[^|\n]* \\( \\)|"))
  18146. ;; There is room for insertion without re-aligning the table.
  18147. (delete-region (match-beginning 1) (match-end 1))
  18148. (self-insert-command N))
  18149. (t
  18150. (setq org-table-may-need-update t)
  18151. (self-insert-command N)
  18152. (org-fix-tags-on-the-fly)
  18153. (when org-self-insert-cluster-for-undo
  18154. (if (not (eq last-command 'org-self-insert-command))
  18155. (setq org-self-insert-command-undo-counter 1)
  18156. (if (>= org-self-insert-command-undo-counter 20)
  18157. (setq org-self-insert-command-undo-counter 1)
  18158. (and (> org-self-insert-command-undo-counter 0)
  18159. buffer-undo-list (listp buffer-undo-list)
  18160. (not (cadr buffer-undo-list)) ; remove nil entry
  18161. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18162. (setq org-self-insert-command-undo-counter
  18163. (1+ org-self-insert-command-undo-counter))))))))
  18164. (defun org-check-before-invisible-edit (kind)
  18165. "Check is editing if kind KIND would be dangerous with invisible text around.
  18166. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18167. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18168. (when (and org-catch-invisible-edits
  18169. (or (not (boundp 'visible-mode)) (not visible-mode))
  18170. (or (get-char-property (point) 'invisible)
  18171. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18172. ;; OK, we need to take a closer look
  18173. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18174. (invisible-before-point (unless (bobp) (get-char-property
  18175. (1- (point)) 'invisible)))
  18176. (border-and-ok-direction
  18177. (or
  18178. ;; Check if we are acting predictably before invisible text
  18179. (and invisible-at-point (not invisible-before-point)
  18180. (memq kind '(insert delete-backward)))
  18181. ;; Check if we are acting predictably after invisible text
  18182. ;; This works not well, and I have turned it off. It seems
  18183. ;; better to always show and stop after invisible text.
  18184. ;; (and (not invisible-at-point) invisible-before-point
  18185. ;; (memq kind '(insert delete)))
  18186. )))
  18187. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18188. (memq invisible-before-point '(outline org-hide-block t)))
  18189. (when (eq org-catch-invisible-edits 'error)
  18190. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18191. (if (and org-custom-properties-overlays
  18192. (y-or-n-p "Display invisible properties in this buffer? "))
  18193. (org-toggle-custom-properties-visibility)
  18194. ;; Make the area visible
  18195. (save-excursion
  18196. (when invisible-before-point
  18197. (goto-char (previous-single-char-property-change
  18198. (point) 'invisible)))
  18199. (outline-show-subtree))
  18200. (cond
  18201. ((eq org-catch-invisible-edits 'show)
  18202. ;; That's it, we do the edit after showing
  18203. (message
  18204. "Unfolding invisible region around point before editing")
  18205. (sit-for 1))
  18206. ((and (eq org-catch-invisible-edits 'smart)
  18207. border-and-ok-direction)
  18208. (message "Unfolding invisible region around point before editing"))
  18209. (t
  18210. ;; Don't do the edit, make the user repeat it in full visibility
  18211. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18212. (defun org-fix-tags-on-the-fly ()
  18213. "Align tags in headline at point.
  18214. Unlike to `org-set-tags', it ignores region and sorting."
  18215. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18216. (org-at-heading-p))
  18217. (let ((org-ignore-region t)
  18218. (org-tags-sort-function nil))
  18219. (org-set-tags nil t))))
  18220. (defun org-delete-backward-char (N)
  18221. "Like `delete-backward-char', insert whitespace at field end in tables.
  18222. When deleting backwards, in tables this function will insert whitespace in
  18223. front of the next \"|\" separator, to keep the table aligned. The table will
  18224. still be marked for re-alignment if the field did fill the entire column,
  18225. because, in this case the deletion might narrow the column."
  18226. (interactive "p")
  18227. (save-match-data
  18228. (org-check-before-invisible-edit 'delete-backward)
  18229. (if (and (org-at-table-p)
  18230. (eq N 1)
  18231. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18232. (looking-at ".*?|"))
  18233. (let ((pos (point))
  18234. (noalign (looking-at "[^|\n\r]* |"))
  18235. (c org-table-may-need-update))
  18236. (backward-delete-char N)
  18237. (unless overwrite-mode
  18238. (skip-chars-forward "^|")
  18239. (insert " ")
  18240. (goto-char (1- pos)))
  18241. ;; noalign: if there were two spaces at the end, this field
  18242. ;; does not determine the width of the column.
  18243. (when noalign (setq org-table-may-need-update c)))
  18244. (backward-delete-char N)
  18245. (org-fix-tags-on-the-fly))))
  18246. (defun org-delete-char (N)
  18247. "Like `delete-char', but insert whitespace at field end in tables.
  18248. When deleting characters, in tables this function will insert whitespace in
  18249. front of the next \"|\" separator, to keep the table aligned. The table will
  18250. still be marked for re-alignment if the field did fill the entire column,
  18251. because, in this case the deletion might narrow the column."
  18252. (interactive "p")
  18253. (save-match-data
  18254. (org-check-before-invisible-edit 'delete)
  18255. (if (and (org-at-table-p)
  18256. (not (bolp))
  18257. (not (= (char-after) ?|))
  18258. (eq N 1))
  18259. (if (looking-at ".*?|")
  18260. (let ((pos (point))
  18261. (noalign (looking-at "[^|\n\r]* |"))
  18262. (c org-table-may-need-update))
  18263. (replace-match
  18264. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18265. (goto-char pos)
  18266. ;; noalign: if there were two spaces at the end, this field
  18267. ;; does not determine the width of the column.
  18268. (when noalign (setq org-table-may-need-update c)))
  18269. (delete-char N))
  18270. (delete-char N)
  18271. (org-fix-tags-on-the-fly))))
  18272. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18273. (put 'org-self-insert-command 'delete-selection
  18274. (lambda ()
  18275. (not (run-hook-with-args-until-success
  18276. 'self-insert-uses-region-functions))))
  18277. (put 'orgtbl-self-insert-command 'delete-selection
  18278. (lambda ()
  18279. (not (run-hook-with-args-until-success
  18280. 'self-insert-uses-region-functions))))
  18281. (put 'org-delete-char 'delete-selection 'supersede)
  18282. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18283. (put 'org-yank 'delete-selection 'yank)
  18284. ;; Make `flyspell-mode' delay after some commands
  18285. (put 'org-self-insert-command 'flyspell-delayed t)
  18286. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18287. (put 'org-delete-char 'flyspell-delayed t)
  18288. (put 'org-delete-backward-char 'flyspell-delayed t)
  18289. ;; Make pabbrev-mode expand after Org mode commands
  18290. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18291. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18292. (defun org-remap (map &rest commands)
  18293. "In MAP, remap the functions given in COMMANDS.
  18294. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18295. (let (new old)
  18296. (while commands
  18297. (setq old (pop commands) new (pop commands))
  18298. (org-defkey map (vector 'remap old) new))))
  18299. (defun org-transpose-words ()
  18300. "Transpose words for Org.
  18301. This uses the `org-mode-transpose-word-syntax-table' syntax
  18302. table, which interprets characters in `org-emphasis-alist' as
  18303. word constituents."
  18304. (interactive)
  18305. (with-syntax-table org-mode-transpose-word-syntax-table
  18306. (call-interactively 'transpose-words)))
  18307. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18308. (when (eq org-enable-table-editor 'optimized)
  18309. ;; If the user wants maximum table support, we need to hijack
  18310. ;; some standard editing functions
  18311. (org-remap org-mode-map
  18312. 'self-insert-command 'org-self-insert-command
  18313. 'delete-char 'org-delete-char
  18314. 'delete-backward-char 'org-delete-backward-char)
  18315. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18316. (defvar org-ctrl-c-ctrl-c-hook nil
  18317. "Hook for functions attaching themselves to `C-c C-c'.
  18318. This can be used to add additional functionality to the C-c C-c
  18319. key which executes context-dependent commands. This hook is run
  18320. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18321. run after the last test.
  18322. Each function will be called with no arguments. The function
  18323. must check if the context is appropriate for it to act. If yes,
  18324. it should do its thing and then return a non-nil value. If the
  18325. context is wrong, just do nothing and return nil.")
  18326. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18327. "Hook for functions attaching themselves to `C-c C-c'.
  18328. This can be used to add additional functionality to the C-c C-c
  18329. key which executes context-dependent commands. This hook is run
  18330. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18331. before the first test.
  18332. Each function will be called with no arguments. The function
  18333. must check if the context is appropriate for it to act. If yes,
  18334. it should do its thing and then return a non-nil value. If the
  18335. context is wrong, just do nothing and return nil.")
  18336. (defvar org-tab-first-hook nil
  18337. "Hook for functions to attach themselves to TAB.
  18338. See `org-ctrl-c-ctrl-c-hook' for more information.
  18339. This hook runs as the first action when TAB is pressed, even before
  18340. `org-cycle' messes around with the `outline-regexp' to cater for
  18341. inline tasks and plain list item folding.
  18342. If any function in this hook returns t, any other actions that
  18343. would have been caused by TAB (such as table field motion or visibility
  18344. cycling) will not occur.")
  18345. (defvar org-tab-after-check-for-table-hook nil
  18346. "Hook for functions to attach themselves to TAB.
  18347. See `org-ctrl-c-ctrl-c-hook' for more information.
  18348. This hook runs after it has been established that the cursor is not in a
  18349. table, but before checking if the cursor is in a headline or if global cycling
  18350. should be done.
  18351. If any function in this hook returns t, not other actions like visibility
  18352. cycling will be done.")
  18353. (defvar org-tab-after-check-for-cycling-hook nil
  18354. "Hook for functions to attach themselves to TAB.
  18355. See `org-ctrl-c-ctrl-c-hook' for more information.
  18356. This hook runs after it has been established that not table field motion and
  18357. not visibility should be done because of current context. This is probably
  18358. the place where a package like yasnippets can hook in.")
  18359. (defvar org-tab-before-tab-emulation-hook nil
  18360. "Hook for functions to attach themselves to TAB.
  18361. See `org-ctrl-c-ctrl-c-hook' for more information.
  18362. This hook runs after every other options for TAB have been exhausted, but
  18363. before indentation and \t insertion takes place.")
  18364. (defvar org-metaleft-hook nil
  18365. "Hook for functions attaching themselves to `M-left'.
  18366. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18367. (defvar org-metaright-hook nil
  18368. "Hook for functions attaching themselves to `M-right'.
  18369. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18370. (defvar org-metaup-hook nil
  18371. "Hook for functions attaching themselves to `M-up'.
  18372. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18373. (defvar org-metadown-hook nil
  18374. "Hook for functions attaching themselves to `M-down'.
  18375. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18376. (defvar org-shiftmetaleft-hook nil
  18377. "Hook for functions attaching themselves to `M-S-left'.
  18378. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18379. (defvar org-shiftmetaright-hook nil
  18380. "Hook for functions attaching themselves to `M-S-right'.
  18381. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18382. (defvar org-shiftmetaup-hook nil
  18383. "Hook for functions attaching themselves to `M-S-up'.
  18384. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18385. (defvar org-shiftmetadown-hook nil
  18386. "Hook for functions attaching themselves to `M-S-down'.
  18387. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18388. (defvar org-metareturn-hook nil
  18389. "Hook for functions attaching themselves to `M-RET'.
  18390. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18391. (defvar org-shiftup-hook nil
  18392. "Hook for functions attaching themselves to `S-up'.
  18393. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18394. (defvar org-shiftup-final-hook nil
  18395. "Hook for functions attaching themselves to `S-up'.
  18396. This one runs after all other options except shift-select have been excluded.
  18397. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18398. (defvar org-shiftdown-hook nil
  18399. "Hook for functions attaching themselves to `S-down'.
  18400. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18401. (defvar org-shiftdown-final-hook nil
  18402. "Hook for functions attaching themselves to `S-down'.
  18403. This one runs after all other options except shift-select have been excluded.
  18404. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18405. (defvar org-shiftleft-hook nil
  18406. "Hook for functions attaching themselves to `S-left'.
  18407. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18408. (defvar org-shiftleft-final-hook nil
  18409. "Hook for functions attaching themselves to `S-left'.
  18410. This one runs after all other options except shift-select have been excluded.
  18411. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18412. (defvar org-shiftright-hook nil
  18413. "Hook for functions attaching themselves to `S-right'.
  18414. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18415. (defvar org-shiftright-final-hook nil
  18416. "Hook for functions attaching themselves to `S-right'.
  18417. This one runs after all other options except shift-select have been excluded.
  18418. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18419. (defun org-modifier-cursor-error ()
  18420. "Throw an error, a modified cursor command was applied in wrong context."
  18421. (user-error "This command is active in special context like tables, headlines or items"))
  18422. (defun org-shiftselect-error ()
  18423. "Throw an error because Shift-Cursor command was applied in wrong context."
  18424. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18425. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18426. (user-error "This command works only in special context like headlines or timestamps")))
  18427. (defun org-call-for-shift-select (cmd)
  18428. (let ((this-command-keys-shift-translated t))
  18429. (call-interactively cmd)))
  18430. (defun org-shifttab (&optional arg)
  18431. "Global visibility cycling or move to previous table field.
  18432. Call `org-table-previous-field' within a table.
  18433. When ARG is nil, cycle globally through visibility states.
  18434. When ARG is a numeric prefix, show contents of this level."
  18435. (interactive "P")
  18436. (cond
  18437. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18438. ((integerp arg)
  18439. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18440. (message "Content view to level: %d" arg)
  18441. (org-content (prefix-numeric-value arg2))
  18442. (org-cycle-show-empty-lines t)
  18443. (setq org-cycle-global-status 'overview)))
  18444. (t (call-interactively 'org-global-cycle))))
  18445. (defun org-shiftmetaleft ()
  18446. "Promote subtree or delete table column.
  18447. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18448. `org-table-delete-column', depending on context. See the
  18449. individual commands for more information."
  18450. (interactive)
  18451. (cond
  18452. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18453. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18454. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18455. ((if (not (org-region-active-p)) (org-at-item-p)
  18456. (save-excursion (goto-char (region-beginning))
  18457. (org-at-item-p)))
  18458. (call-interactively 'org-outdent-item-tree))
  18459. (t (org-modifier-cursor-error))))
  18460. (defun org-shiftmetaright ()
  18461. "Demote subtree or insert table column.
  18462. Calls `org-demote-subtree', `org-indent-item-tree', or
  18463. `org-table-insert-column', depending on context. See the
  18464. individual commands for more information."
  18465. (interactive)
  18466. (cond
  18467. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18468. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18469. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18470. ((if (not (org-region-active-p)) (org-at-item-p)
  18471. (save-excursion (goto-char (region-beginning))
  18472. (org-at-item-p)))
  18473. (call-interactively 'org-indent-item-tree))
  18474. (t (org-modifier-cursor-error))))
  18475. (defun org-shiftmetaup (&optional _arg)
  18476. "Drag the line at point up.
  18477. In a table, kill the current row.
  18478. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18479. but also adjust the previous clocked item in the clock history.
  18480. Everywhere else, drag the line at point up."
  18481. (interactive "P")
  18482. (cond
  18483. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18484. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18485. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18486. (call-interactively 'org-timestamp-up)))
  18487. (t (call-interactively 'org-drag-line-backward))))
  18488. (defun org-shiftmetadown (&optional _arg)
  18489. "Drag the line at point down.
  18490. In a table, insert an empty row at the current line.
  18491. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18492. but also adjust the previous clocked item in the clock history.
  18493. Everywhere else, drag the line at point down."
  18494. (interactive "P")
  18495. (cond
  18496. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18497. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18498. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18499. (call-interactively 'org-timestamp-down)))
  18500. (t (call-interactively 'org-drag-line-forward))))
  18501. (defsubst org-hidden-tree-error ()
  18502. (user-error
  18503. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18504. (defun org-metaleft (&optional _arg)
  18505. "Promote heading, list item at point or move table column left.
  18506. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18507. depending on context. With no specific context, calls the Emacs
  18508. default `backward-word'. See the individual commands for more
  18509. information.
  18510. This function runs the hook `org-metaleft-hook' as a first step,
  18511. and returns at first non-nil value."
  18512. (interactive "P")
  18513. (cond
  18514. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18515. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18516. ((org-with-limited-levels
  18517. (or (org-at-heading-p)
  18518. (and (org-region-active-p)
  18519. (save-excursion
  18520. (goto-char (region-beginning))
  18521. (org-at-heading-p)))))
  18522. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18523. (call-interactively 'org-do-promote))
  18524. ;; At an inline task.
  18525. ((org-at-heading-p)
  18526. (call-interactively 'org-inlinetask-promote))
  18527. ((or (org-at-item-p)
  18528. (and (org-region-active-p)
  18529. (save-excursion
  18530. (goto-char (region-beginning))
  18531. (org-at-item-p))))
  18532. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18533. (call-interactively 'org-outdent-item))
  18534. (t (call-interactively 'backward-word))))
  18535. (defun org-metaright (&optional _arg)
  18536. "Demote heading, list item at point or move table column right.
  18537. In front of a drawer or a block keyword, indent it correctly.
  18538. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18539. `org-indent-drawer' or `org-indent-block' depending on context.
  18540. With no specific context, calls the Emacs default `forward-word'.
  18541. See the individual commands for more information.
  18542. This function runs the hook `org-metaright-hook' as a first step,
  18543. and returns at first non-nil value."
  18544. (interactive "P")
  18545. (cond
  18546. ((run-hook-with-args-until-success 'org-metaright-hook))
  18547. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18548. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18549. ((org-at-block-p) (call-interactively 'org-indent-block))
  18550. ((org-with-limited-levels
  18551. (or (org-at-heading-p)
  18552. (and (org-region-active-p)
  18553. (save-excursion
  18554. (goto-char (region-beginning))
  18555. (org-at-heading-p)))))
  18556. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18557. (call-interactively 'org-do-demote))
  18558. ;; At an inline task.
  18559. ((org-at-heading-p)
  18560. (call-interactively 'org-inlinetask-demote))
  18561. ((or (org-at-item-p)
  18562. (and (org-region-active-p)
  18563. (save-excursion
  18564. (goto-char (region-beginning))
  18565. (org-at-item-p))))
  18566. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18567. (call-interactively 'org-indent-item))
  18568. (t (call-interactively 'forward-word))))
  18569. (defun org-check-for-hidden (what)
  18570. "Check if there are hidden headlines/items in the current visual line.
  18571. WHAT can be either `headlines' or `items'. If the current line is
  18572. an outline or item heading and it has a folded subtree below it,
  18573. this function returns t, nil otherwise."
  18574. (let ((re (cond
  18575. ((eq what 'headlines) org-outline-regexp-bol)
  18576. ((eq what 'items) (org-item-beginning-re))
  18577. (t (error "This should not happen"))))
  18578. beg end)
  18579. (save-excursion
  18580. (catch 'exit
  18581. (unless (org-region-active-p)
  18582. (setq beg (point-at-bol))
  18583. (beginning-of-line 2)
  18584. (while (and (not (eobp)) ;; this is like `next-line'
  18585. (get-char-property (1- (point)) 'invisible))
  18586. (beginning-of-line 2))
  18587. (setq end (point))
  18588. (goto-char beg)
  18589. (goto-char (point-at-eol))
  18590. (setq end (max end (point)))
  18591. (while (re-search-forward re end t)
  18592. (when (get-char-property (match-beginning 0) 'invisible)
  18593. (throw 'exit t))))
  18594. nil))))
  18595. (defun org-metaup (&optional _arg)
  18596. "Move subtree up or move table row up.
  18597. Calls `org-move-subtree-up' or `org-table-move-row' or
  18598. `org-move-item-up', depending on context. See the individual commands
  18599. for more information."
  18600. (interactive "P")
  18601. (cond
  18602. ((run-hook-with-args-until-success 'org-metaup-hook))
  18603. ((org-region-active-p)
  18604. (let* ((a (min (region-beginning) (region-end)))
  18605. (b (1- (max (region-beginning) (region-end))))
  18606. (c (save-excursion (goto-char a)
  18607. (move-beginning-of-line 0)))
  18608. (d (save-excursion (goto-char a)
  18609. (move-end-of-line 0) (point))))
  18610. (transpose-regions a b c d)
  18611. (goto-char c)))
  18612. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18613. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18614. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18615. (t (org-drag-element-backward))))
  18616. (defun org-metadown (&optional _arg)
  18617. "Move subtree down or move table row down.
  18618. Calls `org-move-subtree-down' or `org-table-move-row' or
  18619. `org-move-item-down', depending on context. See the individual
  18620. commands for more information."
  18621. (interactive "P")
  18622. (cond
  18623. ((run-hook-with-args-until-success 'org-metadown-hook))
  18624. ((org-region-active-p)
  18625. (let* ((a (min (region-beginning) (region-end)))
  18626. (b (max (region-beginning) (region-end)))
  18627. (c (save-excursion (goto-char b)
  18628. (move-beginning-of-line 1)))
  18629. (d (save-excursion (goto-char b)
  18630. (move-end-of-line 1) (1+ (point)))))
  18631. (transpose-regions a b c d)
  18632. (goto-char d)))
  18633. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18634. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18635. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18636. (t (org-drag-element-forward))))
  18637. (defun org-shiftup (&optional arg)
  18638. "Increase item in timestamp or increase priority of current headline.
  18639. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18640. depending on context. See the individual commands for more information."
  18641. (interactive "P")
  18642. (cond
  18643. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18644. ((and org-support-shift-select (org-region-active-p))
  18645. (org-call-for-shift-select 'previous-line))
  18646. ((org-at-timestamp-p 'lax)
  18647. (call-interactively (if org-edit-timestamp-down-means-later
  18648. 'org-timestamp-down 'org-timestamp-up)))
  18649. ((and (not (eq org-support-shift-select 'always))
  18650. org-enable-priority-commands
  18651. (org-at-heading-p))
  18652. (call-interactively 'org-priority-up))
  18653. ((and (not org-support-shift-select) (org-at-item-p))
  18654. (call-interactively 'org-previous-item))
  18655. ((org-clocktable-try-shift 'up arg))
  18656. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18657. (org-support-shift-select
  18658. (org-call-for-shift-select 'previous-line))
  18659. (t (org-shiftselect-error))))
  18660. (defun org-shiftdown (&optional arg)
  18661. "Decrease item in timestamp or decrease priority of current headline.
  18662. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18663. depending on context. See the individual commands for more information."
  18664. (interactive "P")
  18665. (cond
  18666. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18667. ((and org-support-shift-select (org-region-active-p))
  18668. (org-call-for-shift-select 'next-line))
  18669. ((org-at-timestamp-p 'lax)
  18670. (call-interactively (if org-edit-timestamp-down-means-later
  18671. 'org-timestamp-up 'org-timestamp-down)))
  18672. ((and (not (eq org-support-shift-select 'always))
  18673. org-enable-priority-commands
  18674. (org-at-heading-p))
  18675. (call-interactively 'org-priority-down))
  18676. ((and (not org-support-shift-select) (org-at-item-p))
  18677. (call-interactively 'org-next-item))
  18678. ((org-clocktable-try-shift 'down arg))
  18679. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18680. (org-support-shift-select
  18681. (org-call-for-shift-select 'next-line))
  18682. (t (org-shiftselect-error))))
  18683. (defun org-shiftright (&optional arg)
  18684. "Cycle the thing at point or in the current line, depending on context.
  18685. Depending on context, this does one of the following:
  18686. - switch a timestamp at point one day into the future
  18687. - on a headline, switch to the next TODO keyword.
  18688. - on an item, switch entire list to the next bullet type
  18689. - on a property line, switch to the next allowed value
  18690. - on a clocktable definition line, move time block into the future"
  18691. (interactive "P")
  18692. (cond
  18693. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18694. ((and org-support-shift-select (org-region-active-p))
  18695. (org-call-for-shift-select 'forward-char))
  18696. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18697. ((and (not (eq org-support-shift-select 'always))
  18698. (org-at-heading-p))
  18699. (let ((org-inhibit-logging
  18700. (not org-treat-S-cursor-todo-selection-as-state-change))
  18701. (org-inhibit-blocking
  18702. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18703. (org-call-with-arg 'org-todo 'right)))
  18704. ((or (and org-support-shift-select
  18705. (not (eq org-support-shift-select 'always))
  18706. (org-at-item-bullet-p))
  18707. (and (not org-support-shift-select) (org-at-item-p)))
  18708. (org-call-with-arg 'org-cycle-list-bullet nil))
  18709. ((and (not (eq org-support-shift-select 'always))
  18710. (org-at-property-p))
  18711. (call-interactively 'org-property-next-allowed-value))
  18712. ((org-clocktable-try-shift 'right arg))
  18713. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18714. (org-support-shift-select
  18715. (org-call-for-shift-select 'forward-char))
  18716. (t (org-shiftselect-error))))
  18717. (defun org-shiftleft (&optional arg)
  18718. "Cycle the thing at point or in the current line, depending on context.
  18719. Depending on context, this does one of the following:
  18720. - switch a timestamp at point one day into the past
  18721. - on a headline, switch to the previous TODO keyword.
  18722. - on an item, switch entire list to the previous bullet type
  18723. - on a property line, switch to the previous allowed value
  18724. - on a clocktable definition line, move time block into the past"
  18725. (interactive "P")
  18726. (cond
  18727. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18728. ((and org-support-shift-select (org-region-active-p))
  18729. (org-call-for-shift-select 'backward-char))
  18730. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18731. ((and (not (eq org-support-shift-select 'always))
  18732. (org-at-heading-p))
  18733. (let ((org-inhibit-logging
  18734. (not org-treat-S-cursor-todo-selection-as-state-change))
  18735. (org-inhibit-blocking
  18736. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18737. (org-call-with-arg 'org-todo 'left)))
  18738. ((or (and org-support-shift-select
  18739. (not (eq org-support-shift-select 'always))
  18740. (org-at-item-bullet-p))
  18741. (and (not org-support-shift-select) (org-at-item-p)))
  18742. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18743. ((and (not (eq org-support-shift-select 'always))
  18744. (org-at-property-p))
  18745. (call-interactively 'org-property-previous-allowed-value))
  18746. ((org-clocktable-try-shift 'left arg))
  18747. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18748. (org-support-shift-select
  18749. (org-call-for-shift-select 'backward-char))
  18750. (t (org-shiftselect-error))))
  18751. (defun org-shiftcontrolright ()
  18752. "Switch to next TODO set."
  18753. (interactive)
  18754. (cond
  18755. ((and org-support-shift-select (org-region-active-p))
  18756. (org-call-for-shift-select 'forward-word))
  18757. ((and (not (eq org-support-shift-select 'always))
  18758. (org-at-heading-p))
  18759. (org-call-with-arg 'org-todo 'nextset))
  18760. (org-support-shift-select
  18761. (org-call-for-shift-select 'forward-word))
  18762. (t (org-shiftselect-error))))
  18763. (defun org-shiftcontrolleft ()
  18764. "Switch to previous TODO set."
  18765. (interactive)
  18766. (cond
  18767. ((and org-support-shift-select (org-region-active-p))
  18768. (org-call-for-shift-select 'backward-word))
  18769. ((and (not (eq org-support-shift-select 'always))
  18770. (org-at-heading-p))
  18771. (org-call-with-arg 'org-todo 'previousset))
  18772. (org-support-shift-select
  18773. (org-call-for-shift-select 'backward-word))
  18774. (t (org-shiftselect-error))))
  18775. (defun org-shiftcontrolup (&optional n)
  18776. "Change timestamps synchronously up in CLOCK log lines.
  18777. Optional argument N tells to change by that many units."
  18778. (interactive "P")
  18779. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18780. (let (org-support-shift-select)
  18781. (org-clock-timestamps-up n))
  18782. (user-error "Not at a clock log")))
  18783. (defun org-shiftcontroldown (&optional n)
  18784. "Change timestamps synchronously down in CLOCK log lines.
  18785. Optional argument N tells to change by that many units."
  18786. (interactive "P")
  18787. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18788. (let (org-support-shift-select)
  18789. (org-clock-timestamps-down n))
  18790. (user-error "Not at a clock log")))
  18791. (defun org-increase-number-at-point (&optional inc)
  18792. "Increment the number at point.
  18793. With an optional prefix numeric argument INC, increment using
  18794. this numeric value."
  18795. (interactive "p")
  18796. (if (not (number-at-point))
  18797. (user-error "Not on a number")
  18798. (unless inc (setq inc 1))
  18799. (let ((pos (point))
  18800. (beg (skip-chars-backward "-+^/*0-9eE."))
  18801. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18802. (setq nap (buffer-substring-no-properties
  18803. (+ pos beg) (+ pos beg end)))
  18804. (delete-region (+ pos beg) (+ pos beg end))
  18805. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18806. (when (org-at-table-p)
  18807. (org-table-align)
  18808. (org-table-end-of-field 1))))
  18809. (defun org-decrease-number-at-point (&optional inc)
  18810. "Decrement the number at point.
  18811. With an optional prefix numeric argument INC, decrement using
  18812. this numeric value."
  18813. (interactive "p")
  18814. (org-increase-number-at-point (- (or inc 1))))
  18815. (defun org-ctrl-c-ret ()
  18816. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18817. (interactive)
  18818. (cond
  18819. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18820. (t (call-interactively 'org-insert-heading))))
  18821. (defun org-find-visible ()
  18822. (let ((s (point)))
  18823. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18824. (get-char-property s 'invisible)))
  18825. s))
  18826. (defun org-find-invisible ()
  18827. (let ((s (point)))
  18828. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18829. (not (get-char-property s 'invisible))))
  18830. s))
  18831. (defun org-copy-visible (beg end)
  18832. "Copy the visible parts of the region."
  18833. (interactive "r")
  18834. (let (snippets s)
  18835. (save-excursion
  18836. (save-restriction
  18837. (narrow-to-region beg end)
  18838. (setq s (goto-char (point-min)))
  18839. (while (not (= (point) (point-max)))
  18840. (goto-char (org-find-invisible))
  18841. (push (buffer-substring s (point)) snippets)
  18842. (setq s (goto-char (org-find-visible))))))
  18843. (kill-new (apply 'concat (nreverse snippets)))))
  18844. (defun org-copy-special ()
  18845. "Copy region in table or copy current subtree.
  18846. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18847. context. See the individual commands for more information."
  18848. (interactive)
  18849. (call-interactively
  18850. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18851. (defun org-cut-special ()
  18852. "Cut region in table or cut current subtree.
  18853. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18854. context. See the individual commands for more information."
  18855. (interactive)
  18856. (call-interactively
  18857. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18858. (defun org-paste-special (arg)
  18859. "Paste rectangular region into table, or past subtree relative to level.
  18860. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18861. See the individual commands for more information."
  18862. (interactive "P")
  18863. (if (org-at-table-p)
  18864. (org-table-paste-rectangle)
  18865. (org-paste-subtree arg)))
  18866. (defun org-edit-special (&optional arg)
  18867. "Call a special editor for the element at point.
  18868. When at a table, call the formula editor with `org-table-edit-formulas'.
  18869. When in a source code block, call `org-edit-src-code'.
  18870. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18871. When in an export block, call `org-edit-export-block'.
  18872. When in a LaTeX environment, call `org-edit-latex-environment'.
  18873. When at an #+INCLUDE keyword, visit the included file.
  18874. When at a footnote reference, call `org-edit-footnote-reference'
  18875. On a link, call `ffap' to visit the link at point.
  18876. Otherwise, return a user error."
  18877. (interactive "P")
  18878. (let ((element (org-element-at-point)))
  18879. (barf-if-buffer-read-only)
  18880. (pcase (org-element-type element)
  18881. (`src-block
  18882. (if (not arg) (org-edit-src-code)
  18883. (let* ((info (org-babel-get-src-block-info))
  18884. (lang (nth 0 info))
  18885. (params (nth 2 info))
  18886. (session (cdr (assq :session params))))
  18887. (if (not session) (org-edit-src-code)
  18888. ;; At a src-block with a session and function called with
  18889. ;; an ARG: switch to the buffer related to the inferior
  18890. ;; process.
  18891. (switch-to-buffer
  18892. (funcall (intern (concat "org-babel-prep-session:" lang))
  18893. session params))))))
  18894. (`keyword
  18895. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18896. (org-open-link-from-string
  18897. (format "[[%s]]"
  18898. (expand-file-name
  18899. (let ((value (org-element-property :value element)))
  18900. (cond ((not (org-string-nw-p value))
  18901. (user-error "No file to edit"))
  18902. ((string-match "\\`\"\\(.*?\\)\"" value)
  18903. (match-string 1 value))
  18904. ((string-match "\\`[^ \t\"]\\S-*" value)
  18905. (match-string 0 value))
  18906. (t (user-error "No valid file specified")))))))
  18907. (user-error "No special environment to edit here")))
  18908. (`table
  18909. (if (eq (org-element-property :type element) 'table.el)
  18910. (org-edit-table.el)
  18911. (call-interactively 'org-table-edit-formulas)))
  18912. ;; Only Org tables contain `table-row' type elements.
  18913. (`table-row (call-interactively 'org-table-edit-formulas))
  18914. (`example-block (org-edit-src-code))
  18915. (`export-block (org-edit-export-block))
  18916. (`fixed-width (org-edit-fixed-width-region))
  18917. (`latex-environment (org-edit-latex-environment))
  18918. (_
  18919. ;; No notable element at point. Though, we may be at a link or
  18920. ;; a footnote reference, which are objects. Thus, scan deeper.
  18921. (let ((context (org-element-context element)))
  18922. (pcase (org-element-type context)
  18923. (`footnote-reference (org-edit-footnote-reference))
  18924. (`inline-src-block (org-edit-inline-src-code))
  18925. (`link (call-interactively #'ffap))
  18926. (_ (user-error "No special environment to edit here"))))))))
  18927. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18928. (defun org-ctrl-c-ctrl-c (&optional arg)
  18929. "Set tags in headline, or update according to changed information at point.
  18930. This command does many different things, depending on context:
  18931. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18932. this is what we do.
  18933. - If the cursor is on a statistics cookie, update it.
  18934. - If the cursor is in a headline, prompt for tags and insert them
  18935. into the current line, aligned to `org-tags-column'. When called
  18936. with prefix arg, realign all tags in the current buffer.
  18937. - If the cursor is in one of the special #+KEYWORD lines, this
  18938. triggers scanning the buffer for these lines and updating the
  18939. information.
  18940. - If the cursor is inside a table, realign the table. This command
  18941. works even if the automatic table editor has been turned off.
  18942. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18943. the entire table.
  18944. - If the cursor is at a footnote reference or definition, jump to
  18945. the corresponding definition or references, respectively.
  18946. - If the cursor is a the beginning of a dynamic block, update it.
  18947. - If the current buffer is a capture buffer, close note and file it.
  18948. - If the cursor is on a <<<target>>>, update radio targets and
  18949. corresponding links in this buffer.
  18950. - If the cursor is on a numbered item in a plain list, renumber the
  18951. ordered list.
  18952. - If the cursor is on a checkbox, toggle it.
  18953. - If the cursor is on a code block, evaluate it. The variable
  18954. `org-confirm-babel-evaluate' can be used to control prompting
  18955. before code block evaluation, by default every code block
  18956. evaluation requires confirmation. Code block evaluation can be
  18957. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18958. (interactive "P")
  18959. (cond
  18960. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18961. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18962. (org-remove-occur-highlights)
  18963. (message "Temporary highlights/overlays removed from current buffer"))
  18964. ((and (local-variable-p 'org-finish-function)
  18965. (fboundp org-finish-function))
  18966. (funcall org-finish-function))
  18967. ((org-babel-hash-at-point))
  18968. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18969. (t
  18970. (let* ((context
  18971. (org-element-lineage
  18972. (org-element-context)
  18973. ;; Limit to supported contexts.
  18974. '(babel-call clock dynamic-block footnote-definition
  18975. footnote-reference inline-babel-call inline-src-block
  18976. inlinetask item keyword node-property paragraph
  18977. plain-list property-drawer radio-target src-block
  18978. statistics-cookie table table-cell table-row
  18979. timestamp)
  18980. t))
  18981. (type (org-element-type context)))
  18982. ;; For convenience: at the first line of a paragraph on the same
  18983. ;; line as an item, apply function on that item instead.
  18984. (when (eq type 'paragraph)
  18985. (let ((parent (org-element-property :parent context)))
  18986. (when (and (eq (org-element-type parent) 'item)
  18987. (= (line-beginning-position)
  18988. (org-element-property :begin parent)))
  18989. (setq context parent)
  18990. (setq type 'item))))
  18991. ;; Act according to type of element or object at point.
  18992. ;;
  18993. ;; Do nothing on a blank line, except if it is contained in
  18994. ;; a src block. Hence, we first check if point is in such
  18995. ;; a block and then if it is at a blank line.
  18996. (pcase type
  18997. ((or `inline-src-block `src-block)
  18998. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18999. (org-babel-eval-wipe-error-buffer)
  19000. (org-babel-execute-src-block
  19001. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19002. ((guard (org-match-line "[ \t]*$"))
  19003. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19004. (user-error
  19005. (substitute-command-keys
  19006. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19007. ((or `babel-call `inline-babel-call)
  19008. (let ((info (org-babel-lob-get-info context)))
  19009. (when info (org-babel-execute-src-block nil info))))
  19010. (`clock (org-clock-update-time-maybe))
  19011. (`dynamic-block
  19012. (save-excursion
  19013. (goto-char (org-element-property :post-affiliated context))
  19014. (org-update-dblock)))
  19015. (`footnote-definition
  19016. (goto-char (org-element-property :post-affiliated context))
  19017. (call-interactively 'org-footnote-action))
  19018. (`footnote-reference (call-interactively #'org-footnote-action))
  19019. ((or `headline `inlinetask)
  19020. (save-excursion (goto-char (org-element-property :begin context))
  19021. (call-interactively #'org-set-tags)))
  19022. (`item
  19023. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19024. ;; unconditionally, whereas `C-u' will toggle its presence.
  19025. ;; Without a universal argument, if the item has a checkbox,
  19026. ;; toggle it. Otherwise repair the list.
  19027. (let* ((box (org-element-property :checkbox context))
  19028. (struct (org-element-property :structure context))
  19029. (old-struct (copy-tree struct))
  19030. (parents (org-list-parents-alist struct))
  19031. (prevs (org-list-prevs-alist struct))
  19032. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19033. (org-list-set-checkbox
  19034. (org-element-property :begin context) struct
  19035. (cond ((equal arg '(16)) "[-]")
  19036. ((and (not box) (equal arg '(4))) "[ ]")
  19037. ((or (not box) (equal arg '(4))) nil)
  19038. ((eq box 'on) "[ ]")
  19039. (t "[X]")))
  19040. ;; Mimic `org-list-write-struct' but with grabbing a return
  19041. ;; value from `org-list-struct-fix-box'.
  19042. (org-list-struct-fix-ind struct parents 2)
  19043. (org-list-struct-fix-item-end struct)
  19044. (org-list-struct-fix-bul struct prevs)
  19045. (org-list-struct-fix-ind struct parents)
  19046. (let ((block-item
  19047. (org-list-struct-fix-box struct parents prevs orderedp)))
  19048. (if (and box (equal struct old-struct))
  19049. (if (equal arg '(16))
  19050. (message "Checkboxes already reset")
  19051. (user-error "Cannot toggle this checkbox: %s"
  19052. (if (eq box 'on)
  19053. "all subitems checked"
  19054. "unchecked subitems")))
  19055. (org-list-struct-apply-struct struct old-struct)
  19056. (org-update-checkbox-count-maybe))
  19057. (when block-item
  19058. (message "Checkboxes were removed due to empty box at line %d"
  19059. (org-current-line block-item))))))
  19060. (`keyword
  19061. (let ((org-inhibit-startup-visibility-stuff t)
  19062. (org-startup-align-all-tables nil))
  19063. (when (boundp 'org-table-coordinate-overlays)
  19064. (mapc #'delete-overlay org-table-coordinate-overlays)
  19065. (setq org-table-coordinate-overlays nil))
  19066. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19067. (message "Local setup has been refreshed"))
  19068. (`plain-list
  19069. ;; At a plain list, with a double C-u argument, set
  19070. ;; checkboxes of each item to "[-]", whereas a single one
  19071. ;; will toggle their presence according to the state of the
  19072. ;; first item in the list. Without an argument, repair the
  19073. ;; list.
  19074. (let* ((begin (org-element-property :contents-begin context))
  19075. (beginm (move-marker (make-marker) begin))
  19076. (struct (org-element-property :structure context))
  19077. (old-struct (copy-tree struct))
  19078. (first-box (save-excursion
  19079. (goto-char begin)
  19080. (looking-at org-list-full-item-re)
  19081. (match-string-no-properties 3)))
  19082. (new-box (cond ((equal arg '(16)) "[-]")
  19083. ((equal arg '(4)) (unless first-box "[ ]"))
  19084. ((equal first-box "[X]") "[ ]")
  19085. (t "[X]"))))
  19086. (cond
  19087. (arg
  19088. (dolist (pos
  19089. (org-list-get-all-items
  19090. begin struct (org-list-prevs-alist struct)))
  19091. (org-list-set-checkbox pos struct new-box)))
  19092. ((and first-box (eq (point) begin))
  19093. ;; For convenience, when point is at bol on the first
  19094. ;; item of the list and no argument is provided, simply
  19095. ;; toggle checkbox of that item, if any.
  19096. (org-list-set-checkbox begin struct new-box)))
  19097. (org-list-write-struct
  19098. struct (org-list-parents-alist struct) old-struct)
  19099. (org-update-checkbox-count-maybe)
  19100. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19101. ((or `property-drawer `node-property)
  19102. (call-interactively #'org-property-action))
  19103. (`radio-target
  19104. (call-interactively #'org-update-radio-target-regexp))
  19105. (`statistics-cookie
  19106. (call-interactively #'org-update-statistics-cookies))
  19107. ((or `table `table-cell `table-row)
  19108. ;; At a table, recalculate every field and align it. Also
  19109. ;; send the table if necessary. If the table has
  19110. ;; a `table.el' type, just give up. At a table row or cell,
  19111. ;; maybe recalculate line but always align table.
  19112. (if (eq (org-element-property :type context) 'table.el)
  19113. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19114. Use `\\[org-edit-special]' to edit table.el tables"))
  19115. (let ((org-enable-table-editor t))
  19116. (if (or (eq type 'table)
  19117. ;; Check if point is at a TBLFM line.
  19118. (and (eq type 'table-row)
  19119. (= (point) (org-element-property :end context))))
  19120. (save-excursion
  19121. (if (org-at-TBLFM-p)
  19122. (progn (require 'org-table)
  19123. (org-table-calc-current-TBLFM))
  19124. (goto-char (org-element-property :contents-begin context))
  19125. (org-call-with-arg 'org-table-recalculate (or arg t))
  19126. (orgtbl-send-table 'maybe)))
  19127. (org-table-maybe-eval-formula)
  19128. (cond (arg (call-interactively #'org-table-recalculate))
  19129. ((org-table-maybe-recalculate-line))
  19130. (t (org-table-align)))))))
  19131. (`timestamp (org-timestamp-change 0 'day))
  19132. ((and `nil (guard (org-at-heading-p)))
  19133. ;; When point is on an unsupported object type, we can miss
  19134. ;; the fact that it also is at a heading. Handle it here.
  19135. (call-interactively #'org-set-tags))
  19136. ((guard
  19137. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19138. (_
  19139. (user-error
  19140. (substitute-command-keys
  19141. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19142. (defun org-mode-restart ()
  19143. (interactive)
  19144. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19145. (funcall major-mode)
  19146. (hack-local-variables)
  19147. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19148. (org-indent-mode -1)))
  19149. (message "%s restarted" major-mode))
  19150. (defun org-kill-note-or-show-branches ()
  19151. "Abort storing current note, or call `outline-show-branches'."
  19152. (interactive)
  19153. (if (not org-finish-function)
  19154. (progn
  19155. (outline-hide-subtree)
  19156. (call-interactively 'outline-show-branches))
  19157. (let ((org-note-abort t))
  19158. (funcall org-finish-function))))
  19159. (defun org-delete-indentation (&optional arg)
  19160. "Join current line to previous and fix whitespace at join.
  19161. If previous line is a headline add to headline title. Otherwise
  19162. the function calls `delete-indentation'.
  19163. With a non-nil optional argument, join it to the following one."
  19164. (interactive "*P")
  19165. (if (save-excursion
  19166. (beginning-of-line (if arg 1 0))
  19167. (let ((case-fold-search nil))
  19168. (looking-at org-complex-heading-regexp)))
  19169. ;; At headline.
  19170. (let ((tags-column (when (match-beginning 5)
  19171. (save-excursion (goto-char (match-beginning 5))
  19172. (current-column))))
  19173. (string (concat " " (progn (when arg (forward-line 1))
  19174. (org-trim (delete-and-extract-region
  19175. (line-beginning-position)
  19176. (line-end-position)))))))
  19177. (unless (bobp) (delete-region (point) (1- (point))))
  19178. (goto-char (or (match-end 4)
  19179. (match-beginning 5)
  19180. (match-end 0)))
  19181. (skip-chars-backward " \t")
  19182. (save-excursion (insert string))
  19183. ;; Adjust alignment of tags.
  19184. (cond
  19185. ((not tags-column)) ;no tags
  19186. (org-auto-align-tags (org-set-tags nil t))
  19187. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19188. (delete-indentation arg)))
  19189. (defun org-open-line (n)
  19190. "Insert a new row in tables, call `open-line' elsewhere.
  19191. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19192. As a special case, when a document starts with a table, allow to
  19193. call `open-line' on the very first character."
  19194. (interactive "*p")
  19195. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19196. (org-table-insert-row)
  19197. (open-line n)))
  19198. (defun org-return (&optional indent)
  19199. "Goto next table row or insert a newline.
  19200. Calls `org-table-next-row' or `newline', depending on context.
  19201. When optional INDENT argument is non-nil, call
  19202. `newline-and-indent' instead of `newline'.
  19203. When `org-return-follows-link' is non-nil and point is on
  19204. a timestamp or a link, call `org-open-at-point'. However, it
  19205. will not happen if point is in a table or on a \"dead\"
  19206. object (e.g., within a comment). In these case, you need to use
  19207. `org-open-at-point' directly."
  19208. (interactive)
  19209. (let ((context (if org-return-follows-link (org-element-context)
  19210. (org-element-at-point))))
  19211. (cond
  19212. ;; In a table, call `org-table-next-row'.
  19213. ((or (and (eq (org-element-type context) 'table)
  19214. (>= (point) (org-element-property :contents-begin context))
  19215. (< (point) (org-element-property :contents-end context)))
  19216. (org-element-lineage context '(table-row table-cell) t))
  19217. (org-table-justify-field-maybe)
  19218. (call-interactively #'org-table-next-row))
  19219. ;; On a link or a timestamp, call `org-open-at-point' if
  19220. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19221. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19222. ((and org-return-follows-link
  19223. (or (org-in-regexp org-ts-regexp-both nil t)
  19224. (org-in-regexp org-tsr-regexp-both nil t)
  19225. (org-in-regexp org-any-link-re nil t)))
  19226. (call-interactively #'org-open-at-point))
  19227. ;; Insert newline in heading, but preserve tags.
  19228. ((and (not (bolp))
  19229. (save-excursion (beginning-of-line)
  19230. (let ((case-fold-search nil))
  19231. (looking-at org-complex-heading-regexp))))
  19232. ;; At headline. Split line. However, if point is on keyword,
  19233. ;; priority cookie or tags, do not break any of them: add
  19234. ;; a newline after the headline instead.
  19235. (let ((tags-column (and (match-beginning 5)
  19236. (save-excursion (goto-char (match-beginning 5))
  19237. (current-column))))
  19238. (string
  19239. (when (and (match-end 4) (org-point-in-group (point) 4))
  19240. (delete-and-extract-region (point) (match-end 4)))))
  19241. ;; Adjust tag alignment.
  19242. (cond
  19243. ((not (and tags-column string)))
  19244. (org-auto-align-tags (org-set-tags nil t))
  19245. (t (org--align-tags-here tags-column))) ;preserve tags column
  19246. (end-of-line)
  19247. (org-show-entry)
  19248. (if indent (newline-and-indent) (newline))
  19249. (when string (save-excursion (insert (org-trim string))))))
  19250. ;; In a list, make sure indenting keeps trailing text within.
  19251. ((and indent
  19252. (not (eolp))
  19253. (org-element-lineage context '(item)))
  19254. (let ((trailing-data
  19255. (delete-and-extract-region (point) (line-end-position))))
  19256. (newline-and-indent)
  19257. (save-excursion (insert trailing-data))))
  19258. (t (if indent (newline-and-indent) (newline))))))
  19259. (defun org-return-indent ()
  19260. "Goto next table row or insert a newline and indent.
  19261. Calls `org-table-next-row' or `newline-and-indent', depending on
  19262. context. See the individual commands for more information."
  19263. (interactive)
  19264. (org-return t))
  19265. (defun org-ctrl-c-star ()
  19266. "Compute table, or change heading status of lines.
  19267. Calls `org-table-recalculate' or `org-toggle-heading',
  19268. depending on context."
  19269. (interactive)
  19270. (cond
  19271. ((org-at-table-p)
  19272. (call-interactively 'org-table-recalculate))
  19273. (t
  19274. ;; Convert all lines in region to list items
  19275. (call-interactively 'org-toggle-heading))))
  19276. (defun org-ctrl-c-minus ()
  19277. "Insert separator line in table or modify bullet status of line.
  19278. Also turns a plain line or a region of lines into list items.
  19279. Calls `org-table-insert-hline', `org-toggle-item', or
  19280. `org-cycle-list-bullet', depending on context."
  19281. (interactive)
  19282. (cond
  19283. ((org-at-table-p)
  19284. (call-interactively 'org-table-insert-hline))
  19285. ((org-region-active-p)
  19286. (call-interactively 'org-toggle-item))
  19287. ((org-in-item-p)
  19288. (call-interactively 'org-cycle-list-bullet))
  19289. (t
  19290. (call-interactively 'org-toggle-item))))
  19291. (defun org-toggle-heading (&optional nstars)
  19292. "Convert headings to normal text, or items or text to headings.
  19293. If there is no active region, only convert the current line.
  19294. With a `\\[universal-argument]' prefix, convert the whole list at
  19295. point into heading.
  19296. In a region:
  19297. - If the first non blank line is a headline, remove the stars
  19298. from all headlines in the region.
  19299. - If it is a normal line, turn each and every normal line (i.e.,
  19300. not an heading or an item) in the region into headings. If you
  19301. want to convert only the first line of this region, use one
  19302. universal prefix argument.
  19303. - If it is a plain list item, turn all plain list items into headings.
  19304. When converting a line into a heading, the number of stars is chosen
  19305. such that the lines become children of the current entry. However,
  19306. when a numeric prefix argument is given, its value determines the
  19307. number of stars to add."
  19308. (interactive "P")
  19309. (let ((skip-blanks
  19310. (function
  19311. ;; Return beginning of first non-blank line, starting from
  19312. ;; line at POS.
  19313. (lambda (pos)
  19314. (save-excursion
  19315. (goto-char pos)
  19316. (while (org-at-comment-p) (forward-line))
  19317. (skip-chars-forward " \r\t\n")
  19318. (point-at-bol)))))
  19319. beg end toggled)
  19320. ;; Determine boundaries of changes. If a universal prefix has
  19321. ;; been given, put the list in a region. If region ends at a bol,
  19322. ;; do not consider the last line to be in the region.
  19323. (when (and current-prefix-arg (org-at-item-p))
  19324. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19325. (org-mark-element))
  19326. (if (org-region-active-p)
  19327. (setq beg (funcall skip-blanks (region-beginning))
  19328. end (copy-marker (save-excursion
  19329. (goto-char (region-end))
  19330. (if (bolp) (point) (point-at-eol)))))
  19331. (setq beg (funcall skip-blanks (point-at-bol))
  19332. end (copy-marker (point-at-eol))))
  19333. ;; Ensure inline tasks don't count as headings.
  19334. (org-with-limited-levels
  19335. (save-excursion
  19336. (goto-char beg)
  19337. (cond
  19338. ;; Case 1. Started at an heading: de-star headings.
  19339. ((org-at-heading-p)
  19340. (while (< (point) end)
  19341. (when (org-at-heading-p t)
  19342. (looking-at org-outline-regexp) (replace-match "")
  19343. (setq toggled t))
  19344. (forward-line)))
  19345. ;; Case 2. Started at an item: change items into headlines.
  19346. ;; One star will be added by `org-list-to-subtree'.
  19347. ((org-at-item-p)
  19348. (while (< (point) end)
  19349. (when (org-at-item-p)
  19350. ;; Pay attention to cases when region ends before list.
  19351. (let* ((struct (org-list-struct))
  19352. (list-end
  19353. (min (org-list-get-bottom-point struct) (1+ end))))
  19354. (save-restriction
  19355. (narrow-to-region (point) list-end)
  19356. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19357. (setq toggled t))
  19358. (forward-line)))
  19359. ;; Case 3. Started at normal text: make every line an heading,
  19360. ;; skipping headlines and items.
  19361. (t (let* ((stars
  19362. (make-string
  19363. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19364. (add-stars
  19365. (cond (nstars "") ; stars from prefix only
  19366. ((equal stars "") "*") ; before first heading
  19367. (org-odd-levels-only "**") ; inside heading, odd
  19368. (t "*"))) ; inside heading, oddeven
  19369. (rpl (concat stars add-stars " "))
  19370. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19371. (while (< (point) (if (equal nstars '(4)) lend end))
  19372. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19373. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19374. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19375. (forward-line)))))))
  19376. (unless toggled (message "Cannot toggle heading from here"))))
  19377. (defun org-meta-return (&optional arg)
  19378. "Insert a new heading or wrap a region in a table.
  19379. Calls `org-insert-heading', `org-insert-item' or
  19380. `org-table-wrap-region', depending on context. When called with
  19381. an argument, unconditionally call `org-insert-heading'."
  19382. (interactive "P")
  19383. (org-check-before-invisible-edit 'insert)
  19384. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19385. (call-interactively (cond (arg #'org-insert-heading)
  19386. ((org-at-table-p) #'org-table-wrap-region)
  19387. ((org-in-item-p) #'org-insert-item)
  19388. (t #'org-insert-heading)))))
  19389. ;;; Menu entries
  19390. (defsubst org-in-subtree-not-table-p ()
  19391. "Are we in a subtree and not in a table?"
  19392. (and (not (org-before-first-heading-p))
  19393. (not (org-at-table-p))))
  19394. ;; Define the Org mode menus
  19395. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19396. '("Tbl"
  19397. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19398. ["Next Field" org-cycle (org-at-table-p)]
  19399. ["Previous Field" org-shifttab (org-at-table-p)]
  19400. ["Next Row" org-return (org-at-table-p)]
  19401. "--"
  19402. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19403. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19404. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19405. "--"
  19406. ("Column"
  19407. ["Move Column Left" org-metaleft (org-at-table-p)]
  19408. ["Move Column Right" org-metaright (org-at-table-p)]
  19409. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19410. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19411. ("Row"
  19412. ["Move Row Up" org-metaup (org-at-table-p)]
  19413. ["Move Row Down" org-metadown (org-at-table-p)]
  19414. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19415. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19416. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19417. "--"
  19418. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19419. ("Rectangle"
  19420. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19421. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19422. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19423. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19424. "--"
  19425. ("Calculate"
  19426. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19427. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19428. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19429. "--"
  19430. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19431. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19432. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19433. "--"
  19434. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19435. "--"
  19436. ["Sum Column/Rectangle" org-table-sum
  19437. (or (org-at-table-p) (org-region-active-p))]
  19438. ["Which Column?" org-table-current-column (org-at-table-p)])
  19439. ["Debug Formulas"
  19440. org-table-toggle-formula-debugger
  19441. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19442. ["Show Col/Row Numbers"
  19443. org-table-toggle-coordinate-overlays
  19444. :style toggle
  19445. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19446. "--"
  19447. ["Create" org-table-create (and (not (org-at-table-p))
  19448. org-enable-table-editor)]
  19449. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19450. ["Import from File" org-table-import (not (org-at-table-p))]
  19451. ["Export to File" org-table-export (org-at-table-p)]
  19452. "--"
  19453. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19454. "--"
  19455. ("Plot"
  19456. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19457. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19458. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19459. '("Org"
  19460. ("Show/Hide"
  19461. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19462. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19463. ["Sparse Tree..." org-sparse-tree t]
  19464. ["Reveal Context" org-reveal t]
  19465. ["Show All" outline-show-all t]
  19466. "--"
  19467. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19468. "--"
  19469. ["New Heading" org-insert-heading t]
  19470. ("Navigate Headings"
  19471. ["Up" outline-up-heading t]
  19472. ["Next" outline-next-visible-heading t]
  19473. ["Previous" outline-previous-visible-heading t]
  19474. ["Next Same Level" outline-forward-same-level t]
  19475. ["Previous Same Level" outline-backward-same-level t]
  19476. "--"
  19477. ["Jump" org-goto t])
  19478. ("Edit Structure"
  19479. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19480. "--"
  19481. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19482. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19483. "--"
  19484. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19485. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19486. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19487. "--"
  19488. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19489. "--"
  19490. ["Copy visible text" org-copy-visible t]
  19491. "--"
  19492. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19493. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19494. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19495. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19496. "--"
  19497. ["Sort Region/Children" org-sort t]
  19498. "--"
  19499. ["Convert to odd levels" org-convert-to-odd-levels t]
  19500. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19501. ("Editing"
  19502. ["Emphasis..." org-emphasize t]
  19503. ["Edit Source Example" org-edit-special t]
  19504. "--"
  19505. ["Footnote new/jump" org-footnote-action t]
  19506. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19507. ("Archive"
  19508. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19509. "--"
  19510. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19511. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19512. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19513. )
  19514. "--"
  19515. ("Hyperlinks"
  19516. ["Store Link (Global)" org-store-link t]
  19517. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19518. ["Insert Link" org-insert-link t]
  19519. ["Follow Link" org-open-at-point t]
  19520. "--"
  19521. ["Next link" org-next-link t]
  19522. ["Previous link" org-previous-link t]
  19523. "--"
  19524. ["Descriptive Links"
  19525. org-toggle-link-display
  19526. :style radio
  19527. :selected org-descriptive-links
  19528. ]
  19529. ["Literal Links"
  19530. org-toggle-link-display
  19531. :style radio
  19532. :selected (not org-descriptive-links)])
  19533. "--"
  19534. ("TODO Lists"
  19535. ["TODO/DONE/-" org-todo t]
  19536. ("Select keyword"
  19537. ["Next keyword" org-shiftright (org-at-heading-p)]
  19538. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19539. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19540. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19541. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19542. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19543. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19544. "--"
  19545. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19546. :selected org-enforce-todo-dependencies :style toggle :active t]
  19547. "Settings for tree at point"
  19548. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19549. :selected (org-entry-get nil "ORDERED")
  19550. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19551. ["Do Children parallel" org-toggle-ordered-property :style radio
  19552. :selected (not (org-entry-get nil "ORDERED"))
  19553. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19554. "--"
  19555. ["Set Priority" org-priority t]
  19556. ["Priority Up" org-shiftup t]
  19557. ["Priority Down" org-shiftdown t]
  19558. "--"
  19559. ["Get news from all feeds" org-feed-update-all t]
  19560. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19561. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19562. ("TAGS and Properties"
  19563. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19564. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19565. "--"
  19566. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19567. ["Column view of properties" org-columns t]
  19568. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19569. ("Dates and Scheduling"
  19570. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19571. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19572. ("Change Date"
  19573. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19574. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19575. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19576. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19577. ["Compute Time Range" org-evaluate-time-range t]
  19578. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19579. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19580. "--"
  19581. ["Custom time format" org-toggle-time-stamp-overlays
  19582. :style radio :selected org-display-custom-times]
  19583. "--"
  19584. ["Goto Calendar" org-goto-calendar t]
  19585. ["Date from Calendar" org-date-from-calendar t]
  19586. "--"
  19587. ["Start/Restart Timer" org-timer-start t]
  19588. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19589. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19590. ["Insert Timer String" org-timer t]
  19591. ["Insert Timer Item" org-timer-item t])
  19592. ("Logging work"
  19593. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19594. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19595. ["Clock out" org-clock-out t]
  19596. ["Clock cancel" org-clock-cancel t]
  19597. "--"
  19598. ["Mark as default task" org-clock-mark-default-task t]
  19599. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19600. ["Goto running clock" org-clock-goto t]
  19601. "--"
  19602. ["Display times" org-clock-display t]
  19603. ["Create clock table" org-clock-report t]
  19604. "--"
  19605. ["Record DONE time"
  19606. (progn (setq org-log-done (not org-log-done))
  19607. (message "Switching to %s will %s record a timestamp"
  19608. (car org-done-keywords)
  19609. (if org-log-done "automatically" "not")))
  19610. :style toggle :selected org-log-done])
  19611. "--"
  19612. ["Agenda Command..." org-agenda t]
  19613. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19614. ("File List for Agenda")
  19615. ("Special views current file"
  19616. ["TODO Tree" org-show-todo-tree t]
  19617. ["Check Deadlines" org-check-deadlines t]
  19618. ["Tags/Property tree" org-match-sparse-tree t])
  19619. "--"
  19620. ["Export/Publish..." org-export-dispatch t]
  19621. ("LaTeX"
  19622. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19623. :selected org-cdlatex-mode]
  19624. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19625. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19626. ["Modify math symbol" org-cdlatex-math-modify
  19627. (org-inside-LaTeX-fragment-p)]
  19628. ["Insert citation" org-reftex-citation t])
  19629. "--"
  19630. ("MobileOrg"
  19631. ["Push Files and Views" org-mobile-push t]
  19632. ["Get Captured and Flagged" org-mobile-pull t]
  19633. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19634. "--"
  19635. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19636. "--"
  19637. ("Documentation"
  19638. ["Show Version" org-version t]
  19639. ["Info Documentation" org-info t])
  19640. ("Customize"
  19641. ["Browse Org Group" org-customize t]
  19642. "--"
  19643. ["Expand This Menu" org-create-customize-menu
  19644. (fboundp 'customize-menu-create)])
  19645. ["Send bug report" org-submit-bug-report t]
  19646. "--"
  19647. ("Refresh/Reload"
  19648. ["Refresh setup current buffer" org-mode-restart t]
  19649. ["Reload Org (after update)" org-reload t]
  19650. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19651. ))
  19652. (defun org-info (&optional node)
  19653. "Read documentation for Org in the info system.
  19654. With optional NODE, go directly to that node."
  19655. (interactive)
  19656. (info (format "(org)%s" (or node ""))))
  19657. ;;;###autoload
  19658. (defun org-submit-bug-report ()
  19659. "Submit a bug report on Org via mail.
  19660. Don't hesitate to report any problems or inaccurate documentation.
  19661. If you don't have setup sending mail from (X)Emacs, please copy the
  19662. output buffer into your mail program, as it gives us important
  19663. information about your Org version and configuration."
  19664. (interactive)
  19665. (require 'reporter)
  19666. (defvar reporter-prompt-for-summary-p)
  19667. (org-load-modules-maybe)
  19668. (org-require-autoloaded-modules)
  19669. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19670. (reporter-submit-bug-report
  19671. "emacs-orgmode@gnu.org"
  19672. (org-version nil 'full)
  19673. (let (list)
  19674. (save-window-excursion
  19675. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19676. (delete-other-windows)
  19677. (erase-buffer)
  19678. (insert "You are about to submit a bug report to the Org mailing list.
  19679. We would like to add your full Org and Outline configuration to the
  19680. bug report. This greatly simplifies the work of the maintainer and
  19681. other experts on the mailing list.
  19682. HOWEVER, some variables you have customized may contain private
  19683. information. The names of customers, colleagues, or friends, might
  19684. appear in the form of file names, tags, todo states, or search strings.
  19685. If you answer yes to the prompt, you might want to check and remove
  19686. such private information before sending the email.")
  19687. (add-text-properties (point-min) (point-max) '(face org-warning))
  19688. (when (yes-or-no-p "Include your Org configuration ")
  19689. (mapatoms
  19690. (lambda (v)
  19691. (and (boundp v)
  19692. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19693. (or (and (symbol-value v)
  19694. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19695. (and
  19696. (get v 'custom-type) (get v 'standard-value)
  19697. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19698. (push v list)))))
  19699. (kill-buffer (get-buffer "*Warn about privacy*"))
  19700. list))
  19701. nil nil
  19702. "Remember to cover the basics, that is, what you expected to happen and
  19703. what in fact did happen. You don't know how to make a good report? See
  19704. http://orgmode.org/manual/Feedback.html#Feedback
  19705. Your bug report will be posted to the Org mailing list.
  19706. ------------------------------------------------------------------------")
  19707. (save-excursion
  19708. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19709. (replace-match "\\1Bug: \\3 [\\2]")))))
  19710. (defun org-install-agenda-files-menu ()
  19711. (let ((bl (buffer-list)))
  19712. (save-excursion
  19713. (while bl
  19714. (set-buffer (pop bl))
  19715. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19716. (when (derived-mode-p 'org-mode)
  19717. (easy-menu-change
  19718. '("Org") "File List for Agenda"
  19719. (append
  19720. (list
  19721. ["Edit File List" (org-edit-agenda-file-list) t]
  19722. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19723. ["Remove Current File from List" org-remove-file t]
  19724. ["Cycle through agenda files" org-cycle-agenda-files t]
  19725. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19726. "--")
  19727. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19728. ;;;; Documentation
  19729. (defun org-require-autoloaded-modules ()
  19730. (interactive)
  19731. (mapc #'require
  19732. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19733. org-table org-timer)))
  19734. ;;;###autoload
  19735. (defun org-reload (&optional uncompiled)
  19736. "Reload all org lisp files.
  19737. With prefix arg UNCOMPILED, load the uncompiled versions."
  19738. (interactive "P")
  19739. (require 'loadhist)
  19740. (let* ((org-dir (org-find-library-dir "org"))
  19741. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19742. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19743. (remove-re (format "\\`%s\\'"
  19744. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19745. (feats (delete-dups
  19746. (mapcar 'file-name-sans-extension
  19747. (mapcar 'file-name-nondirectory
  19748. (delq nil
  19749. (mapcar 'feature-file
  19750. features))))))
  19751. (lfeat (append
  19752. (sort
  19753. (setq feats
  19754. (delq nil (mapcar
  19755. (lambda (f)
  19756. (if (and (string-match feature-re f)
  19757. (not (string-match remove-re f)))
  19758. f nil))
  19759. feats)))
  19760. 'string-lessp)
  19761. (list "org-version" "org")))
  19762. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19763. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19764. load-uncore load-misses)
  19765. (setq load-misses
  19766. (delq 't
  19767. (mapcar (lambda (f)
  19768. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19769. (and (string= org-dir contrib-dir)
  19770. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19771. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19772. (add-to-list 'load-uncore f 'append)
  19773. 't)
  19774. f))
  19775. lfeat)))
  19776. (when load-uncore
  19777. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19778. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19779. (if load-misses
  19780. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19781. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19782. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19783. ;;;###autoload
  19784. (defun org-customize ()
  19785. "Call the customize function with org as argument."
  19786. (interactive)
  19787. (org-load-modules-maybe)
  19788. (org-require-autoloaded-modules)
  19789. (customize-browse 'org))
  19790. (defun org-create-customize-menu ()
  19791. "Create a full customization menu for Org mode, insert it into the menu."
  19792. (interactive)
  19793. (org-load-modules-maybe)
  19794. (org-require-autoloaded-modules)
  19795. (if (fboundp 'customize-menu-create)
  19796. (progn
  19797. (easy-menu-change
  19798. '("Org") "Customize"
  19799. `(["Browse Org group" org-customize t]
  19800. "--"
  19801. ,(customize-menu-create 'org)
  19802. ["Set" Custom-set t]
  19803. ["Save" Custom-save t]
  19804. ["Reset to Current" Custom-reset-current t]
  19805. ["Reset to Saved" Custom-reset-saved t]
  19806. ["Reset to Standard Settings" Custom-reset-standard t]))
  19807. (message "\"Org\"-menu now contains full customization menu"))
  19808. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19809. ;;;; Miscellaneous stuff
  19810. ;;; Generally useful functions
  19811. (defun org-get-at-eol (property n)
  19812. "Get text property PROPERTY at the end of line less N characters."
  19813. (get-text-property (- (point-at-eol) n) property))
  19814. (defun org-find-text-property-in-string (prop s)
  19815. "Return the first non-nil value of property PROP in string S."
  19816. (or (get-text-property 0 prop s)
  19817. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19818. prop s)))
  19819. (defun org-display-warning (message)
  19820. "Display the given MESSAGE as a warning."
  19821. (display-warning 'org message :warning))
  19822. (defun org-eval (form)
  19823. "Eval FORM and return result."
  19824. (condition-case error
  19825. (eval form)
  19826. (error (format "%%![Error: %s]" error))))
  19827. (defun org-in-clocktable-p ()
  19828. "Check if the cursor is in a clocktable."
  19829. (let ((pos (point)) start)
  19830. (save-excursion
  19831. (end-of-line 1)
  19832. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19833. (setq start (match-beginning 0))
  19834. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19835. (>= (match-end 0) pos)
  19836. start))))
  19837. (defun org-in-verbatim-emphasis ()
  19838. (save-match-data
  19839. (and (org-in-regexp org-verbatim-re 2)
  19840. (>= (point) (match-beginning 3))
  19841. (<= (point) (match-end 4)))))
  19842. (defun org-overlay-display (ovl text &optional face evap)
  19843. "Make overlay OVL display TEXT with face FACE."
  19844. (overlay-put ovl 'display text)
  19845. (if face (overlay-put ovl 'face face))
  19846. (if evap (overlay-put ovl 'evaporate t)))
  19847. (defun org-overlay-before-string (ovl text &optional face evap)
  19848. "Make overlay OVL display TEXT with face FACE."
  19849. (if face (org-add-props text nil 'face face))
  19850. (overlay-put ovl 'before-string text)
  19851. (if evap (overlay-put ovl 'evaporate t)))
  19852. (defun org-find-overlays (prop &optional pos delete)
  19853. "Find all overlays specifying PROP at POS or point.
  19854. If DELETE is non-nil, delete all those overlays."
  19855. (let (found)
  19856. (dolist (ov (overlays-at (or pos (point))) found)
  19857. (cond ((not (overlay-get ov prop)))
  19858. (delete (delete-overlay ov))
  19859. (t (push ov found))))))
  19860. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19861. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19862. (if (and marker (marker-buffer marker)
  19863. (buffer-live-p (marker-buffer marker)))
  19864. (progn
  19865. (pop-to-buffer-same-window (marker-buffer marker))
  19866. (when (or (> marker (point-max)) (< marker (point-min)))
  19867. (widen))
  19868. (goto-char marker)
  19869. (org-show-context 'org-goto))
  19870. (if bookmark
  19871. (bookmark-jump bookmark)
  19872. (error "Cannot find location"))))
  19873. (defun org-quote-csv-field (s)
  19874. "Quote field for inclusion in CSV material."
  19875. (if (string-match "[\",]" s)
  19876. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19877. s))
  19878. (defun org-force-self-insert (N)
  19879. "Needed to enforce self-insert under remapping."
  19880. (interactive "p")
  19881. (self-insert-command N))
  19882. (defun org-string-width (s)
  19883. "Compute width of string, ignoring invisible characters.
  19884. This ignores character with invisibility property `org-link', and also
  19885. characters with property `org-cwidth', because these will become invisible
  19886. upon the next fontification round."
  19887. (let (b l)
  19888. (when (or (eq t buffer-invisibility-spec)
  19889. (assq 'org-link buffer-invisibility-spec))
  19890. (while (setq b (text-property-any 0 (length s)
  19891. 'invisible 'org-link s))
  19892. (setq s (concat (substring s 0 b)
  19893. (substring s (or (next-single-property-change
  19894. b 'invisible s)
  19895. (length s)))))))
  19896. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  19897. (setq s (concat (substring s 0 b)
  19898. (substring s (or (next-single-property-change
  19899. b 'org-cwidth s)
  19900. (length s))))))
  19901. (setq l (string-width s) b -1)
  19902. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  19903. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  19904. l))
  19905. (defun org-shorten-string (s maxlength)
  19906. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19907. If the string is shorter or has length MAXLENGTH, just return the
  19908. original string. If it is longer, the functions finds a space in the
  19909. string, breaks this string off at that locations and adds three dots
  19910. as ellipsis. Including the ellipsis, the string will not be longer
  19911. than MAXLENGTH. If finding a good breaking point in the string does
  19912. not work, the string is just chopped off in the middle of a word
  19913. if necessary."
  19914. (if (<= (length s) maxlength)
  19915. s
  19916. (let* ((n (max (- maxlength 4) 1))
  19917. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19918. (if (string-match re s)
  19919. (concat (match-string 1 s) "...")
  19920. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19921. (defun org-get-indentation (&optional line)
  19922. "Get the indentation of the current line, interpreting tabs.
  19923. When LINE is given, assume it represents a line and compute its indentation."
  19924. (if line
  19925. (when (string-match "^ *" (org-remove-tabs line))
  19926. (match-end 0))
  19927. (save-excursion
  19928. (beginning-of-line 1)
  19929. (skip-chars-forward " \t")
  19930. (current-column))))
  19931. (defun org-get-string-indentation (s)
  19932. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19933. (let ((n -1) (i 0) (w tab-width) c)
  19934. (catch 'exit
  19935. (while (< (setq n (1+ n)) (length s))
  19936. (setq c (aref s n))
  19937. (cond ((= c ?\ ) (setq i (1+ i)))
  19938. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19939. (t (throw 'exit t)))))
  19940. i))
  19941. (defun org-remove-tabs (s &optional width)
  19942. "Replace tabulators in S with spaces.
  19943. Assumes that s is a single line, starting in column 0."
  19944. (setq width (or width tab-width))
  19945. (while (string-match "\t" s)
  19946. (setq s (replace-match
  19947. (make-string
  19948. (- (* width (/ (+ (match-beginning 0) width) width))
  19949. (match-beginning 0)) ?\ )
  19950. t t s)))
  19951. s)
  19952. (defun org-fix-indentation (line ind)
  19953. "Fix indentation in LINE.
  19954. IND is a cons cell with target and minimum indentation.
  19955. If the current indentation in LINE is smaller than the minimum,
  19956. leave it alone. If it is larger than ind, set it to the target."
  19957. (let* ((l (org-remove-tabs line))
  19958. (i (org-get-indentation l))
  19959. (i1 (car ind)) (i2 (cdr ind)))
  19960. (when (>= i i2) (setq l (substring line i2)))
  19961. (if (> i1 0)
  19962. (concat (make-string i1 ?\ ) l)
  19963. l)))
  19964. (defun org-remove-indentation (code &optional n)
  19965. "Remove maximum common indentation in string CODE and return it.
  19966. N may optionally be the number of columns to remove. Return CODE
  19967. as-is if removal failed."
  19968. (with-temp-buffer
  19969. (insert code)
  19970. (if (org-do-remove-indentation n) (buffer-string) code)))
  19971. (defun org-do-remove-indentation (&optional n)
  19972. "Remove the maximum common indentation from the buffer.
  19973. When optional argument N is a positive integer, remove exactly
  19974. that much characters from indentation, if possible. Return nil
  19975. if it fails."
  19976. (catch :exit
  19977. (goto-char (point-min))
  19978. ;; Find maximum common indentation, if not specified.
  19979. (let ((n (or n
  19980. (let ((min-ind (point-max)))
  19981. (save-excursion
  19982. (while (re-search-forward "^[ \t]*\\S-" nil t)
  19983. (let ((ind (1- (current-column))))
  19984. (if (zerop ind) (throw :exit nil)
  19985. (setq min-ind (min min-ind ind))))))
  19986. min-ind))))
  19987. (if (zerop n) (throw :exit nil)
  19988. ;; Remove exactly N indentation, but give up if not possible.
  19989. (while (not (eobp))
  19990. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  19991. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  19992. ((< ind n) (throw :exit nil))
  19993. (t (indent-line-to (- ind n))))
  19994. (forward-line)))
  19995. ;; Signal success.
  19996. t))))
  19997. (defun org-fill-template (template alist)
  19998. "Find each %key of ALIST in TEMPLATE and replace it."
  19999. (let ((case-fold-search nil))
  20000. (dolist (entry (sort (copy-sequence alist)
  20001. (lambda (a b) (< (length (car a)) (length (car b))))))
  20002. (setq template
  20003. (replace-regexp-in-string
  20004. (concat "%" (regexp-quote (car entry)))
  20005. (or (cdr entry) "") template t t)))
  20006. template))
  20007. (defun org-base-buffer (buffer)
  20008. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20009. (if (not buffer)
  20010. buffer
  20011. (or (buffer-base-buffer buffer)
  20012. buffer)))
  20013. (defun org-wrap (string &optional width lines)
  20014. "Wrap string to either a number of lines, or a width in characters.
  20015. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20016. that costs. If there is a word longer than WIDTH, the text is actually
  20017. wrapped to the length of that word.
  20018. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20019. many lines, whatever width that takes.
  20020. The return value is a list of lines, without newlines at the end."
  20021. (let* ((words (org-split-string string "[ \t\n]+"))
  20022. (maxword (apply 'max (mapcar 'org-string-width words)))
  20023. w ll)
  20024. (cond (width
  20025. (org-do-wrap words (max maxword width)))
  20026. (lines
  20027. (setq w maxword)
  20028. (setq ll (org-do-wrap words maxword))
  20029. (if (<= (length ll) lines)
  20030. ll
  20031. (setq ll words)
  20032. (while (> (length ll) lines)
  20033. (setq w (1+ w))
  20034. (setq ll (org-do-wrap words w)))
  20035. ll))
  20036. (t (error "Cannot wrap this")))))
  20037. (defun org-do-wrap (words width)
  20038. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20039. (let (lines line)
  20040. (while words
  20041. (setq line (pop words))
  20042. (while (and words (< (+ (length line) (length (car words))) width))
  20043. (setq line (concat line " " (pop words))))
  20044. (setq lines (push line lines)))
  20045. (nreverse lines)))
  20046. (defun org-split-string (string &optional separators)
  20047. "Splits STRING into substrings at SEPARATORS.
  20048. SEPARATORS is a regular expression.
  20049. No empty strings are returned if there are matches at the beginning
  20050. and end of string."
  20051. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20052. (let ((start 0) notfirst list)
  20053. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20054. (if (and notfirst
  20055. (= start (match-beginning 0))
  20056. (< start (length string)))
  20057. (1+ start) start))
  20058. (< (match-beginning 0) (length string)))
  20059. (setq notfirst t)
  20060. (or (eq (match-beginning 0) 0)
  20061. (and (eq (match-beginning 0) (match-end 0))
  20062. (eq (match-beginning 0) start))
  20063. (push (substring string start (match-beginning 0)) list))
  20064. (setq start (match-end 0)))
  20065. (or (eq start (length string))
  20066. (push (substring string start) list))
  20067. (nreverse list)))
  20068. (defun org-quote-vert (s)
  20069. "Replace \"|\" with \"\\vert\"."
  20070. (while (string-match "|" s)
  20071. (setq s (replace-match "\\vert" t t s)))
  20072. s)
  20073. (defun org-uuidgen-p (s)
  20074. "Is S an ID created by UUIDGEN?"
  20075. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20076. (defun org-in-src-block-p (&optional inside)
  20077. "Whether point is in a code source block.
  20078. When INSIDE is non-nil, don't consider we are within a src block
  20079. when point is at #+BEGIN_SRC or #+END_SRC."
  20080. (let ((case-fold-search t))
  20081. (or (and (eq (get-char-property (point) 'src-block) t))
  20082. (and (not inside)
  20083. (save-match-data
  20084. (save-excursion
  20085. (beginning-of-line)
  20086. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20087. (defun org-context ()
  20088. "Return a list of contexts of the current cursor position.
  20089. If several contexts apply, all are returned.
  20090. Each context entry is a list with a symbol naming the context, and
  20091. two positions indicating start and end of the context. Possible
  20092. contexts are:
  20093. :headline anywhere in a headline
  20094. :headline-stars on the leading stars in a headline
  20095. :todo-keyword on a TODO keyword (including DONE) in a headline
  20096. :tags on the TAGS in a headline
  20097. :priority on the priority cookie in a headline
  20098. :item on the first line of a plain list item
  20099. :item-bullet on the bullet/number of a plain list item
  20100. :checkbox on the checkbox in a plain list item
  20101. :table in an Org table
  20102. :table-special on a special filed in a table
  20103. :table-table in a table.el table
  20104. :clocktable in a clocktable
  20105. :src-block in a source block
  20106. :link on a hyperlink
  20107. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20108. :target on a <<target>>
  20109. :radio-target on a <<<radio-target>>>
  20110. :latex-fragment on a LaTeX fragment
  20111. :latex-preview on a LaTeX fragment with overlaid preview image
  20112. This function expects the position to be visible because it uses font-lock
  20113. faces as a help to recognize the following contexts: :table-special, :link,
  20114. and :keyword."
  20115. (let* ((f (get-text-property (point) 'face))
  20116. (faces (if (listp f) f (list f)))
  20117. (case-fold-search t)
  20118. (p (point)) clist o)
  20119. ;; First the large context
  20120. (cond
  20121. ((org-at-heading-p t)
  20122. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20123. (when (progn
  20124. (beginning-of-line 1)
  20125. (looking-at org-todo-line-tags-regexp))
  20126. (push (org-point-in-group p 1 :headline-stars) clist)
  20127. (push (org-point-in-group p 2 :todo-keyword) clist)
  20128. (push (org-point-in-group p 4 :tags) clist))
  20129. (goto-char p)
  20130. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20131. (when (looking-at "\\[#[A-Z0-9]\\]")
  20132. (push (org-point-in-group p 0 :priority) clist)))
  20133. ((org-at-item-p)
  20134. (push (org-point-in-group p 2 :item-bullet) clist)
  20135. (push (list :item (point-at-bol)
  20136. (save-excursion (org-end-of-item) (point)))
  20137. clist)
  20138. (and (org-at-item-checkbox-p)
  20139. (push (org-point-in-group p 0 :checkbox) clist)))
  20140. ((org-at-table-p)
  20141. (push (list :table (org-table-begin) (org-table-end)) clist)
  20142. (when (memq 'org-formula faces)
  20143. (push (list :table-special
  20144. (previous-single-property-change p 'face)
  20145. (next-single-property-change p 'face)) clist)))
  20146. ((org-at-table-p 'any)
  20147. (push (list :table-table) clist)))
  20148. (goto-char p)
  20149. (let ((case-fold-search t))
  20150. ;; New the "medium" contexts: clocktables, source blocks
  20151. (cond ((org-in-clocktable-p)
  20152. (push (list :clocktable
  20153. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20154. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20155. (match-beginning 1))
  20156. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20157. (match-end 0))) clist))
  20158. ((org-in-src-block-p)
  20159. (push (list :src-block
  20160. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20161. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20162. (match-beginning 1))
  20163. (and (search-forward "#+END_SRC" nil t)
  20164. (match-beginning 0))) clist))))
  20165. (goto-char p)
  20166. ;; Now the small context
  20167. (cond
  20168. ((org-at-timestamp-p)
  20169. (push (org-point-in-group p 0 :timestamp) clist))
  20170. ((memq 'org-link faces)
  20171. (push (list :link
  20172. (previous-single-property-change p 'face)
  20173. (next-single-property-change p 'face)) clist))
  20174. ((memq 'org-special-keyword faces)
  20175. (push (list :keyword
  20176. (previous-single-property-change p 'face)
  20177. (next-single-property-change p 'face)) clist))
  20178. ((org-at-target-p)
  20179. (push (org-point-in-group p 0 :target) clist)
  20180. (goto-char (1- (match-beginning 0)))
  20181. (when (looking-at org-radio-target-regexp)
  20182. (push (org-point-in-group p 0 :radio-target) clist))
  20183. (goto-char p))
  20184. ((setq o (cl-some
  20185. (lambda (o)
  20186. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20187. o))
  20188. (overlays-at (point))))
  20189. (push (list :latex-fragment
  20190. (overlay-start o) (overlay-end o)) clist)
  20191. (push (list :latex-preview
  20192. (overlay-start o) (overlay-end o)) clist))
  20193. ((org-inside-LaTeX-fragment-p)
  20194. ;; FIXME: positions wrong.
  20195. (push (list :latex-fragment (point) (point)) clist)))
  20196. (setq clist (nreverse (delq nil clist)))
  20197. clist))
  20198. (defun org-in-regexp (regexp &optional nlines visually)
  20199. "Check if point is inside a match of REGEXP.
  20200. Normally only the current line is checked, but you can include
  20201. NLINES extra lines around point into the search. If VISUALLY is
  20202. set, require that the cursor is not after the match but really
  20203. on, so that the block visually is on the match.
  20204. Return nil or a cons cell (BEG . END) where BEG and END are,
  20205. respectively, the positions at the beginning and the end of the
  20206. match."
  20207. (catch :exit
  20208. (let ((pos (point))
  20209. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20210. (save-excursion
  20211. (beginning-of-line (- 1 (or nlines 0)))
  20212. (while (and (re-search-forward regexp eol t)
  20213. (<= (match-beginning 0) pos))
  20214. (let ((end (match-end 0)))
  20215. (when (or (> end pos) (and (= end pos) (not visually)))
  20216. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20217. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20218. "Non-nil when point is between matches of START-RE and END-RE.
  20219. Also return a non-nil value when point is on one of the matches.
  20220. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20221. buffer positions. Default values are the positions of headlines
  20222. surrounding the point.
  20223. The functions returns a cons cell whose car (resp. cdr) is the
  20224. position before START-RE (resp. after END-RE)."
  20225. (save-match-data
  20226. (let ((pos (point))
  20227. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20228. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20229. beg end)
  20230. (save-excursion
  20231. ;; Point is on a block when on START-RE or if START-RE can be
  20232. ;; found before it...
  20233. (and (or (org-in-regexp start-re)
  20234. (re-search-backward start-re limit-up t))
  20235. (setq beg (match-beginning 0))
  20236. ;; ... and END-RE after it...
  20237. (goto-char (match-end 0))
  20238. (re-search-forward end-re limit-down t)
  20239. (> (setq end (match-end 0)) pos)
  20240. ;; ... without another START-RE in-between.
  20241. (goto-char (match-beginning 0))
  20242. (not (re-search-backward start-re (1+ beg) t))
  20243. ;; Return value.
  20244. (cons beg end))))))
  20245. (defun org-in-block-p (names)
  20246. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20247. NAMES is a list of strings containing names of blocks.
  20248. Return first block name matched, or nil. Beware that in case of
  20249. nested blocks, the returned name may not belong to the closest
  20250. block from point."
  20251. (save-match-data
  20252. (catch 'exit
  20253. (let ((case-fold-search t)
  20254. (lim-up (save-excursion (outline-previous-heading)))
  20255. (lim-down (save-excursion (outline-next-heading))))
  20256. (dolist (name names)
  20257. (let ((n (regexp-quote name)))
  20258. (when (org-between-regexps-p
  20259. (concat "^[ \t]*#\\+begin_" n)
  20260. (concat "^[ \t]*#\\+end_" n)
  20261. lim-up lim-down)
  20262. (throw 'exit n)))))
  20263. nil)))
  20264. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20265. "Call `multi-occur' with buffers for all agenda files."
  20266. (interactive "sOrg-files matching: ")
  20267. (let* ((files (org-agenda-files))
  20268. (tnames (mapcar #'file-truename files))
  20269. (extra org-agenda-text-search-extra-files))
  20270. (when (eq (car extra) 'agenda-archives)
  20271. (setq extra (cdr extra))
  20272. (setq files (org-add-archive-files files)))
  20273. (dolist (f extra)
  20274. (unless (member (file-truename f) tnames)
  20275. (unless (member f files) (setq files (append files (list f))))
  20276. (setq tnames (append tnames (list (file-truename f))))))
  20277. (multi-occur
  20278. (mapcar (lambda (x)
  20279. (with-current-buffer
  20280. ;; FIXME: Why not just (find-file-noselect x)?
  20281. ;; Is it to avoid the "revert buffer" prompt?
  20282. (or (get-file-buffer x) (find-file-noselect x))
  20283. (widen)
  20284. (current-buffer)))
  20285. files)
  20286. regexp)))
  20287. (add-hook 'occur-mode-find-occurrence-hook
  20288. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20289. (defun org-occur-link-in-agenda-files ()
  20290. "Create a link and search for it in the agendas.
  20291. The link is not stored in `org-stored-links', it is just created
  20292. for the search purpose."
  20293. (interactive)
  20294. (let ((link (condition-case nil
  20295. (org-store-link nil)
  20296. (error "Unable to create a link to here"))))
  20297. (org-occur-in-agenda-files (regexp-quote link))))
  20298. (defun org-reverse-string (string)
  20299. "Return the reverse of STRING."
  20300. (apply 'string (reverse (string-to-list string))))
  20301. ;; defsubst org-uniquify must be defined before first use
  20302. (defun org-uniquify-alist (alist)
  20303. "Merge elements of ALIST with the same key.
  20304. For example, in this alist:
  20305. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20306. => \\='((a 1 3) (b 2))
  20307. merge (a 1) and (a 3) into (a 1 3).
  20308. The function returns the new ALIST."
  20309. (let (rtn)
  20310. (dolist (e alist rtn)
  20311. (let (n)
  20312. (if (not (assoc (car e) rtn))
  20313. (push e rtn)
  20314. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20315. (setq rtn (assq-delete-all (car e) rtn))
  20316. (push n rtn))))))
  20317. (defun org-delete-all (elts list)
  20318. "Remove all elements in ELTS from LIST.
  20319. Comparison is done with `equal'. It is a destructive operation
  20320. that may remove elements by altering the list structure."
  20321. (while elts
  20322. (setq list (delete (pop elts) list)))
  20323. list)
  20324. (defun org-back-over-empty-lines ()
  20325. "Move backwards over whitespace, to the beginning of the first empty line.
  20326. Returns the number of empty lines passed."
  20327. (let ((pos (point)))
  20328. (if (cdr (assq 'heading org-blank-before-new-entry))
  20329. (skip-chars-backward " \t\n\r")
  20330. (unless (eobp)
  20331. (forward-line -1)))
  20332. (beginning-of-line 2)
  20333. (goto-char (min (point) pos))
  20334. (count-lines (point) pos)))
  20335. (defun org-skip-whitespace ()
  20336. (skip-chars-forward " \t\n\r"))
  20337. (defun org-point-in-group (point group &optional context)
  20338. "Check if POINT is in match-group GROUP.
  20339. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20340. match. If the match group does not exist or point is not inside it,
  20341. return nil."
  20342. (and (match-beginning group)
  20343. (>= point (match-beginning group))
  20344. (<= point (match-end group))
  20345. (if context
  20346. (list context (match-beginning group) (match-end group))
  20347. t)))
  20348. (defun org-switch-to-buffer-other-window (&rest args)
  20349. "Switch to buffer in a second window on the current frame.
  20350. In particular, do not allow pop-up frames.
  20351. Returns the newly created buffer."
  20352. (org-no-popups
  20353. (apply 'switch-to-buffer-other-window args)))
  20354. (defun org-combine-plists (&rest plists)
  20355. "Create a single property list from all plists in PLISTS.
  20356. The process starts by copying the first list, and then setting properties
  20357. from the other lists. Settings in the last list are the most significant
  20358. ones and overrule settings in the other lists."
  20359. (let ((rtn (copy-sequence (pop plists)))
  20360. p v ls)
  20361. (while plists
  20362. (setq ls (pop plists))
  20363. (while ls
  20364. (setq p (pop ls) v (pop ls))
  20365. (setq rtn (plist-put rtn p v))))
  20366. rtn))
  20367. (defun org-replace-escapes (string table)
  20368. "Replace %-escapes in STRING with values in TABLE.
  20369. TABLE is an association list with keys like \"%a\" and string values.
  20370. The sequences in STRING may contain normal field width and padding information,
  20371. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20372. so values can contain further %-escapes if they are define later in TABLE."
  20373. (let ((tbl (copy-alist table))
  20374. (case-fold-search nil)
  20375. (pchg 0)
  20376. re rpl)
  20377. (dolist (e tbl)
  20378. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20379. (when (and (cdr e) (string-match re (cdr e)))
  20380. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20381. (safe "SREF"))
  20382. (add-text-properties 0 3 (list 'sref sref) safe)
  20383. (setcdr e (replace-match safe t t (cdr e)))))
  20384. (while (string-match re string)
  20385. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20386. (cdr e)))
  20387. (setq string (replace-match rpl t t string))))
  20388. (while (setq pchg (next-property-change pchg string))
  20389. (let ((sref (get-text-property pchg 'sref string)))
  20390. (when (and sref (string-match "SREF" string pchg))
  20391. (setq string (replace-match sref t t string)))))
  20392. string))
  20393. (defun org-find-base-buffer-visiting (file)
  20394. "Like `find-buffer-visiting' but always return the base buffer and
  20395. not an indirect buffer."
  20396. (let ((buf (or (get-file-buffer file)
  20397. (find-buffer-visiting file))))
  20398. (if buf
  20399. (or (buffer-base-buffer buf) buf)
  20400. nil)))
  20401. ;;; TODO: Only called once, from ox-odt which should probably use
  20402. ;;; org-export-inline-image-p or something.
  20403. (defun org-file-image-p (file)
  20404. "Return non-nil if FILE is an image."
  20405. (save-match-data
  20406. (string-match (image-file-name-regexp) file)))
  20407. (defun org-get-cursor-date (&optional with-time)
  20408. "Return the date at cursor in as a time.
  20409. This works in the calendar and in the agenda, anywhere else it just
  20410. returns the current time.
  20411. If WITH-TIME is non-nil, returns the time of the event at point (in
  20412. the agenda) or the current time of the day."
  20413. (let (date day defd tp hod mod)
  20414. (when with-time
  20415. (setq tp (get-text-property (point) 'time))
  20416. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20417. (setq hod (string-to-number (match-string 1 tp))
  20418. mod (string-to-number (match-string 2 tp))))
  20419. (or tp (let ((now (decode-time)))
  20420. (setq hod (nth 2 now)
  20421. mod (nth 1 now)))))
  20422. (cond
  20423. ((eq major-mode 'calendar-mode)
  20424. (setq date (calendar-cursor-to-date)
  20425. defd (encode-time 0 (or mod 0) (or hod 0)
  20426. (nth 1 date) (nth 0 date) (nth 2 date))))
  20427. ((eq major-mode 'org-agenda-mode)
  20428. (setq day (get-text-property (point) 'day))
  20429. (when day
  20430. (setq date (calendar-gregorian-from-absolute day)
  20431. defd (encode-time 0 (or mod 0) (or hod 0)
  20432. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20433. (or defd (current-time))))
  20434. (defun org-mark-subtree (&optional up)
  20435. "Mark the current subtree.
  20436. This puts point at the start of the current subtree, and mark at
  20437. the end. If a numeric prefix UP is given, move up into the
  20438. hierarchy of headlines by UP levels before marking the subtree."
  20439. (interactive "P")
  20440. (org-with-limited-levels
  20441. (cond ((org-at-heading-p) (beginning-of-line))
  20442. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20443. (t (outline-previous-visible-heading 1))))
  20444. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20445. (if (called-interactively-p 'any)
  20446. (call-interactively 'org-mark-element)
  20447. (org-mark-element)))
  20448. (defun org-file-newer-than-p (file time)
  20449. "Non-nil if FILE is newer than TIME.
  20450. FILE is a filename, as a string, TIME is a list of integers, as
  20451. returned by, e.g., `current-time'."
  20452. (and (file-exists-p file)
  20453. ;; Only compare times up to whole seconds as some file-systems
  20454. ;; (e.g. HFS+) do not retain any finer granularity. As
  20455. ;; a consequence, make sure we return non-nil when the two
  20456. ;; times are equal.
  20457. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20458. (cl-subseq time 0 2)))))
  20459. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20460. "Compile a SOURCE file using PROCESS.
  20461. PROCESS is either a function or a list of shell commands, as
  20462. strings. EXT is a file extension, without the leading dot, as
  20463. a string. It is used to check if the process actually succeeded.
  20464. PROCESS must create a file with the same base name and directory
  20465. as SOURCE, but ending with EXT. The function then returns its
  20466. filename. Otherwise, it raises an error. The error message can
  20467. then be refined by providing string ERR-MSG, which is appended to
  20468. the standard message.
  20469. If PROCESS is a function, it is called with a single argument:
  20470. the SOURCE file.
  20471. If it is a list of commands, each of them is called using
  20472. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20473. %O are replaced with, respectively, SOURCE base name, name, full
  20474. name, directory and absolute output file name. It is possible,
  20475. however, to use more place-holders by specifying them in optional
  20476. argument SPEC, as an alist following the pattern
  20477. (CHARACTER . REPLACEMENT-STRING).
  20478. When PROCESS is a list of commands, optional argument LOG-BUF can
  20479. be set to a buffer or a buffer name. `shell-command' then uses
  20480. it for output."
  20481. (let* ((base-name (file-name-base source))
  20482. (full-name (file-truename source))
  20483. (out-dir (or (file-name-directory source) "./"))
  20484. (output (expand-file-name (concat base-name "." ext) out-dir))
  20485. (time (current-time))
  20486. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20487. (save-window-excursion
  20488. (pcase process
  20489. ((pred functionp) (funcall process (shell-quote-argument source)))
  20490. ((pred consp)
  20491. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20492. (spec (append spec
  20493. `((?b . ,(shell-quote-argument base-name))
  20494. (?f . ,(shell-quote-argument source))
  20495. (?F . ,(shell-quote-argument full-name))
  20496. (?o . ,(shell-quote-argument out-dir))
  20497. (?O . ,(shell-quote-argument output))))))
  20498. (dolist (command process)
  20499. (shell-command (format-spec command spec) log-buf))
  20500. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20501. (_ (error "No valid command to process %S%s" source err-msg))))
  20502. ;; Check for process failure. Output file is expected to be
  20503. ;; located in the same directory as SOURCE.
  20504. (unless (org-file-newer-than-p output time)
  20505. (error (format "File %S wasn't produced%s" output err-msg)))
  20506. output))
  20507. ;;; Indentation
  20508. (defvar org-element-greater-elements)
  20509. (defun org--get-expected-indentation (element contentsp)
  20510. "Expected indentation column for current line, according to ELEMENT.
  20511. ELEMENT is an element containing point. CONTENTSP is non-nil
  20512. when indentation is to be computed according to contents of
  20513. ELEMENT."
  20514. (let ((type (org-element-type element))
  20515. (start (org-element-property :begin element))
  20516. (post-affiliated (org-element-property :post-affiliated element)))
  20517. (org-with-wide-buffer
  20518. (cond
  20519. (contentsp
  20520. (cl-case type
  20521. ((diary-sexp footnote-definition) 0)
  20522. ((headline inlinetask nil)
  20523. (if (not org-adapt-indentation) 0
  20524. (let ((level (org-current-level)))
  20525. (if level (1+ level) 0))))
  20526. ((item plain-list) (org-list-item-body-column post-affiliated))
  20527. (t
  20528. (goto-char start)
  20529. (org-get-indentation))))
  20530. ((memq type '(headline inlinetask nil))
  20531. (if (org-match-line "[ \t]*$")
  20532. (org--get-expected-indentation element t)
  20533. 0))
  20534. ((memq type '(diary-sexp footnote-definition)) 0)
  20535. ;; First paragraph of a footnote definition or an item.
  20536. ;; Indent like parent.
  20537. ((< (line-beginning-position) start)
  20538. (org--get-expected-indentation
  20539. (org-element-property :parent element) t))
  20540. ;; At first line: indent according to previous sibling, if any,
  20541. ;; ignoring footnote definitions and inline tasks, or parent's
  20542. ;; contents.
  20543. ((= (line-beginning-position) start)
  20544. (catch 'exit
  20545. (while t
  20546. (if (= (point-min) start) (throw 'exit 0)
  20547. (goto-char (1- start))
  20548. (let* ((previous (org-element-at-point))
  20549. (parent previous))
  20550. (while (and parent (<= (org-element-property :end parent) start))
  20551. (setq previous parent
  20552. parent (org-element-property :parent parent)))
  20553. (cond
  20554. ((not previous) (throw 'exit 0))
  20555. ((> (org-element-property :end previous) start)
  20556. (throw 'exit (org--get-expected-indentation previous t)))
  20557. ((memq (org-element-type previous)
  20558. '(footnote-definition inlinetask))
  20559. (setq start (org-element-property :begin previous)))
  20560. (t (goto-char (org-element-property :begin previous))
  20561. (throw 'exit
  20562. (if (bolp) (org-get-indentation)
  20563. ;; At first paragraph in an item or
  20564. ;; a footnote definition.
  20565. (org--get-expected-indentation
  20566. (org-element-property :parent previous) t))))))))))
  20567. ;; Otherwise, move to the first non-blank line above.
  20568. (t
  20569. (beginning-of-line)
  20570. (let ((pos (point)))
  20571. (skip-chars-backward " \r\t\n")
  20572. (cond
  20573. ;; Two blank lines end a footnote definition or a plain
  20574. ;; list. When we indent an empty line after them, the
  20575. ;; containing list or footnote definition is over, so it
  20576. ;; qualifies as a previous sibling. Therefore, we indent
  20577. ;; like its first line.
  20578. ((and (memq type '(footnote-definition plain-list))
  20579. (> (count-lines (point) pos) 2))
  20580. (goto-char start)
  20581. (org-get-indentation))
  20582. ;; Line above is the first one of a paragraph at the
  20583. ;; beginning of an item or a footnote definition. Indent
  20584. ;; like parent.
  20585. ((< (line-beginning-position) start)
  20586. (org--get-expected-indentation
  20587. (org-element-property :parent element) t))
  20588. ;; Line above is the beginning of an element, i.e., point
  20589. ;; was originally on the blank lines between element's start
  20590. ;; and contents.
  20591. ((= (line-beginning-position) post-affiliated)
  20592. (org--get-expected-indentation element t))
  20593. ;; POS is after contents in a greater element. Indent like
  20594. ;; the beginning of the element.
  20595. ((and (memq type org-element-greater-elements)
  20596. (let ((cend (org-element-property :contents-end element)))
  20597. (and cend (<= cend pos))))
  20598. ;; As a special case, if point is at the end of a footnote
  20599. ;; definition or an item, indent like the very last element
  20600. ;; within. If that last element is an item, indent like
  20601. ;; its contents.
  20602. (if (memq type '(footnote-definition item plain-list))
  20603. (let ((last (org-element-at-point)))
  20604. (goto-char pos)
  20605. (org--get-expected-indentation
  20606. last (eq (org-element-type last) 'item)))
  20607. (goto-char start)
  20608. (org-get-indentation)))
  20609. ;; In any other case, indent like the current line.
  20610. (t (org-get-indentation)))))))))
  20611. (defun org--align-node-property ()
  20612. "Align node property at point.
  20613. Alignment is done according to `org-property-format', which see."
  20614. (when (save-excursion
  20615. (beginning-of-line)
  20616. (looking-at org-property-re))
  20617. (replace-match
  20618. (concat (match-string 4)
  20619. (org-trim
  20620. (format org-property-format (match-string 1) (match-string 3))))
  20621. t t)))
  20622. (defun org-indent-line ()
  20623. "Indent line depending on context.
  20624. Indentation is done according to the following rules:
  20625. - Footnote definitions, diary sexps, headlines and inline tasks
  20626. have to start at column 0.
  20627. - On the very first line of an element, consider, in order, the
  20628. next rules until one matches:
  20629. 1. If there's a sibling element before, ignoring footnote
  20630. definitions and inline tasks, indent like its first line.
  20631. 2. If element has a parent, indent like its contents. More
  20632. precisely, if parent is an item, indent after the
  20633. description part, if any, or the bullet (see
  20634. `org-list-description-max-indent'). Else, indent like
  20635. parent's first line.
  20636. 3. Otherwise, indent relatively to current level, if
  20637. `org-adapt-indentation' is non-nil, or to left margin.
  20638. - On a blank line at the end of an element, indent according to
  20639. the type of the element. More precisely
  20640. 1. If element is a plain list, an item, or a footnote
  20641. definition, indent like the very last element within.
  20642. 2. If element is a paragraph, indent like its last non blank
  20643. line.
  20644. 3. Otherwise, indent like its very first line.
  20645. - In the code part of a source block, use language major mode
  20646. to indent current line if `org-src-tab-acts-natively' is
  20647. non-nil. If it is nil, do nothing.
  20648. - Otherwise, indent like the first non-blank line above.
  20649. The function doesn't indent an item as it could break the whole
  20650. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20651. `\\[org-shiftmetaright]'.
  20652. Also align node properties according to `org-property-format'."
  20653. (interactive)
  20654. (cond
  20655. (orgstruct-is-++
  20656. (let ((indent-line-function
  20657. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20658. (indent-according-to-mode)))
  20659. ((org-at-heading-p) 'noindent)
  20660. (t
  20661. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20662. (type (org-element-type element)))
  20663. (cond ((and (memq type '(plain-list item))
  20664. (= (line-beginning-position)
  20665. (org-element-property :post-affiliated element)))
  20666. 'noindent)
  20667. ((and (eq type 'latex-environment)
  20668. (>= (point) (org-element-property :post-affiliated element))
  20669. (< (point) (org-with-wide-buffer
  20670. (goto-char (org-element-property :end element))
  20671. (skip-chars-backward " \r\t\n")
  20672. (line-beginning-position 2))))
  20673. 'noindent)
  20674. ((and (eq type 'src-block)
  20675. org-src-tab-acts-natively
  20676. (> (line-beginning-position)
  20677. (org-element-property :post-affiliated element))
  20678. (< (line-beginning-position)
  20679. (org-with-wide-buffer
  20680. (goto-char (org-element-property :end element))
  20681. (skip-chars-backward " \r\t\n")
  20682. (line-beginning-position))))
  20683. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20684. (t
  20685. (let ((column (org--get-expected-indentation element nil)))
  20686. ;; Preserve current column.
  20687. (if (<= (current-column) (current-indentation))
  20688. (indent-line-to column)
  20689. (save-excursion (indent-line-to column))))
  20690. ;; Align node property. Also preserve current column.
  20691. (when (eq type 'node-property)
  20692. (let ((column (current-column)))
  20693. (org--align-node-property)
  20694. (org-move-to-column column)))))))))
  20695. (defun org-indent-region (start end)
  20696. "Indent each non-blank line in the region.
  20697. Called from a program, START and END specify the region to
  20698. indent. The function will not indent contents of example blocks,
  20699. verse blocks and export blocks as leading white spaces are
  20700. assumed to be significant there."
  20701. (interactive "r")
  20702. (save-excursion
  20703. (goto-char start)
  20704. (skip-chars-forward " \r\t\n")
  20705. (unless (eobp) (beginning-of-line))
  20706. (let ((indent-to
  20707. (lambda (ind pos)
  20708. ;; Set IND as indentation for all lines between point and
  20709. ;; POS. Blank lines are ignored. Leave point after POS
  20710. ;; once done.
  20711. (let ((limit (copy-marker pos)))
  20712. (while (< (point) limit)
  20713. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20714. (forward-line))
  20715. (set-marker limit nil))))
  20716. (end (copy-marker end)))
  20717. (while (< (point) end)
  20718. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20719. (let* ((element (org-element-at-point))
  20720. (type (org-element-type element))
  20721. (element-end (copy-marker (org-element-property :end element)))
  20722. (ind (org--get-expected-indentation element nil)))
  20723. (cond
  20724. ;; Element indented as a single block. Example blocks
  20725. ;; preserving indentation are a special case since the
  20726. ;; "contents" must not be indented whereas the block
  20727. ;; boundaries can.
  20728. ((or (memq type '(export-block latex-environment))
  20729. (and (eq type 'example-block)
  20730. (not
  20731. (or org-src-preserve-indentation
  20732. (org-element-property :preserve-indent element)))))
  20733. (let ((offset (- ind (org-get-indentation))))
  20734. (unless (zerop offset)
  20735. (indent-rigidly (org-element-property :begin element)
  20736. (org-element-property :end element)
  20737. offset)))
  20738. (goto-char element-end))
  20739. ;; Elements indented line wise. Be sure to exclude
  20740. ;; example blocks (preserving indentation) and source
  20741. ;; blocks from this category as they are treated
  20742. ;; specially later.
  20743. ((or (memq type '(paragraph table table-row))
  20744. (not (or (org-element-property :contents-begin element)
  20745. (memq type '(example-block src-block)))))
  20746. (when (eq type 'node-property)
  20747. (org--align-node-property)
  20748. (beginning-of-line))
  20749. (funcall indent-to ind (min element-end end)))
  20750. ;; Elements consisting of three parts: before the
  20751. ;; contents, the contents, and after the contents. The
  20752. ;; contents are treated specially, according to the
  20753. ;; element type, or not indented at all. Other parts are
  20754. ;; indented as a single block.
  20755. (t
  20756. (let* ((post (copy-marker
  20757. (org-element-property :post-affiliated element)))
  20758. (cbeg
  20759. (copy-marker
  20760. (cond
  20761. ((not (org-element-property :contents-begin element))
  20762. ;; Fake contents for source blocks.
  20763. (org-with-wide-buffer
  20764. (goto-char post)
  20765. (line-beginning-position 2)))
  20766. ((memq type '(footnote-definition item plain-list))
  20767. ;; Contents in these elements could start on
  20768. ;; the same line as the beginning of the
  20769. ;; element. Make sure we start indenting
  20770. ;; from the second line.
  20771. (org-with-wide-buffer
  20772. (goto-char post)
  20773. (end-of-line)
  20774. (skip-chars-forward " \r\t\n")
  20775. (if (eobp) (point) (line-beginning-position))))
  20776. (t (org-element-property :contents-begin element)))))
  20777. (cend (copy-marker
  20778. (or (org-element-property :contents-end element)
  20779. ;; Fake contents for source blocks.
  20780. (org-with-wide-buffer
  20781. (goto-char element-end)
  20782. (skip-chars-backward " \r\t\n")
  20783. (line-beginning-position)))
  20784. t)))
  20785. ;; Do not change items indentation individually as it
  20786. ;; might break the list as a whole. On the other
  20787. ;; hand, when at a plain list, indent it as a whole.
  20788. (cond ((eq type 'plain-list)
  20789. (let ((offset (- ind (org-get-indentation))))
  20790. (unless (zerop offset)
  20791. (indent-rigidly (org-element-property :begin element)
  20792. (org-element-property :end element)
  20793. offset))
  20794. (goto-char cbeg)))
  20795. ((eq type 'item) (goto-char cbeg))
  20796. (t (funcall indent-to ind (min cbeg end))))
  20797. (when (< (point) end)
  20798. (cl-case type
  20799. ((example-block verse-block))
  20800. (src-block
  20801. ;; In a source block, indent source code
  20802. ;; according to language major mode, but only if
  20803. ;; `org-src-tab-acts-natively' is non-nil.
  20804. (when (and (< (point) end) org-src-tab-acts-natively)
  20805. (ignore-errors
  20806. (org-babel-do-in-edit-buffer
  20807. (indent-region (point-min) (point-max))))))
  20808. (t (org-indent-region (point) (min cend end))))
  20809. (goto-char (min cend end))
  20810. (when (< (point) end)
  20811. (funcall indent-to ind (min element-end end))))
  20812. (set-marker post nil)
  20813. (set-marker cbeg nil)
  20814. (set-marker cend nil))))
  20815. (set-marker element-end nil))))
  20816. (set-marker end nil))))
  20817. (defun org-indent-drawer ()
  20818. "Indent the drawer at point."
  20819. (interactive)
  20820. (unless (save-excursion
  20821. (beginning-of-line)
  20822. (looking-at-p org-drawer-regexp))
  20823. (user-error "Not at a drawer"))
  20824. (let ((element (org-element-at-point)))
  20825. (unless (memq (org-element-type element) '(drawer property-drawer))
  20826. (user-error "Not at a drawer"))
  20827. (org-with-wide-buffer
  20828. (org-indent-region (org-element-property :begin element)
  20829. (org-element-property :end element))))
  20830. (message "Drawer at point indented"))
  20831. (defun org-indent-block ()
  20832. "Indent the block at point."
  20833. (interactive)
  20834. (unless (save-excursion
  20835. (beginning-of-line)
  20836. (let ((case-fold-search t))
  20837. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20838. (user-error "Not at a block"))
  20839. (let ((element (org-element-at-point)))
  20840. (unless (memq (org-element-type element)
  20841. '(comment-block center-block dynamic-block example-block
  20842. export-block quote-block special-block
  20843. src-block verse-block))
  20844. (user-error "Not at a block"))
  20845. (org-with-wide-buffer
  20846. (org-indent-region (org-element-property :begin element)
  20847. (org-element-property :end element))))
  20848. (message "Block at point indented"))
  20849. ;;; Filling
  20850. ;; We use our own fill-paragraph and auto-fill functions.
  20851. ;; `org-fill-paragraph' relies on adaptive filling and context
  20852. ;; checking. Appropriate `fill-prefix' is computed with
  20853. ;; `org-adaptive-fill-function'.
  20854. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20855. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20856. ;; `org-adaptive-fill-function' value. Internally,
  20857. ;; `org-comment-line-break-function' breaks the line.
  20858. ;; `org-setup-filling' installs filling and auto-filling related
  20859. ;; variables during `org-mode' initialization.
  20860. (defvar org-element-paragraph-separate) ; org-element.el
  20861. (defun org-setup-filling ()
  20862. (require 'org-element)
  20863. ;; Prevent auto-fill from inserting unwanted new items.
  20864. (when (boundp 'fill-nobreak-predicate)
  20865. (setq-local
  20866. fill-nobreak-predicate
  20867. (org-uniquify
  20868. (append fill-nobreak-predicate
  20869. '(org-fill-line-break-nobreak-p
  20870. org-fill-n-macro-as-item-nobreak-p
  20871. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20872. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20873. (setq-local paragraph-start paragraph-ending)
  20874. (setq-local paragraph-separate paragraph-ending))
  20875. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20876. (setq-local auto-fill-inhibit-regexp nil)
  20877. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20878. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20879. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20880. (defun org-fill-line-break-nobreak-p ()
  20881. "Non-nil when a new line at point would create an Org line break."
  20882. (save-excursion
  20883. (skip-chars-backward "[ \t]")
  20884. (skip-chars-backward "\\\\")
  20885. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20886. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20887. "Non-nil when a new line at point would split a timestamp."
  20888. (and (org-at-timestamp-p 'lax)
  20889. (not (looking-at org-ts-regexp-both))))
  20890. (defun org-fill-n-macro-as-item-nobreak-p ()
  20891. "Non-nil when a new line at point would create a new list."
  20892. ;; During export, a "n" macro followed by a dot or a closing
  20893. ;; parenthesis can end up being parsed as a new list item.
  20894. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20895. (declare-function message-in-body-p "message" ())
  20896. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20897. (defun org-adaptive-fill-function ()
  20898. "Compute a fill prefix for the current line.
  20899. Return fill prefix, as a string, or nil if current line isn't
  20900. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20901. matches in paragraphs or comments, use it."
  20902. (catch 'exit
  20903. (when (derived-mode-p 'message-mode)
  20904. (save-excursion
  20905. (beginning-of-line)
  20906. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20907. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20908. ((looking-at message-cite-prefix-regexp)
  20909. (throw 'exit (match-string-no-properties 0)))
  20910. ((looking-at org-outline-regexp)
  20911. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20912. (org-with-wide-buffer
  20913. (unless (org-at-heading-p)
  20914. (let* ((p (line-beginning-position))
  20915. (element (save-excursion
  20916. (beginning-of-line)
  20917. (org-element-at-point)))
  20918. (type (org-element-type element))
  20919. (post-affiliated (org-element-property :post-affiliated element)))
  20920. (unless (< p post-affiliated)
  20921. (cl-case type
  20922. (comment
  20923. (save-excursion
  20924. (beginning-of-line)
  20925. (looking-at "[ \t]*")
  20926. (concat (match-string 0) "# ")))
  20927. (footnote-definition "")
  20928. ((item plain-list)
  20929. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20930. (paragraph
  20931. ;; Fill prefix is usually the same as the current line,
  20932. ;; unless the paragraph is at the beginning of an item.
  20933. (let ((parent (org-element-property :parent element)))
  20934. (save-excursion
  20935. (beginning-of-line)
  20936. (cond ((eq (org-element-type parent) 'item)
  20937. (make-string (org-list-item-body-column
  20938. (org-element-property :begin parent))
  20939. ?\s))
  20940. ((and adaptive-fill-regexp
  20941. ;; Locally disable
  20942. ;; `adaptive-fill-function' to let
  20943. ;; `fill-context-prefix' handle
  20944. ;; `adaptive-fill-regexp' variable.
  20945. (let (adaptive-fill-function)
  20946. (fill-context-prefix
  20947. post-affiliated
  20948. (org-element-property :end element)))))
  20949. ((looking-at "[ \t]+") (match-string 0))
  20950. (t "")))))
  20951. (comment-block
  20952. ;; Only fill contents if P is within block boundaries.
  20953. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20954. (forward-line)
  20955. (point)))
  20956. (cend (save-excursion
  20957. (goto-char (org-element-property :end element))
  20958. (skip-chars-backward " \r\t\n")
  20959. (line-beginning-position))))
  20960. (when (and (>= p cbeg) (< p cend))
  20961. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20962. (match-string 0)
  20963. "")))))))))))
  20964. (declare-function message-goto-body "message" ())
  20965. (defvar message-cite-prefix-regexp) ; From message.el
  20966. (defun org-fill-element (&optional justify)
  20967. "Fill element at point, when applicable.
  20968. This function only applies to comment blocks, comments, example
  20969. blocks and paragraphs. Also, as a special case, re-align table
  20970. when point is at one.
  20971. If JUSTIFY is non-nil (interactively, with prefix argument),
  20972. justify as well. If `sentence-end-double-space' is non-nil, then
  20973. period followed by one space does not end a sentence, so don't
  20974. break a line there. The variable `fill-column' controls the
  20975. width for filling.
  20976. For convenience, when point is at a plain list, an item or
  20977. a footnote definition, try to fill the first paragraph within."
  20978. (with-syntax-table org-mode-transpose-word-syntax-table
  20979. ;; Move to end of line in order to get the first paragraph within
  20980. ;; a plain list or a footnote definition.
  20981. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20982. ;; First check if point is in a blank line at the beginning of
  20983. ;; the buffer. In that case, ignore filling.
  20984. (cl-case (org-element-type element)
  20985. ;; Use major mode filling function is src blocks.
  20986. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20987. ;; Align Org tables, leave table.el tables as-is.
  20988. (table-row (org-table-align) t)
  20989. (table
  20990. (when (eq (org-element-property :type element) 'org)
  20991. (save-excursion
  20992. (goto-char (org-element-property :post-affiliated element))
  20993. (org-table-align)))
  20994. t)
  20995. (paragraph
  20996. ;; Paragraphs may contain `line-break' type objects.
  20997. (let ((beg (max (point-min)
  20998. (org-element-property :contents-begin element)))
  20999. (end (min (point-max)
  21000. (org-element-property :contents-end element))))
  21001. ;; Do nothing if point is at an affiliated keyword.
  21002. (if (< (line-end-position) beg) t
  21003. (when (derived-mode-p 'message-mode)
  21004. ;; In `message-mode', do not fill following citation
  21005. ;; in current paragraph nor text before message body.
  21006. (let ((body-start (save-excursion (message-goto-body))))
  21007. (when body-start (setq beg (max body-start beg))))
  21008. (when (save-excursion
  21009. (re-search-forward
  21010. (concat "^" message-cite-prefix-regexp) end t))
  21011. (setq end (match-beginning 0))))
  21012. ;; Fill paragraph, taking line breaks into account.
  21013. (save-excursion
  21014. (goto-char beg)
  21015. (let ((cuts (list beg)))
  21016. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21017. (when (eq 'line-break
  21018. (org-element-type
  21019. (save-excursion (backward-char)
  21020. (org-element-context))))
  21021. (push (point) cuts)))
  21022. (dolist (c (delq end cuts))
  21023. (fill-region-as-paragraph c end justify)
  21024. (setq end c))))
  21025. t)))
  21026. ;; Contents of `comment-block' type elements should be
  21027. ;; filled as plain text, but only if point is within block
  21028. ;; markers.
  21029. (comment-block
  21030. (let* ((case-fold-search t)
  21031. (beg (save-excursion
  21032. (goto-char (org-element-property :begin element))
  21033. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21034. (forward-line)
  21035. (point)))
  21036. (end (save-excursion
  21037. (goto-char (org-element-property :end element))
  21038. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21039. (line-beginning-position))))
  21040. (if (or (< (point) beg) (> (point) end)) t
  21041. (fill-region-as-paragraph
  21042. (save-excursion (end-of-line)
  21043. (re-search-backward "^[ \t]*$" beg 'move)
  21044. (line-beginning-position))
  21045. (save-excursion (beginning-of-line)
  21046. (re-search-forward "^[ \t]*$" end 'move)
  21047. (line-beginning-position))
  21048. justify))))
  21049. ;; Fill comments.
  21050. (comment
  21051. (let ((begin (org-element-property :post-affiliated element))
  21052. (end (org-element-property :end element)))
  21053. (when (and (>= (point) begin) (<= (point) end))
  21054. (let ((begin (save-excursion
  21055. (end-of-line)
  21056. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21057. (progn (forward-line) (point))
  21058. begin)))
  21059. (end (save-excursion
  21060. (end-of-line)
  21061. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21062. (1- (line-beginning-position))
  21063. (skip-chars-backward " \r\t\n")
  21064. (line-end-position)))))
  21065. ;; Do not fill comments when at a blank line.
  21066. (when (> end begin)
  21067. (let ((fill-prefix
  21068. (save-excursion
  21069. (beginning-of-line)
  21070. (looking-at "[ \t]*#")
  21071. (let ((comment-prefix (match-string 0)))
  21072. (goto-char (match-end 0))
  21073. (if (looking-at adaptive-fill-regexp)
  21074. (concat comment-prefix (match-string 0))
  21075. (concat comment-prefix " "))))))
  21076. (save-excursion
  21077. (fill-region-as-paragraph begin end justify))))))
  21078. t))
  21079. ;; Ignore every other element.
  21080. (otherwise t)))))
  21081. (defun org-fill-paragraph (&optional justify region)
  21082. "Fill element at point, when applicable.
  21083. This function only applies to comment blocks, comments, example
  21084. blocks and paragraphs. Also, as a special case, re-align table
  21085. when point is at one.
  21086. For convenience, when point is at a plain list, an item or
  21087. a footnote definition, try to fill the first paragraph within.
  21088. If JUSTIFY is non-nil (interactively, with prefix argument),
  21089. justify as well. If `sentence-end-double-space' is non-nil, then
  21090. period followed by one space does not end a sentence, so don't
  21091. break a line there. The variable `fill-column' controls the
  21092. width for filling.
  21093. The REGION argument is non-nil if called interactively; in that
  21094. case, if Transient Mark mode is enabled and the mark is active,
  21095. fill each of the elements in the active region, instead of just
  21096. filling the current element."
  21097. (interactive (progn
  21098. (barf-if-buffer-read-only)
  21099. (list (if current-prefix-arg 'full) t)))
  21100. (cond
  21101. ((and (derived-mode-p 'message-mode)
  21102. (or (not (message-in-body-p))
  21103. (save-excursion (move-beginning-of-line 1)
  21104. (looking-at message-cite-prefix-regexp))))
  21105. ;; First ensure filling is correct in message-mode.
  21106. (let ((fill-paragraph-function
  21107. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21108. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21109. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21110. (paragraph-separate
  21111. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21112. (fill-paragraph nil)))
  21113. ((and region transient-mark-mode mark-active
  21114. (not (eq (region-beginning) (region-end))))
  21115. (let ((origin (point-marker))
  21116. (start (region-beginning)))
  21117. (unwind-protect
  21118. (progn
  21119. (goto-char (region-end))
  21120. (while (> (point) start)
  21121. (org-backward-paragraph)
  21122. (org-fill-element justify)))
  21123. (goto-char origin)
  21124. (set-marker origin nil))))
  21125. (t (org-fill-element justify))))
  21126. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  21127. (defun org-auto-fill-function ()
  21128. "Auto-fill function."
  21129. ;; Check if auto-filling is meaningful.
  21130. (let ((fc (current-fill-column)))
  21131. (when (and fc (> (current-column) fc))
  21132. (let* ((fill-prefix (org-adaptive-fill-function))
  21133. ;; Enforce empty fill prefix, if required. Otherwise, it
  21134. ;; will be computed again.
  21135. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21136. (when fill-prefix (do-auto-fill))))))
  21137. (defun org-comment-line-break-function (&optional soft)
  21138. "Break line at point and indent, continuing comment if within one.
  21139. The inserted newline is marked hard if variable
  21140. `use-hard-newlines' is true, unless optional argument SOFT is
  21141. non-nil."
  21142. (if soft (insert-and-inherit ?\n) (newline 1))
  21143. (save-excursion (forward-char -1) (delete-horizontal-space))
  21144. (delete-horizontal-space)
  21145. (indent-to-left-margin)
  21146. (insert-before-markers-and-inherit fill-prefix))
  21147. ;;; Fixed Width Areas
  21148. (defun org-toggle-fixed-width ()
  21149. "Toggle fixed-width markup.
  21150. Add or remove fixed-width markup on current line, whenever it
  21151. makes sense. Return an error otherwise.
  21152. If a region is active and if it contains only fixed-width areas
  21153. or blank lines, remove all fixed-width markup in it. If the
  21154. region contains anything else, convert all non-fixed-width lines
  21155. to fixed-width ones.
  21156. Blank lines at the end of the region are ignored unless the
  21157. region only contains such lines."
  21158. (interactive)
  21159. (if (not (org-region-active-p))
  21160. ;; No region:
  21161. ;;
  21162. ;; Remove fixed width marker only in a fixed-with element.
  21163. ;;
  21164. ;; Add fixed width maker in paragraphs, in blank lines after
  21165. ;; elements or at the beginning of a headline or an inlinetask,
  21166. ;; and before any one-line elements (e.g., a clock).
  21167. (progn
  21168. (beginning-of-line)
  21169. (let* ((element (org-element-at-point))
  21170. (type (org-element-type element)))
  21171. (cond
  21172. ((and (eq type 'fixed-width)
  21173. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21174. (replace-match
  21175. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21176. ((and (memq type '(babel-call clock comment diary-sexp headline
  21177. horizontal-rule keyword paragraph
  21178. planning))
  21179. (<= (org-element-property :post-affiliated element) (point)))
  21180. (skip-chars-forward " \t")
  21181. (insert ": "))
  21182. ((and (looking-at-p "[ \t]*$")
  21183. (or (eq type 'inlinetask)
  21184. (save-excursion
  21185. (skip-chars-forward " \r\t\n")
  21186. (<= (org-element-property :end element) (point)))))
  21187. (delete-region (point) (line-end-position))
  21188. (org-indent-line)
  21189. (insert ": "))
  21190. (t (user-error "Cannot insert a fixed-width line here")))))
  21191. ;; Region active.
  21192. (let* ((begin (save-excursion
  21193. (goto-char (region-beginning))
  21194. (line-beginning-position)))
  21195. (end (copy-marker
  21196. (save-excursion
  21197. (goto-char (region-end))
  21198. (unless (eolp) (beginning-of-line))
  21199. (if (save-excursion (re-search-backward "\\S-" begin t))
  21200. (progn (skip-chars-backward " \r\t\n") (point))
  21201. (point)))))
  21202. (all-fixed-width-p
  21203. (catch 'not-all-p
  21204. (save-excursion
  21205. (goto-char begin)
  21206. (skip-chars-forward " \r\t\n")
  21207. (when (eobp) (throw 'not-all-p nil))
  21208. (while (< (point) end)
  21209. (let ((element (org-element-at-point)))
  21210. (if (eq (org-element-type element) 'fixed-width)
  21211. (goto-char (org-element-property :end element))
  21212. (throw 'not-all-p nil))))
  21213. t))))
  21214. (if all-fixed-width-p
  21215. (save-excursion
  21216. (goto-char begin)
  21217. (while (< (point) end)
  21218. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21219. (replace-match
  21220. "" nil nil nil
  21221. (if (= (line-end-position) (match-end 0)) 0 1)))
  21222. (forward-line)))
  21223. (let ((min-ind (point-max)))
  21224. ;; Find minimum indentation across all lines.
  21225. (save-excursion
  21226. (goto-char begin)
  21227. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21228. (setq min-ind 0)
  21229. (catch 'zerop
  21230. (while (< (point) end)
  21231. (unless (looking-at-p "[ \t]*$")
  21232. (let ((ind (org-get-indentation)))
  21233. (setq min-ind (min min-ind ind))
  21234. (when (zerop ind) (throw 'zerop t))))
  21235. (forward-line)))))
  21236. ;; Loop over all lines and add fixed-width markup everywhere
  21237. ;; but in fixed-width lines.
  21238. (save-excursion
  21239. (goto-char begin)
  21240. (while (< (point) end)
  21241. (cond
  21242. ((org-at-heading-p)
  21243. (insert ": ")
  21244. (forward-line)
  21245. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21246. (insert ":")
  21247. (forward-line)))
  21248. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21249. (let* ((element (org-element-at-point))
  21250. (element-end (org-element-property :end element)))
  21251. (if (eq (org-element-type element) 'fixed-width)
  21252. (progn (goto-char element-end)
  21253. (skip-chars-backward " \r\t\n")
  21254. (forward-line))
  21255. (let ((limit (min end element-end)))
  21256. (while (< (point) limit)
  21257. (org-move-to-column min-ind t)
  21258. (insert ": ")
  21259. (forward-line))))))
  21260. (t
  21261. (org-move-to-column min-ind t)
  21262. (insert ": ")
  21263. (forward-line)))))))
  21264. (set-marker end nil))))
  21265. ;;; Comments
  21266. ;; Org comments syntax is quite complex. It requires the entire line
  21267. ;; to be just a comment. Also, even with the right syntax at the
  21268. ;; beginning of line, some elements (e.g., verse-block or
  21269. ;; example-block) don't accept comments. Usual Emacs comment commands
  21270. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21271. ;; Org still relies on `comment-dwim', but cannot trust
  21272. ;; `comment-only-p'. So, `comment-region-function' and
  21273. ;; `uncomment-region-function' both point
  21274. ;; to`org-comment-or-uncomment-region'. Eventually,
  21275. ;; `org-insert-comment' takes care of insertion of comments at the
  21276. ;; beginning of line.
  21277. ;; `org-setup-comments-handling' install comments related variables
  21278. ;; during `org-mode' initialization.
  21279. (defun org-setup-comments-handling ()
  21280. (interactive)
  21281. (setq-local comment-use-syntax nil)
  21282. (setq-local comment-start "# ")
  21283. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21284. (setq-local comment-insert-comment-function 'org-insert-comment)
  21285. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21286. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21287. (defun org-insert-comment ()
  21288. "Insert an empty comment above current line.
  21289. If the line is empty, insert comment at its beginning. When
  21290. point is within a source block, comment according to the related
  21291. major mode."
  21292. (if (let ((element (org-element-at-point)))
  21293. (and (eq (org-element-type element) 'src-block)
  21294. (< (save-excursion
  21295. (goto-char (org-element-property :post-affiliated element))
  21296. (line-end-position))
  21297. (point))
  21298. (> (save-excursion
  21299. (goto-char (org-element-property :end element))
  21300. (skip-chars-backward " \r\t\n")
  21301. (line-beginning-position))
  21302. (point))))
  21303. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21304. (beginning-of-line)
  21305. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21306. (open-line 1))
  21307. (org-indent-line)
  21308. (insert "# ")))
  21309. (defvar comment-empty-lines) ; From newcomment.el.
  21310. (defun org-comment-or-uncomment-region (beg end &rest _)
  21311. "Comment or uncomment each non-blank line in the region.
  21312. Uncomment each non-blank line between BEG and END if it only
  21313. contains commented lines. Otherwise, comment them. If region is
  21314. strictly within a source block, use appropriate comment syntax."
  21315. (if (let ((element (org-element-at-point)))
  21316. (and (eq (org-element-type element) 'src-block)
  21317. (< (save-excursion
  21318. (goto-char (org-element-property :post-affiliated element))
  21319. (line-end-position))
  21320. beg)
  21321. (>= (save-excursion
  21322. (goto-char (org-element-property :end element))
  21323. (skip-chars-backward " \r\t\n")
  21324. (line-beginning-position))
  21325. end)))
  21326. ;; Translate region boundaries for the Org buffer to the source
  21327. ;; buffer.
  21328. (let ((offset (- end beg)))
  21329. (save-excursion
  21330. (goto-char beg)
  21331. (org-babel-do-in-edit-buffer
  21332. (comment-or-uncomment-region (point) (+ offset (point))))))
  21333. (save-restriction
  21334. ;; Restrict region
  21335. (narrow-to-region (save-excursion (goto-char beg)
  21336. (skip-chars-forward " \r\t\n" end)
  21337. (line-beginning-position))
  21338. (save-excursion (goto-char end)
  21339. (skip-chars-backward " \r\t\n" beg)
  21340. (line-end-position)))
  21341. (let ((uncommentp
  21342. ;; UNCOMMENTP is non-nil when every non blank line between
  21343. ;; BEG and END is a comment.
  21344. (save-excursion
  21345. (goto-char (point-min))
  21346. (while (and (not (eobp))
  21347. (let ((element (org-element-at-point)))
  21348. (and (eq (org-element-type element) 'comment)
  21349. (goto-char (min (point-max)
  21350. (org-element-property
  21351. :end element)))))))
  21352. (eobp))))
  21353. (if uncommentp
  21354. ;; Only blank lines and comments in region: uncomment it.
  21355. (save-excursion
  21356. (goto-char (point-min))
  21357. (while (not (eobp))
  21358. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21359. (replace-match "" nil nil nil 1))
  21360. (forward-line)))
  21361. ;; Comment each line in region.
  21362. (let ((min-indent (point-max)))
  21363. ;; First find the minimum indentation across all lines.
  21364. (save-excursion
  21365. (goto-char (point-min))
  21366. (while (and (not (eobp)) (not (zerop min-indent)))
  21367. (unless (looking-at "[ \t]*$")
  21368. (setq min-indent (min min-indent (current-indentation))))
  21369. (forward-line)))
  21370. ;; Then loop over all lines.
  21371. (save-excursion
  21372. (goto-char (point-min))
  21373. (while (not (eobp))
  21374. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21375. ;; Don't get fooled by invisible text (e.g. link path)
  21376. ;; when moving to column MIN-INDENT.
  21377. (let ((buffer-invisibility-spec nil))
  21378. (org-move-to-column min-indent t))
  21379. (insert comment-start))
  21380. (forward-line)))))))))
  21381. (defun org-comment-dwim (_arg)
  21382. "Call `comment-dwim' within a source edit buffer if needed."
  21383. (interactive "*P")
  21384. (if (org-in-src-block-p)
  21385. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21386. (call-interactively 'comment-dwim)))
  21387. ;;; Timestamps API
  21388. ;; This section contains tools to operate on timestamp objects, as
  21389. ;; returned by, e.g. `org-element-context'.
  21390. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21391. "Encode TIMESTAMP object into Emacs internal time.
  21392. Use end of date range or time range when END is non-nil."
  21393. (apply #'encode-time
  21394. (cons 0
  21395. (mapcar
  21396. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21397. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21398. '(:minute-start :hour-start :day-start :month-start
  21399. :year-start))))))
  21400. (defun org-timestamp-has-time-p (timestamp)
  21401. "Non-nil when TIMESTAMP has a time specified."
  21402. (org-element-property :hour-start timestamp))
  21403. (defun org-timestamp-format (timestamp format &optional end utc)
  21404. "Format a TIMESTAMP object into a string.
  21405. FORMAT is a format specifier to be passed to
  21406. `format-time-string'.
  21407. When optional argument END is non-nil, use end of date-range or
  21408. time-range, if possible.
  21409. When optional argument UTC is non-nil, time will be expressed as
  21410. Universal Time."
  21411. (format-time-string
  21412. format (org-timestamp--to-internal-time timestamp end)
  21413. (and utc t)))
  21414. (defun org-timestamp-split-range (timestamp &optional end)
  21415. "Extract a TIMESTAMP object from a date or time range.
  21416. END, when non-nil, means extract the end of the range.
  21417. Otherwise, extract its start.
  21418. Return a new timestamp object."
  21419. (let ((type (org-element-property :type timestamp)))
  21420. (if (memq type '(active inactive diary)) timestamp
  21421. (let ((split-ts (org-element-copy timestamp)))
  21422. ;; Set new type.
  21423. (org-element-put-property
  21424. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21425. ;; Copy start properties over end properties if END is
  21426. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21427. (let ((p-alist '((:minute-start . :minute-end)
  21428. (:hour-start . :hour-end)
  21429. (:day-start . :day-end)
  21430. (:month-start . :month-end)
  21431. (:year-start . :year-end))))
  21432. (dolist (p-cell p-alist)
  21433. (org-element-put-property
  21434. split-ts
  21435. (funcall (if end #'car #'cdr) p-cell)
  21436. (org-element-property
  21437. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21438. ;; Eventually refresh `:raw-value'.
  21439. (org-element-put-property split-ts :raw-value nil)
  21440. (org-element-put-property
  21441. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21442. (defun org-timestamp-translate (timestamp &optional boundary)
  21443. "Translate TIMESTAMP object to custom format.
  21444. Format string is defined in `org-time-stamp-custom-formats',
  21445. which see.
  21446. When optional argument BOUNDARY is non-nil, it is either the
  21447. symbol `start' or `end'. In this case, only translate the
  21448. starting or ending part of TIMESTAMP if it is a date or time
  21449. range. Otherwise, translate both parts.
  21450. Return timestamp as-is if `org-display-custom-times' is nil or if
  21451. it has a `diary' type."
  21452. (let ((type (org-element-property :type timestamp)))
  21453. (if (or (not org-display-custom-times) (eq type 'diary))
  21454. (org-element-interpret-data timestamp)
  21455. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21456. org-time-stamp-custom-formats)))
  21457. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21458. (concat (org-timestamp-format timestamp fmt)
  21459. "--"
  21460. (org-timestamp-format timestamp fmt t))
  21461. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21462. ;;; Other stuff.
  21463. (defvar reftex-docstruct-symbol)
  21464. (defvar org--rds)
  21465. (defun org-reftex-citation ()
  21466. "Use reftex-citation to insert a citation into the buffer.
  21467. This looks for a line like
  21468. #+BIBLIOGRAPHY: foo plain option:-d
  21469. and derives from it that foo.bib is the bibliography file relevant
  21470. for this document. It then installs the necessary environment for RefTeX
  21471. to work in this buffer and calls `reftex-citation' to insert a citation
  21472. into the buffer.
  21473. Export of such citations to both LaTeX and HTML is handled by the contributed
  21474. package ox-bibtex by Taru Karttunen."
  21475. (interactive)
  21476. (let ((reftex-docstruct-symbol 'org--rds)
  21477. org--rds bib)
  21478. (org-with-wide-buffer
  21479. (let ((case-fold-search t)
  21480. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21481. (if (not (save-excursion
  21482. (or (re-search-forward re nil t)
  21483. (re-search-backward re nil t))))
  21484. (user-error "No bibliography defined in file")
  21485. (setq bib (concat (match-string 1) ".bib")
  21486. org--rds (list (list 'bib bib))))))
  21487. (call-interactively 'reftex-citation)))
  21488. ;;;; Functions extending outline functionality
  21489. (defun org-beginning-of-line (&optional n)
  21490. "Go to the beginning of the current visible line.
  21491. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21492. tags on the first attempt, and only move to after the tags when
  21493. the cursor is already beyond the end of the headline.
  21494. With argument N not nil or 1, move forward N - 1 lines first."
  21495. (interactive "^p")
  21496. (let ((origin (point))
  21497. (special (pcase org-special-ctrl-a/e
  21498. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21499. deactivate-mark)
  21500. ;; First move to a visible line.
  21501. (if (bound-and-true-p visual-line-mode)
  21502. (beginning-of-visual-line n)
  21503. (move-beginning-of-line n)
  21504. ;; `move-beginning-of-line' may leave point after invisible
  21505. ;; characters if line starts with such of these (e.g., with
  21506. ;; a link at column 0). Really move to the beginning of the
  21507. ;; current visible line.
  21508. (beginning-of-line))
  21509. (cond
  21510. ;; No special behavior. Point is already at the beginning of
  21511. ;; a line, logical or visual.
  21512. ((not special))
  21513. ;; `beginning-of-visual-line' left point before logical beginning
  21514. ;; of line: point is at the beginning of a visual line. Bail
  21515. ;; out.
  21516. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21517. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21518. ;; At a headline, special position is before the title, but
  21519. ;; after any TODO keyword or priority cookie.
  21520. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21521. (line-end-position)))
  21522. (bol (point)))
  21523. (if (eq special 'reversed)
  21524. (when (and (= origin bol) (eq last-command this-command))
  21525. (goto-char refpos))
  21526. (when (or (> origin refpos) (= origin bol))
  21527. (goto-char refpos)))))
  21528. ((and (looking-at org-list-full-item-re)
  21529. (memq (org-element-type (save-match-data (org-element-at-point)))
  21530. '(item plain-list)))
  21531. ;; Set special position at first white space character after
  21532. ;; bullet, and check-box, if any.
  21533. (let ((after-bullet
  21534. (let ((box (match-end 3)))
  21535. (cond ((not box) (match-end 1))
  21536. ((eq (char-after box) ?\s) (1+ box))
  21537. (t box)))))
  21538. (if (eq special 'reversed)
  21539. (when (and (= (point) origin) (eq last-command this-command))
  21540. (goto-char after-bullet))
  21541. (when (or (> origin after-bullet) (= (point) origin))
  21542. (goto-char after-bullet)))))
  21543. ;; No special context. Point is already at beginning of line.
  21544. (t nil))))
  21545. (defun org-end-of-line (&optional n)
  21546. "Go to the end of the line, but before ellipsis, if any.
  21547. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21548. tags on the first attempt, and only move to after the tags when
  21549. the cursor is already beyond the end of the headline.
  21550. With argument N not nil or 1, move forward N - 1 lines first."
  21551. (interactive "^p")
  21552. (let ((origin (point))
  21553. (special (pcase org-special-ctrl-a/e
  21554. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21555. deactivate-mark)
  21556. ;; First move to a visible line.
  21557. (if (bound-and-true-p visual-line-mode)
  21558. (beginning-of-visual-line n)
  21559. (move-beginning-of-line n))
  21560. (cond
  21561. ;; At a headline, with tags.
  21562. ((and special
  21563. (save-excursion
  21564. (beginning-of-line)
  21565. (let ((case-fold-search nil))
  21566. (looking-at org-complex-heading-regexp)))
  21567. (match-end 5))
  21568. (let ((tags (save-excursion
  21569. (goto-char (match-beginning 5))
  21570. (skip-chars-backward " \t")
  21571. (point)))
  21572. (visual-end (and (bound-and-true-p visual-line-mode)
  21573. (save-excursion
  21574. (end-of-visual-line)
  21575. (point)))))
  21576. ;; If `end-of-visual-line' brings us before end of line or
  21577. ;; even tags, i.e., the headline spans over multiple visual
  21578. ;; lines, move there.
  21579. (cond ((and visual-end
  21580. (< visual-end tags)
  21581. (<= origin visual-end))
  21582. (goto-char visual-end))
  21583. ((eq special 'reversed)
  21584. (if (and (= origin (line-end-position))
  21585. (eq this-command last-command))
  21586. (goto-char tags)
  21587. (end-of-line)))
  21588. (t
  21589. (if (or (< origin tags) (= origin (line-end-position)))
  21590. (goto-char tags)
  21591. (end-of-line))))))
  21592. ((bound-and-true-p visual-line-mode)
  21593. (let ((bol (line-beginning-position)))
  21594. (end-of-visual-line)
  21595. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21596. ;; end of a line, backtrack and use `end-of-line' instead.
  21597. (when (/= bol (line-beginning-position))
  21598. (goto-char bol)
  21599. (end-of-line))))
  21600. (t (end-of-line)))))
  21601. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21602. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21603. (defun org-backward-sentence (&optional _arg)
  21604. "Go to beginning of sentence, or beginning of table field.
  21605. This will call `backward-sentence' or `org-table-beginning-of-field',
  21606. depending on context."
  21607. (interactive)
  21608. (let* ((element (org-element-at-point))
  21609. (contents-begin (org-element-property :contents-begin element))
  21610. (table (org-element-lineage element '(table) t)))
  21611. (if (and table
  21612. (> (point) contents-begin)
  21613. (<= (point) (org-element-property :contents-end table)))
  21614. (call-interactively #'org-table-beginning-of-field)
  21615. (save-restriction
  21616. (when (and contents-begin
  21617. (< (point-min) contents-begin)
  21618. (> (point) contents-begin))
  21619. (narrow-to-region contents-begin
  21620. (org-element-property :contents-end element)))
  21621. (call-interactively #'backward-sentence)))))
  21622. (defun org-forward-sentence (&optional _arg)
  21623. "Go to end of sentence, or end of table field.
  21624. This will call `forward-sentence' or `org-table-end-of-field',
  21625. depending on context."
  21626. (interactive)
  21627. (let* ((element (org-element-at-point))
  21628. (contents-end (org-element-property :contents-end element))
  21629. (table (org-element-lineage element '(table) t)))
  21630. (if (and table
  21631. (>= (point) (org-element-property :contents-begin table))
  21632. (< (point) contents-end))
  21633. (call-interactively #'org-table-end-of-field)
  21634. (save-restriction
  21635. (when (and contents-end
  21636. (> (point-max) contents-end)
  21637. ;; Skip blank lines between elements.
  21638. (< (org-element-property :end element)
  21639. (save-excursion (goto-char contents-end)
  21640. (skip-chars-forward " \r\t\n"))))
  21641. (narrow-to-region (org-element-property :contents-begin element)
  21642. contents-end))
  21643. (call-interactively #'forward-sentence)))))
  21644. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21645. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21646. (defun org-kill-line (&optional _arg)
  21647. "Kill line, to tags or end of line."
  21648. (interactive)
  21649. (cond
  21650. ((or (not org-special-ctrl-k)
  21651. (bolp)
  21652. (not (org-at-heading-p)))
  21653. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21654. org-ctrl-k-protect-subtree
  21655. (or (eq org-ctrl-k-protect-subtree 'error)
  21656. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21657. (user-error "C-k aborted as it would kill a hidden subtree"))
  21658. (call-interactively
  21659. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21660. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21661. (kill-region (point) (match-beginning 1))
  21662. (org-set-tags nil t))
  21663. (t (kill-region (point) (point-at-eol)))))
  21664. (define-key org-mode-map "\C-k" 'org-kill-line)
  21665. (defun org-yank (&optional arg)
  21666. "Yank. If the kill is a subtree, treat it specially.
  21667. This command will look at the current kill and check if is a single
  21668. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21669. cursor is at the beginning of a line or after the stars of a currently
  21670. empty headline, then the yank is handled specially. How exactly depends
  21671. on the value of the following variables.
  21672. `org-yank-folded-subtrees'
  21673. By default, this variable is non-nil, which results in
  21674. subtree(s) being folded after insertion, except if doing so
  21675. would swallow text after the yanked text.
  21676. `org-yank-adjusted-subtrees'
  21677. When non-nil (the default value is nil), the subtree will be
  21678. promoted or demoted in order to fit into the local outline tree
  21679. structure, which means that the level will be adjusted so that it
  21680. becomes the smaller one of the two *visible* surrounding headings.
  21681. Any prefix to this command will cause `yank' to be called directly with
  21682. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21683. will just
  21684. plainly yank the text as it is.
  21685. \[1] The test checks if the first non-white line is a heading
  21686. and if there are no other headings with fewer stars."
  21687. (interactive "P")
  21688. (org-yank-generic 'yank arg))
  21689. (defun org-yank-generic (command arg)
  21690. "Perform some yank-like command.
  21691. This function implements the behavior described in the `org-yank'
  21692. documentation. However, it has been generalized to work for any
  21693. interactive command with similar behavior."
  21694. ;; pretend to be command COMMAND
  21695. (setq this-command command)
  21696. (if arg
  21697. (call-interactively command)
  21698. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21699. (and (org-kill-is-subtree-p)
  21700. (or (bolp)
  21701. (and (looking-at "[ \t]*$")
  21702. (string-match
  21703. "\\`\\*+\\'"
  21704. (buffer-substring (point-at-bol) (point)))))))
  21705. swallowp)
  21706. (cond
  21707. ((and subtreep org-yank-folded-subtrees)
  21708. (let ((beg (point))
  21709. end)
  21710. (if (and subtreep org-yank-adjusted-subtrees)
  21711. (org-paste-subtree nil nil 'for-yank)
  21712. (call-interactively command))
  21713. (setq end (point))
  21714. (goto-char beg)
  21715. (when (and (bolp) subtreep
  21716. (not (setq swallowp
  21717. (org-yank-folding-would-swallow-text beg end))))
  21718. (org-with-limited-levels
  21719. (or (looking-at org-outline-regexp)
  21720. (re-search-forward org-outline-regexp-bol end t))
  21721. (while (and (< (point) end) (looking-at org-outline-regexp))
  21722. (outline-hide-subtree)
  21723. (org-cycle-show-empty-lines 'folded)
  21724. (condition-case nil
  21725. (outline-forward-same-level 1)
  21726. (error (goto-char end))))))
  21727. (when swallowp
  21728. (message
  21729. "Inserted text not folded because that would swallow text"))
  21730. (goto-char end)
  21731. (skip-chars-forward " \t\n\r")
  21732. (beginning-of-line 1)
  21733. (push-mark beg 'nomsg)))
  21734. ((and subtreep org-yank-adjusted-subtrees)
  21735. (let ((beg (point-at-bol)))
  21736. (org-paste-subtree nil nil 'for-yank)
  21737. (push-mark beg 'nomsg)))
  21738. (t
  21739. (call-interactively command))))))
  21740. (defun org-yank-folding-would-swallow-text (beg end)
  21741. "Would hide-subtree at BEG swallow any text after END?"
  21742. (let (level)
  21743. (org-with-limited-levels
  21744. (save-excursion
  21745. (goto-char beg)
  21746. (when (or (looking-at org-outline-regexp)
  21747. (re-search-forward org-outline-regexp-bol end t))
  21748. (setq level (org-outline-level)))
  21749. (goto-char end)
  21750. (skip-chars-forward " \t\r\n\v\f")
  21751. (not (or (eobp)
  21752. (and (bolp) (looking-at-p org-outline-regexp)
  21753. (<= (org-outline-level) level))))))))
  21754. (define-key org-mode-map "\C-y" 'org-yank)
  21755. (defun org-truely-invisible-p ()
  21756. "Check if point is at a character currently not visible.
  21757. This version does not only check the character property, but also
  21758. `visible-mode'."
  21759. ;; Early versions of noutline don't have `outline-invisible-p'.
  21760. (unless (bound-and-true-p visible-mode)
  21761. (outline-invisible-p)))
  21762. (defun org-invisible-p2 ()
  21763. "Check if point is at a character currently not visible."
  21764. (save-excursion
  21765. (when (and (eolp) (not (bobp))) (backward-char 1))
  21766. ;; Early versions of noutline don't have `outline-invisible-p'.
  21767. (outline-invisible-p)))
  21768. (defun org-back-to-heading (&optional invisible-ok)
  21769. "Call `outline-back-to-heading', but provide a better error message."
  21770. (condition-case nil
  21771. (outline-back-to-heading invisible-ok)
  21772. (error (error "Before first headline at position %d in buffer %s"
  21773. (point) (current-buffer)))))
  21774. (defun org-before-first-heading-p ()
  21775. "Before first heading?"
  21776. (save-excursion
  21777. (end-of-line)
  21778. (null (re-search-backward org-outline-regexp-bol nil t))))
  21779. (defun org-at-heading-p (&optional ignored)
  21780. (outline-on-heading-p t))
  21781. (defun org-in-commented-heading-p (&optional no-inheritance)
  21782. "Non-nil if point is under a commented heading.
  21783. This function also checks ancestors of the current headline,
  21784. unless optional argument NO-INHERITANCE is non-nil."
  21785. (cond
  21786. ((org-before-first-heading-p) nil)
  21787. ((let ((headline (nth 4 (org-heading-components))))
  21788. (and headline
  21789. (let ((case-fold-search nil))
  21790. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21791. headline)))))
  21792. (no-inheritance nil)
  21793. (t
  21794. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21795. (defun org-at-comment-p nil
  21796. "Is cursor in a commented line?"
  21797. (save-excursion
  21798. (save-match-data
  21799. (beginning-of-line)
  21800. (looking-at "^[ \t]*# "))))
  21801. (defun org-at-drawer-p nil
  21802. "Is cursor at a drawer keyword?"
  21803. (save-excursion
  21804. (move-beginning-of-line 1)
  21805. (looking-at org-drawer-regexp)))
  21806. (defun org-at-block-p nil
  21807. "Is cursor at a block keyword?"
  21808. (save-excursion
  21809. (move-beginning-of-line 1)
  21810. (looking-at org-block-regexp)))
  21811. (defun org-point-at-end-of-empty-headline ()
  21812. "If point is at the end of an empty headline, return t, else nil.
  21813. If the heading only contains a TODO keyword, it is still still considered
  21814. empty."
  21815. (let ((case-fold-search nil))
  21816. (and (looking-at "[ \t]*$")
  21817. org-todo-line-regexp
  21818. (save-excursion
  21819. (beginning-of-line)
  21820. (looking-at org-todo-line-regexp)
  21821. (string= (match-string 3) "")))))
  21822. (defun org-at-heading-or-item-p ()
  21823. (or (org-at-heading-p) (org-at-item-p)))
  21824. (defun org-at-target-p ()
  21825. (or (org-in-regexp org-radio-target-regexp)
  21826. (org-in-regexp org-target-regexp)))
  21827. ;; Compatibility alias with Org versions < 7.8.03
  21828. (defalias 'org-on-target-p 'org-at-target-p)
  21829. (defun org-up-heading-all (arg)
  21830. "Move to the heading line of which the present line is a subheading.
  21831. This function considers both visible and invisible heading lines.
  21832. With argument, move up ARG levels."
  21833. (outline-up-heading arg t))
  21834. (defun org-up-heading-safe ()
  21835. "Move to the heading line of which the present line is a subheading.
  21836. This version will not throw an error. It will return the level of the
  21837. headline found, or nil if no higher level is found.
  21838. Also, this function will be a lot faster than `outline-up-heading',
  21839. because it relies on stars being the outline starters. This can really
  21840. make a significant difference in outlines with very many siblings."
  21841. (when (ignore-errors (org-back-to-heading t))
  21842. (let ((level-up (1- (funcall outline-level))))
  21843. (and (> level-up 0)
  21844. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21845. (funcall outline-level)))))
  21846. (defun org-first-sibling-p ()
  21847. "Is this heading the first child of its parents?"
  21848. (interactive)
  21849. (let ((re org-outline-regexp-bol)
  21850. level l)
  21851. (unless (org-at-heading-p t)
  21852. (user-error "Not at a heading"))
  21853. (setq level (funcall outline-level))
  21854. (save-excursion
  21855. (if (not (re-search-backward re nil t))
  21856. t
  21857. (setq l (funcall outline-level))
  21858. (< l level)))))
  21859. (defun org-goto-sibling (&optional previous)
  21860. "Goto the next sibling, even if it is invisible.
  21861. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21862. when a sibling was found. When none is found, return nil and don't
  21863. move point."
  21864. (let ((fun (if previous 're-search-backward 're-search-forward))
  21865. (pos (point))
  21866. (re org-outline-regexp-bol)
  21867. level l)
  21868. (when (ignore-errors (org-back-to-heading t))
  21869. (setq level (funcall outline-level))
  21870. (catch 'exit
  21871. (or previous (forward-char 1))
  21872. (while (funcall fun re nil t)
  21873. (setq l (funcall outline-level))
  21874. (when (< l level) (goto-char pos) (throw 'exit nil))
  21875. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21876. (goto-char pos)
  21877. nil))))
  21878. (defun org-show-siblings ()
  21879. "Show all siblings of the current headline."
  21880. (save-excursion
  21881. (while (org-goto-sibling) (org-flag-heading nil)))
  21882. (save-excursion
  21883. (while (org-goto-sibling 'previous)
  21884. (org-flag-heading nil))))
  21885. (defun org-goto-first-child ()
  21886. "Goto the first child, even if it is invisible.
  21887. Return t when a child was found. Otherwise don't move point and
  21888. return nil."
  21889. (let (level (pos (point)) (re org-outline-regexp-bol))
  21890. (when (ignore-errors (org-back-to-heading t))
  21891. (setq level (outline-level))
  21892. (forward-char 1)
  21893. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21894. (progn (goto-char (match-beginning 0)) t)
  21895. (goto-char pos) nil))))
  21896. (defun org-show-hidden-entry ()
  21897. "Show an entry where even the heading is hidden."
  21898. (save-excursion
  21899. (org-show-entry)))
  21900. (defun org-flag-heading (flag &optional entry)
  21901. "Flag the current heading. FLAG non-nil means make invisible.
  21902. When ENTRY is non-nil, show the entire entry."
  21903. (save-excursion
  21904. (org-back-to-heading t)
  21905. ;; Check if we should show the entire entry
  21906. (if entry
  21907. (progn
  21908. (org-show-entry)
  21909. (save-excursion
  21910. (and (outline-next-heading)
  21911. (org-flag-heading nil))))
  21912. (outline-flag-region (max (point-min) (1- (point)))
  21913. (save-excursion (outline-end-of-heading) (point))
  21914. flag))))
  21915. (defun org-get-next-sibling ()
  21916. "Move to next heading of the same level, and return point.
  21917. If there is no such heading, return nil.
  21918. This is like outline-next-sibling, but invisible headings are ok."
  21919. (let ((level (funcall outline-level)))
  21920. (outline-next-heading)
  21921. (while (and (not (eobp)) (> (funcall outline-level) level))
  21922. (outline-next-heading))
  21923. (unless (or (eobp) (< (funcall outline-level) level))
  21924. (point))))
  21925. (defun org-get-last-sibling ()
  21926. "Move to previous heading of the same level, and return point.
  21927. If there is no such heading, return nil."
  21928. (let ((opoint (point))
  21929. (level (funcall outline-level)))
  21930. (outline-previous-heading)
  21931. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21932. (while (and (> (funcall outline-level) level)
  21933. (not (bobp)))
  21934. (outline-previous-heading))
  21935. (unless (< (funcall outline-level) level)
  21936. (point)))))
  21937. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21938. "Goto to the end of a subtree."
  21939. ;; This contains an exact copy of the original function, but it uses
  21940. ;; `org-back-to-heading', to make it work also in invisible
  21941. ;; trees. And is uses an invisible-ok argument.
  21942. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21943. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21944. ;; with many children and grandchildren etc, this can be much faster
  21945. ;; than the outline version.
  21946. (org-back-to-heading invisible-ok)
  21947. (let ((first t)
  21948. (level (funcall outline-level)))
  21949. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21950. ;; A true heading (not a plain list item), in Org
  21951. ;; This means we can easily find the end by looking
  21952. ;; only for the right number of stars. Using a regexp to do
  21953. ;; this is so much faster than using a Lisp loop.
  21954. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21955. (forward-char 1)
  21956. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21957. ;; something else, do it the slow way
  21958. (while (and (not (eobp))
  21959. (or first (> (funcall outline-level) level)))
  21960. (setq first nil)
  21961. (outline-next-heading)))
  21962. (unless to-heading
  21963. (when (memq (preceding-char) '(?\n ?\^M))
  21964. ;; Go to end of line before heading
  21965. (forward-char -1)
  21966. (when (memq (preceding-char) '(?\n ?\^M))
  21967. ;; leave blank line before heading
  21968. (forward-char -1)))))
  21969. (point))
  21970. (defun org-end-of-meta-data (&optional full)
  21971. "Skip planning line and properties drawer in current entry.
  21972. When optional argument FULL is non-nil, also skip empty lines,
  21973. clocking lines and regular drawers at the beginning of the
  21974. entry."
  21975. (org-back-to-heading t)
  21976. (forward-line)
  21977. (when (looking-at-p org-planning-line-re) (forward-line))
  21978. (when (looking-at org-property-drawer-re)
  21979. (goto-char (match-end 0))
  21980. (forward-line))
  21981. (when (and full (not (org-at-heading-p)))
  21982. (catch 'exit
  21983. (let ((end (save-excursion (outline-next-heading) (point)))
  21984. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21985. (while (not (eobp))
  21986. (cond ((looking-at-p org-drawer-regexp)
  21987. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21988. (forward-line)
  21989. (throw 'exit t)))
  21990. ((looking-at-p re) (forward-line))
  21991. (t (throw 'exit t))))))))
  21992. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21993. "Move forward to the ARG'th subheading at same level as this one.
  21994. Stop at the first and last subheadings of a superior heading.
  21995. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21996. non-nil it will also look at invisible ones."
  21997. (interactive "p")
  21998. (let ((backward? (and arg (< arg 0))))
  21999. (if (org-before-first-heading-p)
  22000. (if backward? (goto-char (point-min)) (outline-next-heading))
  22001. (org-back-to-heading invisible-ok)
  22002. (unless backward? (end-of-line)) ;do not match current headline
  22003. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22004. (f (if backward? #'re-search-backward #'re-search-forward))
  22005. (count (if arg (abs arg) 1))
  22006. (result (point)))
  22007. (while (and (> count 0)
  22008. (funcall f org-outline-regexp-bol nil 'move))
  22009. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22010. (cond ((< l level) (setq count 0))
  22011. ((and (= l level)
  22012. (or invisible-ok
  22013. (not (outline-invisible-p
  22014. (line-beginning-position)))))
  22015. (cl-decf count)
  22016. (when (= l level) (setq result (point)))))))
  22017. (goto-char result))
  22018. (beginning-of-line))))
  22019. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22020. "Move backward to the ARG'th subheading at same level as this one.
  22021. Stop at the first and last subheadings of a superior heading."
  22022. (interactive "p")
  22023. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22024. (defun org-next-visible-heading (arg)
  22025. "Move to the next visible heading.
  22026. This function wraps `outline-next-visible-heading' with
  22027. `org-with-limited-levels' in order to skip over inline tasks and
  22028. respect customization of `org-odd-levels-only'."
  22029. (interactive "p")
  22030. (org-with-limited-levels
  22031. (outline-next-visible-heading arg)))
  22032. (defun org-previous-visible-heading (arg)
  22033. "Move to the previous visible heading.
  22034. This function wraps `outline-previous-visible-heading' with
  22035. `org-with-limited-levels' in order to skip over inline tasks and
  22036. respect customization of `org-odd-levels-only'."
  22037. (interactive "p")
  22038. (org-with-limited-levels
  22039. (outline-previous-visible-heading arg)))
  22040. (defun org-next-block (arg &optional backward block-regexp)
  22041. "Jump to the next block.
  22042. With a prefix argument ARG, jump forward ARG many blocks.
  22043. When BACKWARD is non-nil, jump to the previous block.
  22044. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22045. Match data is set according to this regexp when the function
  22046. returns.
  22047. Return point at beginning of the opening line of found block.
  22048. Throw an error if no block is found."
  22049. (interactive "p")
  22050. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22051. (case-fold-search t)
  22052. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22053. (count (or arg 1))
  22054. (origin (point))
  22055. last-element)
  22056. (if backward (beginning-of-line) (end-of-line))
  22057. (while (and (> count 0) (funcall search-fn re nil t))
  22058. (let ((element (save-excursion
  22059. (goto-char (match-beginning 0))
  22060. (save-match-data (org-element-at-point)))))
  22061. (when (and (memq (org-element-type element)
  22062. '(center-block comment-block dynamic-block
  22063. example-block export-block quote-block
  22064. special-block src-block verse-block))
  22065. (<= (match-beginning 0)
  22066. (org-element-property :post-affiliated element)))
  22067. (setq last-element element)
  22068. (cl-decf count))))
  22069. (if (= count 0)
  22070. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22071. (save-match-data (org-show-context)))
  22072. (goto-char origin)
  22073. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22074. (defun org-previous-block (arg &optional block-regexp)
  22075. "Jump to the previous block.
  22076. With a prefix argument ARG, jump backward ARG many source blocks.
  22077. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22078. (interactive "p")
  22079. (org-next-block arg t block-regexp))
  22080. (defun org-forward-paragraph ()
  22081. "Move forward to beginning of next paragraph or equivalent.
  22082. The function moves point to the beginning of the next visible
  22083. structural element, which can be a paragraph, a table, a list
  22084. item, etc. It also provides some special moves for convenience:
  22085. - On an affiliated keyword, jump to the beginning of the
  22086. relative element.
  22087. - On an item or a footnote definition, move to the second
  22088. element inside, if any.
  22089. - On a table or a property drawer, jump after it.
  22090. - On a verse or source block, stop after blank lines."
  22091. (interactive)
  22092. (when (eobp) (user-error "Cannot move further down"))
  22093. (let* ((deactivate-mark nil)
  22094. (element (org-element-at-point))
  22095. (type (org-element-type element))
  22096. (post-affiliated (org-element-property :post-affiliated element))
  22097. (contents-begin (org-element-property :contents-begin element))
  22098. (contents-end (org-element-property :contents-end element))
  22099. (end (let ((end (org-element-property :end element)) (parent element))
  22100. (while (and (setq parent (org-element-property :parent parent))
  22101. (= (org-element-property :contents-end parent) end))
  22102. (setq end (org-element-property :end parent)))
  22103. end)))
  22104. (cond ((not element)
  22105. (skip-chars-forward " \r\t\n")
  22106. (or (eobp) (beginning-of-line)))
  22107. ;; On affiliated keywords, move to element's beginning.
  22108. ((< (point) post-affiliated)
  22109. (goto-char post-affiliated))
  22110. ;; At a table row, move to the end of the table. Similarly,
  22111. ;; at a node property, move to the end of the property
  22112. ;; drawer.
  22113. ((memq type '(node-property table-row))
  22114. (goto-char (org-element-property
  22115. :end (org-element-property :parent element))))
  22116. ((memq type '(property-drawer table)) (goto-char end))
  22117. ;; Consider blank lines as separators in verse and source
  22118. ;; blocks to ease editing.
  22119. ((memq type '(src-block verse-block))
  22120. (when (eq type 'src-block)
  22121. (setq contents-end
  22122. (save-excursion (goto-char end)
  22123. (skip-chars-backward " \r\t\n")
  22124. (line-beginning-position))))
  22125. (beginning-of-line)
  22126. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22127. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22128. (goto-char end)
  22129. (skip-chars-forward " \r\t\n")
  22130. (if (= (point) contents-end) (goto-char end)
  22131. (beginning-of-line))))
  22132. ;; With no contents, just skip element.
  22133. ((not contents-begin) (goto-char end))
  22134. ;; If contents are invisible, skip the element altogether.
  22135. ((outline-invisible-p (line-end-position))
  22136. (cl-case type
  22137. (headline
  22138. (org-with-limited-levels (outline-next-visible-heading 1)))
  22139. ;; At a plain list, make sure we move to the next item
  22140. ;; instead of skipping the whole list.
  22141. (plain-list (forward-char)
  22142. (org-forward-paragraph))
  22143. (otherwise (goto-char end))))
  22144. ((>= (point) contents-end) (goto-char end))
  22145. ((>= (point) contents-begin)
  22146. ;; This can only happen on paragraphs and plain lists.
  22147. (cl-case type
  22148. (paragraph (goto-char end))
  22149. ;; At a plain list, try to move to second element in
  22150. ;; first item, if possible.
  22151. (plain-list (end-of-line)
  22152. (org-forward-paragraph))))
  22153. ;; When contents start on the middle of a line (e.g. in
  22154. ;; items and footnote definitions), try to reach first
  22155. ;; element starting after current line.
  22156. ((> (line-end-position) contents-begin)
  22157. (end-of-line)
  22158. (org-forward-paragraph))
  22159. (t (goto-char contents-begin)))))
  22160. (defun org-backward-paragraph ()
  22161. "Move backward to start of previous paragraph or equivalent.
  22162. The function moves point to the beginning of the current
  22163. structural element, which can be a paragraph, a table, a list
  22164. item, etc., or to the beginning of the previous visible one if
  22165. point is already there. It also provides some special moves for
  22166. convenience:
  22167. - On an affiliated keyword, jump to the first one.
  22168. - On a table or a property drawer, move to its beginning.
  22169. - On a verse or source block, stop before blank lines."
  22170. (interactive)
  22171. (when (bobp) (user-error "Cannot move further up"))
  22172. (let* ((deactivate-mark nil)
  22173. (element (org-element-at-point))
  22174. (type (org-element-type element))
  22175. (contents-begin (org-element-property :contents-begin element))
  22176. (contents-end (org-element-property :contents-end element))
  22177. (post-affiliated (org-element-property :post-affiliated element))
  22178. (begin (org-element-property :begin element)))
  22179. (cond
  22180. ((not element) (goto-char (point-min)))
  22181. ((= (point) begin)
  22182. (backward-char)
  22183. (org-backward-paragraph))
  22184. ((<= (point) post-affiliated) (goto-char begin))
  22185. ((memq type '(node-property table-row))
  22186. (goto-char (org-element-property
  22187. :post-affiliated (org-element-property :parent element))))
  22188. ((memq type '(property-drawer table)) (goto-char begin))
  22189. ((memq type '(src-block verse-block))
  22190. (when (eq type 'src-block)
  22191. (setq contents-begin
  22192. (save-excursion (goto-char begin) (forward-line) (point))))
  22193. (if (= (point) contents-begin) (goto-char post-affiliated)
  22194. ;; Inside a verse block, see blank lines as paragraph
  22195. ;; separators.
  22196. (let ((origin (point)))
  22197. (skip-chars-backward " \r\t\n" contents-begin)
  22198. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22199. (skip-chars-forward " \r\t\n" origin)
  22200. (if (= (point) origin) (goto-char contents-begin)
  22201. (beginning-of-line))))))
  22202. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22203. ((eq type 'paragraph)
  22204. (goto-char contents-begin)
  22205. ;; When at first paragraph in an item or a footnote definition,
  22206. ;; move directly to beginning of line.
  22207. (let ((parent-contents
  22208. (org-element-property
  22209. :contents-begin (org-element-property :parent element))))
  22210. (when (and parent-contents (= parent-contents contents-begin))
  22211. (beginning-of-line))))
  22212. ;; At the end of a greater element, move to the beginning of the
  22213. ;; last element within.
  22214. ((>= (point) contents-end)
  22215. (goto-char (1- contents-end))
  22216. (org-backward-paragraph))
  22217. (t (goto-char (or post-affiliated begin))))
  22218. ;; Ensure we never leave point invisible.
  22219. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22220. (defun org-forward-element ()
  22221. "Move forward by one element.
  22222. Move to the next element at the same level, when possible."
  22223. (interactive)
  22224. (cond ((eobp) (user-error "Cannot move further down"))
  22225. ((org-with-limited-levels (org-at-heading-p))
  22226. (let ((origin (point)))
  22227. (goto-char (org-end-of-subtree nil t))
  22228. (unless (org-with-limited-levels (org-at-heading-p))
  22229. (goto-char origin)
  22230. (user-error "Cannot move further down"))))
  22231. (t
  22232. (let* ((elem (org-element-at-point))
  22233. (end (org-element-property :end elem))
  22234. (parent (org-element-property :parent elem)))
  22235. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22236. (goto-char (org-element-property :end parent)))
  22237. ((integer-or-marker-p end) (goto-char end))
  22238. (t (message "No element at point")))))))
  22239. (defun org-backward-element ()
  22240. "Move backward by one element.
  22241. Move to the previous element at the same level, when possible."
  22242. (interactive)
  22243. (cond ((bobp) (user-error "Cannot move further up"))
  22244. ((org-with-limited-levels (org-at-heading-p))
  22245. ;; At a headline, move to the previous one, if any, or stay
  22246. ;; here.
  22247. (let ((origin (point)))
  22248. (org-with-limited-levels (org-backward-heading-same-level 1))
  22249. ;; When current headline has no sibling above, move to its
  22250. ;; parent.
  22251. (when (= (point) origin)
  22252. (or (org-with-limited-levels (org-up-heading-safe))
  22253. (progn (goto-char origin)
  22254. (user-error "Cannot move further up"))))))
  22255. (t
  22256. (let* ((elem (org-element-at-point))
  22257. (beg (org-element-property :begin elem)))
  22258. (cond
  22259. ;; Move to beginning of current element if point isn't
  22260. ;; there already.
  22261. ((null beg) (message "No element at point"))
  22262. ((/= (point) beg) (goto-char beg))
  22263. (t (goto-char beg)
  22264. (skip-chars-backward " \r\t\n")
  22265. (unless (bobp)
  22266. (let ((prev (org-element-at-point)))
  22267. (goto-char (org-element-property :begin prev))
  22268. (while (and (setq prev (org-element-property :parent prev))
  22269. (<= (org-element-property :end prev) beg))
  22270. (goto-char (org-element-property :begin prev)))))))))))
  22271. (defun org-up-element ()
  22272. "Move to upper element."
  22273. (interactive)
  22274. (if (org-with-limited-levels (org-at-heading-p))
  22275. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22276. (let* ((elem (org-element-at-point))
  22277. (parent (org-element-property :parent elem)))
  22278. (if parent (goto-char (org-element-property :begin parent))
  22279. (if (org-with-limited-levels (org-before-first-heading-p))
  22280. (user-error "No surrounding element")
  22281. (org-with-limited-levels (org-back-to-heading)))))))
  22282. (defun org-down-element ()
  22283. "Move to inner element."
  22284. (interactive)
  22285. (let ((element (org-element-at-point)))
  22286. (cond
  22287. ((memq (org-element-type element) '(plain-list table))
  22288. (goto-char (org-element-property :contents-begin element))
  22289. (forward-char))
  22290. ((memq (org-element-type element) org-element-greater-elements)
  22291. ;; If contents are hidden, first disclose them.
  22292. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22293. (goto-char (or (org-element-property :contents-begin element)
  22294. (user-error "No content for this element"))))
  22295. (t (user-error "No inner element")))))
  22296. (defun org-drag-element-backward ()
  22297. "Move backward element at point."
  22298. (interactive)
  22299. (let ((elem (or (org-element-at-point)
  22300. (user-error "No element at point"))))
  22301. (if (eq (org-element-type elem) 'headline)
  22302. ;; Preserve point when moving a whole tree, even if point was
  22303. ;; on blank lines below the headline.
  22304. (let ((offset (skip-chars-backward " \t\n")))
  22305. (unwind-protect (org-move-subtree-up)
  22306. (forward-char (- offset))))
  22307. (let ((prev-elem
  22308. (save-excursion
  22309. (goto-char (org-element-property :begin elem))
  22310. (skip-chars-backward " \r\t\n")
  22311. (unless (bobp)
  22312. (let* ((beg (org-element-property :begin elem))
  22313. (prev (org-element-at-point))
  22314. (up prev))
  22315. (while (and (setq up (org-element-property :parent up))
  22316. (<= (org-element-property :end up) beg))
  22317. (setq prev up))
  22318. prev)))))
  22319. ;; Error out if no previous element or previous element is
  22320. ;; a parent of the current one.
  22321. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22322. (user-error "Cannot drag element backward")
  22323. (let ((pos (point)))
  22324. (org-element-swap-A-B prev-elem elem)
  22325. (goto-char (+ (org-element-property :begin prev-elem)
  22326. (- pos (org-element-property :begin elem))))))))))
  22327. (defun org-drag-element-forward ()
  22328. "Move forward element at point."
  22329. (interactive)
  22330. (let* ((pos (point))
  22331. (elem (or (org-element-at-point)
  22332. (user-error "No element at point"))))
  22333. (when (= (point-max) (org-element-property :end elem))
  22334. (user-error "Cannot drag element forward"))
  22335. (goto-char (org-element-property :end elem))
  22336. (let ((next-elem (org-element-at-point)))
  22337. (when (or (org-element-nested-p elem next-elem)
  22338. (and (eq (org-element-type next-elem) 'headline)
  22339. (not (eq (org-element-type elem) 'headline))))
  22340. (goto-char pos)
  22341. (user-error "Cannot drag element forward"))
  22342. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22343. ;; body's length (without final blanks) and by the length of
  22344. ;; blanks between ELEM and NEXT-ELEM.
  22345. (let ((size-next (- (save-excursion
  22346. (goto-char (org-element-property :end next-elem))
  22347. (skip-chars-backward " \r\t\n")
  22348. (forward-line)
  22349. ;; Small correction if buffer doesn't end
  22350. ;; with a newline character.
  22351. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22352. (org-element-property :begin next-elem)))
  22353. (size-blank (- (org-element-property :end elem)
  22354. (save-excursion
  22355. (goto-char (org-element-property :end elem))
  22356. (skip-chars-backward " \r\t\n")
  22357. (forward-line)
  22358. (point)))))
  22359. (org-element-swap-A-B elem next-elem)
  22360. (goto-char (+ pos size-next size-blank))))))
  22361. (defun org-drag-line-forward (arg)
  22362. "Drag the line at point ARG lines forward."
  22363. (interactive "p")
  22364. (dotimes (_ (abs arg))
  22365. (let ((c (current-column)))
  22366. (if (< 0 arg)
  22367. (progn
  22368. (beginning-of-line 2)
  22369. (transpose-lines 1)
  22370. (beginning-of-line 0))
  22371. (transpose-lines 1)
  22372. (beginning-of-line -1))
  22373. (org-move-to-column c))))
  22374. (defun org-drag-line-backward (arg)
  22375. "Drag the line at point ARG lines backward."
  22376. (interactive "p")
  22377. (org-drag-line-forward (- arg)))
  22378. (defun org-mark-element ()
  22379. "Put point at beginning of this element, mark at end.
  22380. Interactively, if this command is repeated or (in Transient Mark
  22381. mode) if the mark is active, it marks the next element after the
  22382. ones already marked."
  22383. (interactive)
  22384. (let (deactivate-mark)
  22385. (if (and (called-interactively-p 'any)
  22386. (or (and (eq last-command this-command) (mark t))
  22387. (and transient-mark-mode mark-active)))
  22388. (set-mark
  22389. (save-excursion
  22390. (goto-char (mark))
  22391. (goto-char (org-element-property :end (org-element-at-point)))))
  22392. (let ((element (org-element-at-point)))
  22393. (end-of-line)
  22394. (push-mark (org-element-property :end element) t t)
  22395. (goto-char (org-element-property :begin element))))))
  22396. (defun org-narrow-to-element ()
  22397. "Narrow buffer to current element."
  22398. (interactive)
  22399. (let ((elem (org-element-at-point)))
  22400. (cond
  22401. ((eq (car elem) 'headline)
  22402. (narrow-to-region
  22403. (org-element-property :begin elem)
  22404. (org-element-property :end elem)))
  22405. ((memq (car elem) org-element-greater-elements)
  22406. (narrow-to-region
  22407. (org-element-property :contents-begin elem)
  22408. (org-element-property :contents-end elem)))
  22409. (t
  22410. (narrow-to-region
  22411. (org-element-property :begin elem)
  22412. (org-element-property :end elem))))))
  22413. (defun org-transpose-element ()
  22414. "Transpose current and previous elements, keeping blank lines between.
  22415. Point is moved after both elements."
  22416. (interactive)
  22417. (org-skip-whitespace)
  22418. (let ((end (org-element-property :end (org-element-at-point))))
  22419. (org-drag-element-backward)
  22420. (goto-char end)))
  22421. (defun org-unindent-buffer ()
  22422. "Un-indent the visible part of the buffer.
  22423. Relative indentation (between items, inside blocks, etc.) isn't
  22424. modified."
  22425. (interactive)
  22426. (unless (eq major-mode 'org-mode)
  22427. (user-error "Cannot un-indent a buffer not in Org mode"))
  22428. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22429. (unindent-tree
  22430. (lambda (contents)
  22431. (dolist (element (reverse contents))
  22432. (if (memq (org-element-type element) '(headline section))
  22433. (funcall unindent-tree (org-element-contents element))
  22434. (save-excursion
  22435. (save-restriction
  22436. (narrow-to-region
  22437. (org-element-property :begin element)
  22438. (org-element-property :end element))
  22439. (org-do-remove-indentation))))))))
  22440. (funcall unindent-tree (org-element-contents parse-tree))))
  22441. (defun org-show-children (&optional level)
  22442. "Show all direct subheadings of this heading.
  22443. Prefix arg LEVEL is how many levels below the current level
  22444. should be shown. Default is enough to cause the following
  22445. heading to appear."
  22446. (interactive "p")
  22447. ;; If `orgstruct-mode' is active, use the slower version.
  22448. (if orgstruct-mode (call-interactively #'outline-show-children)
  22449. (save-excursion
  22450. (org-back-to-heading t)
  22451. (let* ((current-level (funcall outline-level))
  22452. (max-level (org-get-valid-level
  22453. current-level
  22454. (if level (prefix-numeric-value level) 1)))
  22455. (end (save-excursion (org-end-of-subtree t t)))
  22456. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22457. (past-first-child nil)
  22458. ;; Make sure to skip inlinetasks.
  22459. (re (format regexp-fmt
  22460. current-level
  22461. (cond
  22462. ((not (featurep 'org-inlinetask)) "")
  22463. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22464. 3))
  22465. (t (1- org-inlinetask-min-level))))))
  22466. ;; Display parent heading.
  22467. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22468. (forward-line)
  22469. ;; Display children. First child may be deeper than expected
  22470. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22471. ;; MAX-LEVEL accordingly.
  22472. (while (re-search-forward re end t)
  22473. (unless past-first-child
  22474. (setq re (format regexp-fmt
  22475. current-level
  22476. (max (funcall outline-level) max-level)))
  22477. (setq past-first-child t))
  22478. (outline-flag-region
  22479. (line-end-position 0) (line-end-position) nil))))))
  22480. (defun org-show-subtree ()
  22481. "Show everything after this heading at deeper levels."
  22482. (interactive)
  22483. (outline-flag-region
  22484. (point)
  22485. (save-excursion
  22486. (org-end-of-subtree t t))
  22487. nil))
  22488. (defun org-show-entry ()
  22489. "Show the body directly following this heading.
  22490. Show the heading too, if it is currently invisible."
  22491. (interactive)
  22492. (save-excursion
  22493. (ignore-errors
  22494. (org-back-to-heading t)
  22495. (outline-flag-region
  22496. (max (point-min) (1- (point)))
  22497. (save-excursion
  22498. (if (re-search-forward
  22499. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22500. (match-beginning 1)
  22501. (point-max)))
  22502. nil)
  22503. (org-cycle-hide-drawers 'children))))
  22504. (defun org-make-options-regexp (kwds &optional extra)
  22505. "Make a regular expression for keyword lines.
  22506. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22507. when non-nil, is a regexp matching keywords names."
  22508. (concat "^[ \t]*#\\+\\("
  22509. (regexp-opt kwds)
  22510. (and extra (concat (and kwds "\\|") extra))
  22511. "\\):[ \t]*\\(.*\\)"))
  22512. ;;;; Integration with and fixes for other packages
  22513. ;;; Imenu support
  22514. (defvar-local org-imenu-markers nil
  22515. "All markers currently used by Imenu.")
  22516. (defun org-imenu-new-marker (&optional pos)
  22517. "Return a new marker for use by Imenu, and remember the marker."
  22518. (let ((m (make-marker)))
  22519. (move-marker m (or pos (point)))
  22520. (push m org-imenu-markers)
  22521. m))
  22522. (defun org-imenu-get-tree ()
  22523. "Produce the index for Imenu."
  22524. (dolist (x org-imenu-markers) (move-marker x nil))
  22525. (setq org-imenu-markers nil)
  22526. (let* ((case-fold-search nil)
  22527. (n org-imenu-depth)
  22528. (re (concat "^" (org-get-limited-outline-regexp)))
  22529. (subs (make-vector (1+ n) nil))
  22530. (last-level 0)
  22531. m level head0 head)
  22532. (org-with-wide-buffer
  22533. (goto-char (point-max))
  22534. (while (re-search-backward re nil t)
  22535. (setq level (org-reduced-level (funcall outline-level)))
  22536. (when (and (<= level n)
  22537. (looking-at org-complex-heading-regexp)
  22538. (setq head0 (match-string-no-properties 4)))
  22539. (setq head (org-link-display-format head0)
  22540. m (org-imenu-new-marker))
  22541. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22542. (if (>= level last-level)
  22543. (push (cons head m) (aref subs level))
  22544. (push (cons head (aref subs (1+ level))) (aref subs level))
  22545. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22546. (setq last-level level))))
  22547. (aref subs 1)))
  22548. (eval-after-load "imenu"
  22549. '(progn
  22550. (add-hook 'imenu-after-jump-hook
  22551. (lambda ()
  22552. (when (derived-mode-p 'org-mode)
  22553. (org-show-context 'org-goto))))))
  22554. (defun org-link-display-format (s)
  22555. "Replace links in string S with their description.
  22556. If there is no description, use the link target."
  22557. (save-match-data
  22558. (replace-regexp-in-string
  22559. org-bracket-link-analytic-regexp
  22560. (lambda (m)
  22561. (if (match-end 5) (match-string 5 m)
  22562. (concat (match-string 1 m) (match-string 3 m))))
  22563. s nil t)))
  22564. (defun org-toggle-link-display ()
  22565. "Toggle the literal or descriptive display of links."
  22566. (interactive)
  22567. (if org-descriptive-links
  22568. (progn (org-remove-from-invisibility-spec '(org-link))
  22569. (org-restart-font-lock)
  22570. (setq org-descriptive-links nil))
  22571. (progn (add-to-invisibility-spec '(org-link))
  22572. (org-restart-font-lock)
  22573. (setq org-descriptive-links t))))
  22574. ;; Speedbar support
  22575. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22576. "Overlay marking the agenda restriction line in speedbar.")
  22577. (overlay-put org-speedbar-restriction-lock-overlay
  22578. 'face 'org-agenda-restriction-lock)
  22579. (overlay-put org-speedbar-restriction-lock-overlay
  22580. 'help-echo "Agendas are currently limited to this item.")
  22581. (delete-overlay org-speedbar-restriction-lock-overlay)
  22582. (defun org-speedbar-set-agenda-restriction ()
  22583. "Restrict future agenda commands to the location at point in speedbar.
  22584. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22585. (interactive)
  22586. (require 'org-agenda)
  22587. (let (p m tp np dir txt)
  22588. (cond
  22589. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22590. 'org-imenu t))
  22591. (setq m (get-text-property p 'org-imenu-marker))
  22592. (with-current-buffer (marker-buffer m)
  22593. (goto-char m)
  22594. (org-agenda-set-restriction-lock 'subtree)))
  22595. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22596. 'speedbar-function 'speedbar-find-file))
  22597. (setq tp (previous-single-property-change
  22598. (1+ p) 'speedbar-function)
  22599. np (next-single-property-change
  22600. tp 'speedbar-function)
  22601. dir (speedbar-line-directory)
  22602. txt (buffer-substring-no-properties (or tp (point-min))
  22603. (or np (point-max))))
  22604. (with-current-buffer (find-file-noselect
  22605. (let ((default-directory dir))
  22606. (expand-file-name txt)))
  22607. (unless (derived-mode-p 'org-mode)
  22608. (user-error "Cannot restrict to non-Org mode file"))
  22609. (org-agenda-set-restriction-lock 'file)))
  22610. (t (user-error "Don't know how to restrict Org mode agenda")))
  22611. (move-overlay org-speedbar-restriction-lock-overlay
  22612. (point-at-bol) (point-at-eol))
  22613. (setq current-prefix-arg nil)
  22614. (org-agenda-maybe-redo)))
  22615. (defvar speedbar-file-key-map)
  22616. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22617. (eval-after-load "speedbar"
  22618. '(progn
  22619. (speedbar-add-supported-extension ".org")
  22620. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22621. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22622. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22623. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22624. (add-hook 'speedbar-visiting-tag-hook
  22625. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22626. ;;; Fixes and Hacks for problems with other packages
  22627. (defun org--flyspell-object-check-p (element)
  22628. "Non-nil when Flyspell can check object at point.
  22629. ELEMENT is the element at point."
  22630. (let ((object (save-excursion
  22631. (when (looking-at-p "\\>") (backward-char))
  22632. (org-element-context element))))
  22633. (cl-case (org-element-type object)
  22634. ;; Prevent checks in links due to keybinding conflict with
  22635. ;; Flyspell.
  22636. ((code entity export-snippet inline-babel-call
  22637. inline-src-block line-break latex-fragment link macro
  22638. statistics-cookie target timestamp verbatim)
  22639. nil)
  22640. (footnote-reference
  22641. ;; Only in inline footnotes, within the definition.
  22642. (and (eq (org-element-property :type object) 'inline)
  22643. (< (save-excursion
  22644. (goto-char (org-element-property :begin object))
  22645. (search-forward ":" nil t 2))
  22646. (point))))
  22647. (otherwise t))))
  22648. (defun org-mode-flyspell-verify ()
  22649. "Function used for `flyspell-generic-check-word-predicate'."
  22650. (if (org-at-heading-p)
  22651. ;; At a headline or an inlinetask, check title only. This is
  22652. ;; faster than relying on `org-element-at-point'.
  22653. (and (save-excursion (beginning-of-line)
  22654. (and (let ((case-fold-search t))
  22655. (not (looking-at-p "\\*+ END[ \t]*$")))
  22656. (let ((case-fold-search nil))
  22657. (looking-at org-complex-heading-regexp))))
  22658. (match-beginning 4)
  22659. (>= (point) (match-beginning 4))
  22660. (or (not (match-beginning 5))
  22661. (< (point) (match-beginning 5))))
  22662. (let* ((element (org-element-at-point))
  22663. (post-affiliated (org-element-property :post-affiliated element)))
  22664. (cond
  22665. ;; Ignore checks in all affiliated keywords but captions.
  22666. ((< (point) post-affiliated)
  22667. (and (save-excursion
  22668. (beginning-of-line)
  22669. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22670. (> (point) (match-end 0))
  22671. (org--flyspell-object-check-p element)))
  22672. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22673. ((let ((log (org-log-into-drawer)))
  22674. (and log
  22675. (let ((drawer (org-element-lineage element '(drawer))))
  22676. (and drawer
  22677. (eq (compare-strings
  22678. log nil nil
  22679. (org-element-property :drawer-name drawer) nil nil t)
  22680. t)))))
  22681. nil)
  22682. (t
  22683. (cl-case (org-element-type element)
  22684. ((comment quote-section) t)
  22685. (comment-block
  22686. ;; Allow checks between block markers, not on them.
  22687. (and (> (line-beginning-position) post-affiliated)
  22688. (save-excursion
  22689. (end-of-line)
  22690. (skip-chars-forward " \r\t\n")
  22691. (< (point) (org-element-property :end element)))))
  22692. ;; Arbitrary list of keywords where checks are meaningful.
  22693. ;; Make sure point is on the value part of the element.
  22694. (keyword
  22695. (and (member (org-element-property :key element)
  22696. '("DESCRIPTION" "TITLE"))
  22697. (save-excursion
  22698. (search-backward ":" (line-beginning-position) t))))
  22699. ;; Check is globally allowed in paragraphs verse blocks and
  22700. ;; table rows (after affiliated keywords) but some objects
  22701. ;; must not be affected.
  22702. ((paragraph table-row verse-block)
  22703. (let ((cbeg (org-element-property :contents-begin element))
  22704. (cend (org-element-property :contents-end element)))
  22705. (and cbeg (>= (point) cbeg) (< (point) cend)
  22706. (org--flyspell-object-check-p element))))))))))
  22707. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22708. (defun org-remove-flyspell-overlays-in (beg end)
  22709. "Remove flyspell overlays in region."
  22710. (and (bound-and-true-p flyspell-mode)
  22711. (fboundp 'flyspell-delete-region-overlays)
  22712. (flyspell-delete-region-overlays beg end)))
  22713. (defvar flyspell-delayed-commands)
  22714. (eval-after-load "flyspell"
  22715. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22716. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22717. (eval-after-load "bookmark"
  22718. '(if (boundp 'bookmark-after-jump-hook)
  22719. ;; We can use the hook
  22720. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22721. ;; Hook not available, use advice
  22722. (defadvice bookmark-jump (after org-make-visible activate)
  22723. "Make the position visible."
  22724. (org-bookmark-jump-unhide))))
  22725. ;; Make sure saveplace shows the location if it was hidden
  22726. (eval-after-load "saveplace"
  22727. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22728. "Make the position visible."
  22729. (org-bookmark-jump-unhide)))
  22730. ;; Make sure ecb shows the location if it was hidden
  22731. (eval-after-load "ecb"
  22732. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22733. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22734. (when (derived-mode-p 'org-mode)
  22735. (org-show-context))))
  22736. (defun org-bookmark-jump-unhide ()
  22737. "Unhide the current position, to show the bookmark location."
  22738. (and (derived-mode-p 'org-mode)
  22739. (or (outline-invisible-p)
  22740. (save-excursion (goto-char (max (point-min) (1- (point))))
  22741. (outline-invisible-p)))
  22742. (org-show-context 'bookmark-jump)))
  22743. (defun org-mark-jump-unhide ()
  22744. "Make the point visible with `org-show-context' after jumping to the mark."
  22745. (when (and (derived-mode-p 'org-mode)
  22746. (outline-invisible-p))
  22747. (org-show-context 'mark-goto)))
  22748. (eval-after-load "simple"
  22749. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22750. "Make the point visible with `org-show-context'."
  22751. (org-mark-jump-unhide)))
  22752. (eval-after-load "simple"
  22753. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22754. "Make the point visible with `org-show-context'."
  22755. (org-mark-jump-unhide)))
  22756. (eval-after-load "simple"
  22757. '(defadvice pop-global-mark (after org-make-visible activate)
  22758. "Make the point visible with `org-show-context'."
  22759. (org-mark-jump-unhide)))
  22760. ;; Make session.el ignore our circular variable
  22761. (defvar session-globals-exclude)
  22762. (eval-after-load "session"
  22763. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22764. ;;;; Finish up
  22765. (provide 'org)
  22766. (run-hooks 'org-load-hook)
  22767. ;;; org.el ends here