org.el 951 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178
  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-2016 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"
  105. (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  108. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  109. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  110. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  111. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  112. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  113. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  114. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  115. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  116. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  117. (declare-function org-clock-update-time-maybe "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  128. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  129. (declare-function org-element-property "org-element" (property element))
  130. (declare-function org-element-put-property "org-element" (element property value))
  131. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  132. (declare-function org-element-type "org-element" (element))
  133. (declare-function org-element-update-syntax "org-element" ())
  134. (declare-function org-id-find-id-file "org-id" (id))
  135. (declare-function org-id-get-create "org-id" (&optional force))
  136. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  137. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  138. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  139. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  140. (declare-function org-table-align "org-table" ())
  141. (declare-function org-table-begin "org-table" (&optional table-type))
  142. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  143. (declare-function org-table-blank-field "org-table" ())
  144. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  145. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  146. (declare-function org-table-cut-region "org-table" (beg end))
  147. (declare-function org-table-edit-field "org-table" (arg))
  148. (declare-function org-table-end "org-table" (&optional table-type))
  149. (declare-function org-table-end-of-field "org-table" (&optional n))
  150. (declare-function org-table-insert-row "org-table" (&optional arg))
  151. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  152. (declare-function org-table-maybe-eval-formula "org-table" ())
  153. (declare-function org-table-maybe-recalculate-line "org-table" ())
  154. (declare-function org-table-next-row "org-table" ())
  155. (declare-function org-table-paste-rectangle "org-table" ())
  156. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  157. (declare-function org-table-wrap-region "org-table" (arg))
  158. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  159. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  160. (declare-function orgtbl-mode "org-table" (&optional arg))
  161. (defsubst org-uniquify (list)
  162. "Non-destructively remove duplicate elements from LIST."
  163. (let ((res (copy-sequence list))) (delete-dups res)))
  164. (defsubst org-get-at-bol (property)
  165. "Get text property PROPERTY at the beginning of line."
  166. (get-text-property (point-at-bol) property))
  167. (defsubst org-trim (s &optional keep-lead)
  168. "Remove whitespace at the beginning and the end of string S.
  169. When optional argument KEEP-LEAD is non-nil, removing blank lines
  170. at the beginning of the string does not affect leading indentation."
  171. (replace-regexp-in-string
  172. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  173. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  174. ;; load languages based on value of `org-babel-load-languages'
  175. (defvar org-babel-load-languages)
  176. ;;;###autoload
  177. (defun org-babel-do-load-languages (sym value)
  178. "Load the languages defined in `org-babel-load-languages'."
  179. (set-default sym value)
  180. (dolist (pair org-babel-load-languages)
  181. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  182. (if active
  183. (require (intern (concat "ob-" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-execute:" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-expand-body:" lang)))))))
  188. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  189. ;;;###autoload
  190. (defun org-babel-load-file (file &optional compile)
  191. "Load Emacs Lisp source code blocks in the Org FILE.
  192. This function exports the source code using `org-babel-tangle'
  193. and then loads the resulting file using `load-file'. With prefix
  194. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  195. file to byte-code before it is loaded."
  196. (interactive "fFile to load: \nP")
  197. (let* ((age (lambda (file)
  198. (float-time
  199. (time-subtract (current-time)
  200. (nth 5 (or (file-attributes (file-truename file))
  201. (file-attributes file)))))))
  202. (base-name (file-name-sans-extension file))
  203. (exported-file (concat base-name ".el")))
  204. ;; tangle if the Org file is newer than the elisp file
  205. (unless (and (file-exists-p exported-file)
  206. (> (funcall age file) (funcall age exported-file)))
  207. ;; Tangle-file traversal returns reversed list of tangled files
  208. ;; and we want to evaluate the first target.
  209. (setq exported-file
  210. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  211. (message "%s %s"
  212. (if compile
  213. (progn (byte-compile-file exported-file 'load)
  214. "Compiled and loaded")
  215. (progn (load-file exported-file) "Loaded"))
  216. exported-file)))
  217. (defcustom org-babel-load-languages '((emacs-lisp . t))
  218. "Languages which can be evaluated in Org buffers.
  219. This list can be used to load support for any of the languages
  220. below, note that each language will depend on a different set of
  221. system executables and/or Emacs modes. When a language is
  222. \"loaded\", then code blocks in that language can be evaluated
  223. with `org-babel-execute-src-block' bound by default to C-c
  224. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  225. be set to remove code block evaluation from the C-c C-c
  226. keybinding. By default only Emacs Lisp (which has no
  227. requirements) is loaded."
  228. :group 'org-babel
  229. :set 'org-babel-do-load-languages
  230. :version "24.1"
  231. :type '(alist :tag "Babel Languages"
  232. :key-type
  233. (choice
  234. (const :tag "Awk" awk)
  235. (const :tag "C" C)
  236. (const :tag "R" R)
  237. (const :tag "Asymptote" asymptote)
  238. (const :tag "Calc" calc)
  239. (const :tag "Clojure" clojure)
  240. (const :tag "CSS" css)
  241. (const :tag "Ditaa" ditaa)
  242. (const :tag "Dot" dot)
  243. (const :tag "Emacs Lisp" emacs-lisp)
  244. (const :tag "Forth" forth)
  245. (const :tag "Fortran" fortran)
  246. (const :tag "Gnuplot" gnuplot)
  247. (const :tag "Haskell" haskell)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "ebnf2ps" ebnf2ps))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-comment-string "COMMENT"
  462. "Entries starting with this keyword will never be exported.
  463. \\<org-mode-map>
  464. An entry can be toggled between COMMENT and normal with
  465. `\\[org-toggle-comment]'.")
  466. ;;;; LaTeX Environments and Fragments
  467. (defconst org-latex-regexps
  468. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  469. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  470. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  471. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  472. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  473. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  474. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  475. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  476. "Regular expressions for matching embedded LaTeX.")
  477. ;;;; Node Property
  478. (defconst org-effort-property "Effort"
  479. "The property that is being used to keep track of effort estimates.
  480. Effort estimates given in this property need to have the format H:MM.")
  481. ;;;; Table
  482. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  483. "Detect an org-type or table-type table.")
  484. (defconst org-table-line-regexp "^[ \t]*|"
  485. "Detect an org-type table line.")
  486. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  487. "Detect an org-type table line.")
  488. (defconst org-table-hline-regexp "^[ \t]*|-"
  489. "Detect an org-type table hline.")
  490. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  491. "Detect a table-type table hline.")
  492. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  493. "Detect the first line outside a table when searching from within it.
  494. This works for both table types.")
  495. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  496. "Detect a #+TBLFM line.")
  497. ;;;; Timestamp
  498. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  499. "Regular expression for fast time stamp matching.")
  500. (defconst org-ts-regexp-inactive
  501. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  502. "Regular expression for fast inactive time stamp matching.")
  503. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  504. "Regular expression for fast time stamp matching.")
  505. (defconst org-ts-regexp0
  506. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.
  508. This one does not require the space after the date, so it can be used
  509. on a string that terminates immediately after the date.")
  510. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  511. "Regular expression matching time strings for analysis.")
  512. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  513. "Regular expression matching time stamps, with groups.")
  514. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  515. "Regular expression matching time stamps (also [..]), with groups.")
  516. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  517. "Regular expression matching a time stamp range.")
  518. (defconst org-tr-regexp-both
  519. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  522. org-ts-regexp "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.")
  524. (defconst org-tsr-regexp-both
  525. (concat org-ts-regexp-both "\\(--?-?"
  526. org-ts-regexp-both "\\)?")
  527. "Regular expression matching a time stamp or time stamp range.
  528. The time stamps may be either active or inactive.")
  529. (defconst org-repeat-re
  530. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (dolist (ext org-modules)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. (setq org-modules-loaded t)))
  564. (defun org-set-modules (var value)
  565. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  566. (set var value)
  567. (when (featurep 'org)
  568. (org-load-modules-maybe 'force)
  569. (org-element-cache-reset 'all)))
  570. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  571. "Modules that should always be loaded together with org.el.
  572. If a description starts with <C>, the file is not part of Emacs
  573. and loading it will require that you have downloaded and properly
  574. installed the Org mode distribution.
  575. You can also use this system to load external packages (i.e. neither Org
  576. core modules, nor modules from the CONTRIB directory). Just add symbols
  577. to the end of the list. If the package is called org-xyz.el, then you need
  578. to add the symbol `xyz', and the package must have a call to:
  579. (provide \\='org-xyz)
  580. For export specific modules, see also `org-export-backends'."
  581. :group 'org
  582. :set 'org-set-modules
  583. :version "24.4"
  584. :package-version '(Org . "8.0")
  585. :type
  586. '(set :greedy t
  587. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  588. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  589. (const :tag " crypt: Encryption of subtrees" org-crypt)
  590. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  591. (const :tag " docview: Links to doc-view buffers" org-docview)
  592. (const :tag " eww: Store link to url of eww" org-eww)
  593. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" org-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  603. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  604. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  605. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  606. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  607. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  608. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  609. (const :tag "C collector: Collect properties into tables" org-collector)
  610. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  611. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  612. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  613. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  614. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  615. (const :tag "C eval: Include command output as text" org-eval)
  616. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  617. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  618. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  619. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  620. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  621. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  622. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  623. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  624. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  625. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  626. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  627. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  628. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  629. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  630. (const :tag "C registry: A registry for Org links" org-registry)
  631. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  632. (const :tag "C secretary: Team management with org-mode" org-secretary)
  633. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  634. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  635. (const :tag "C track: Keep up with Org mode development" org-track)
  636. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  637. (const :tag "C vm: Links to VM folders/messages" org-vm)
  638. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  639. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  640. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  641. (defvar org-export-registered-backends) ; From ox.el.
  642. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  643. (declare-function org-export-backend-name "ox" (backend) t)
  644. (defcustom org-export-backends '(ascii html icalendar latex odt)
  645. "List of export back-ends that should be always available.
  646. If a description starts with <C>, the file is not part of Emacs
  647. and loading it will require that you have downloaded and properly
  648. installed the Org mode distribution.
  649. Unlike to `org-modules', libraries in this list will not be
  650. loaded along with Org, but only once the export framework is
  651. needed.
  652. This variable needs to be set before org.el is loaded. If you
  653. need to make a change while Emacs is running, use the customize
  654. interface or run the following code, where VAL stands for the new
  655. value of the variable, after updating it:
  656. (progn
  657. (setq org-export-registered-backends
  658. (cl-remove-if-not
  659. (lambda (backend)
  660. (let ((name (org-export-backend-name backend)))
  661. (or (memq name val)
  662. (catch \\='parentp
  663. (dolist (b val)
  664. (and (org-export-derived-backend-p b name)
  665. (throw \\='parentp t)))))))
  666. org-export-registered-backends))
  667. (let ((new-list (mapcar #\\='org-export-backend-name
  668. org-export-registered-backends)))
  669. (dolist (backend val)
  670. (cond
  671. ((not (load (format \"ox-%s\" backend) t t))
  672. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  673. backend))
  674. ((not (memq backend new-list)) (push backend new-list))))
  675. (set-default \\='org-export-backends new-list)))
  676. Adding a back-end to this list will also pull the back-end it
  677. depends on, if any."
  678. :group 'org
  679. :group 'org-export
  680. :version "25.2"
  681. :package-version '(Org . "9.0")
  682. :initialize 'custom-initialize-set
  683. :set (lambda (var val)
  684. (if (not (featurep 'ox)) (set-default var val)
  685. ;; Any back-end not required anymore (not present in VAL and not
  686. ;; a parent of any back-end in the new value) is removed from the
  687. ;; list of registered back-ends.
  688. (setq org-export-registered-backends
  689. (cl-remove-if-not
  690. (lambda (backend)
  691. (let ((name (org-export-backend-name backend)))
  692. (or (memq name val)
  693. (catch 'parentp
  694. (dolist (b val)
  695. (and (org-export-derived-backend-p b name)
  696. (throw 'parentp t)))))))
  697. org-export-registered-backends))
  698. ;; Now build NEW-LIST of both new back-ends and required
  699. ;; parents.
  700. (let ((new-list (mapcar #'org-export-backend-name
  701. org-export-registered-backends)))
  702. (dolist (backend val)
  703. (cond
  704. ((not (load (format "ox-%s" backend) t t))
  705. (message "Problems while trying to load export back-end `%s'"
  706. backend))
  707. ((not (memq backend new-list)) (push backend new-list))))
  708. ;; Set VAR to that list with fixed dependencies.
  709. (set-default var new-list))))
  710. :type '(set :greedy t
  711. (const :tag " ascii Export buffer to ASCII format" ascii)
  712. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  713. (const :tag " html Export buffer to HTML format" html)
  714. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  715. (const :tag " latex Export buffer to LaTeX format" latex)
  716. (const :tag " man Export buffer to MAN format" man)
  717. (const :tag " md Export buffer to Markdown format" md)
  718. (const :tag " odt Export buffer to ODT format" odt)
  719. (const :tag " org Export buffer to Org format" org)
  720. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  721. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  722. (const :tag "C deck Export buffer to deck.js presentations" deck)
  723. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  724. (const :tag "C groff Export buffer to Groff format" groff)
  725. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  726. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  727. (const :tag "C s5 Export buffer to s5 presentations" s5)
  728. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  729. (eval-after-load 'ox
  730. '(dolist (backend org-export-backends)
  731. (condition-case nil (require (intern (format "ox-%s" backend)))
  732. (error (message "Problems while trying to load export back-end `%s'"
  733. backend)))))
  734. (defcustom org-support-shift-select nil
  735. "Non-nil means make shift-cursor commands select text when possible.
  736. \\<org-mode-map>\
  737. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  738. start selecting a region, or enlarge regions started in this way.
  739. In Org mode, in special contexts, these same keys are used for
  740. other purposes, important enough to compete with shift selection.
  741. Org tries to balance these needs by supporting `shift-select-mode'
  742. outside these special contexts, under control of this variable.
  743. The default of this variable is nil, to avoid confusing behavior. Shifted
  744. cursor keys will then execute Org commands in the following contexts:
  745. - on a headline, changing TODO state (left/right) and priority (up/down)
  746. - on a time stamp, changing the time
  747. - in a plain list item, changing the bullet type
  748. - in a property definition line, switching between allowed values
  749. - in the BEGIN line of a clock table (changing the time block).
  750. Outside these contexts, the commands will throw an error.
  751. When this variable is t and the cursor is not in a special
  752. context, Org mode will support shift-selection for making and
  753. enlarging regions. To make this more effective, the bullet
  754. cycling will no longer happen anywhere in an item line, but only
  755. if the cursor is exactly on the bullet.
  756. If you set this variable to the symbol `always', then the keys
  757. will not be special in headlines, property lines, and item lines,
  758. to make shift selection work there as well. If this is what you
  759. want, you can use the following alternative commands:
  760. `\\[org-todo]' and `\\[org-priority]' \
  761. to change TODO state and priority,
  762. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  763. can be used to switch TODO sets,
  764. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  765. and properties can be edited by hand or in column view.
  766. However, when the cursor is on a timestamp, shift-cursor commands
  767. will still edit the time stamp - this is just too good to give up."
  768. :group 'org
  769. :type '(choice
  770. (const :tag "Never" nil)
  771. (const :tag "When outside special context" t)
  772. (const :tag "Everywhere except timestamps" always)))
  773. (defcustom org-loop-over-headlines-in-active-region nil
  774. "Shall some commands act upon headlines in the active region?
  775. When set to t, some commands will be performed in all headlines
  776. within the active region.
  777. When set to `start-level', some commands will be performed in all
  778. headlines within the active region, provided that these headlines
  779. are of the same level than the first one.
  780. When set to a string, those commands will be performed on the
  781. matching headlines within the active region. Such string must be
  782. a tags/property/todo match as it is used in the agenda tags view.
  783. The list of commands is: `org-schedule', `org-deadline',
  784. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  785. `org-archive-to-archive-sibling'. The archiving commands skip
  786. already archived entries."
  787. :type '(choice (const :tag "Don't loop" nil)
  788. (const :tag "All headlines in active region" t)
  789. (const :tag "In active region, headlines at the same level than the first one" start-level)
  790. (string :tag "Tags/Property/Todo matcher"))
  791. :version "24.1"
  792. :group 'org-todo
  793. :group 'org-archive)
  794. (defgroup org-startup nil
  795. "Options concerning startup of Org mode."
  796. :tag "Org Startup"
  797. :group 'org)
  798. (defcustom org-startup-folded t
  799. "Non-nil means entering Org mode will switch to OVERVIEW.
  800. This can also be configured on a per-file basis by adding one of
  801. the following lines anywhere in the buffer:
  802. #+STARTUP: fold (or `overview', this is equivalent)
  803. #+STARTUP: nofold (or `showall', this is equivalent)
  804. #+STARTUP: content
  805. #+STARTUP: showeverything
  806. Set `org-agenda-inhibit-startup' to a non-nil value so as to
  807. ignore this option when Org opens agenda files for the first time."
  808. :group 'org-startup
  809. :type '(choice
  810. (const :tag "nofold: show all" nil)
  811. (const :tag "fold: overview" t)
  812. (const :tag "content: all headlines" content)
  813. (const :tag "show everything, even drawers" showeverything)))
  814. (defcustom org-startup-truncated t
  815. "Non-nil means entering Org mode will set `truncate-lines'.
  816. This is useful since some lines containing links can be very long and
  817. uninteresting. Also tables look terrible when wrapped.
  818. The variable `org-startup-truncated' allows to configure
  819. truncation for Org mode different to the other modes that use the
  820. variable `truncate-lines' and as a shortcut instead of putting
  821. the variable `truncate-lines' into the `org-mode-hook'. If one
  822. wants to configure truncation for Org mode not statically but
  823. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  824. the variable `truncate-lines' has to be used because in such a
  825. case it is too late to set the variable `org-startup-truncated'."
  826. :group 'org-startup
  827. :type 'boolean)
  828. (defcustom org-startup-indented nil
  829. "Non-nil means turn on `org-indent-mode' on startup.
  830. This can also be configured on a per-file basis by adding one of
  831. the following lines anywhere in the buffer:
  832. #+STARTUP: indent
  833. #+STARTUP: noindent"
  834. :group 'org-structure
  835. :type '(choice
  836. (const :tag "Not" nil)
  837. (const :tag "Globally (slow on startup in large files)" t)))
  838. (defcustom org-use-sub-superscripts t
  839. "Non-nil means interpret \"_\" and \"^\" for display.
  840. If you want to control how Org exports those characters, see
  841. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  842. used to be an alias for `org-export-with-sub-superscripts' in
  843. Org <8.0, it is not anymore.
  844. When this option is turned on, you can use TeX-like syntax for
  845. sub- and superscripts within the buffer. Several characters after
  846. \"_\" or \"^\" will be considered as a single item - so grouping
  847. with {} is normally not needed. For example, the following things
  848. will be parsed as single sub- or superscripts:
  849. 10^24 or 10^tau several digits will be considered 1 item.
  850. 10^-12 or 10^-tau a leading sign with digits or a word
  851. x^2-y^3 will be read as x^2 - y^3, because items are
  852. terminated by almost any nonword/nondigit char.
  853. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  854. Still, ambiguity is possible. So when in doubt, use {} to enclose
  855. the sub/superscript. If you set this variable to the symbol `{}',
  856. the braces are *required* in order to trigger interpretations as
  857. sub/superscript. This can be helpful in documents that need \"_\"
  858. frequently in plain text."
  859. :group 'org-startup
  860. :version "24.4"
  861. :package-version '(Org . "8.0")
  862. :type '(choice
  863. (const :tag "Always interpret" t)
  864. (const :tag "Only with braces" {})
  865. (const :tag "Never interpret" nil)))
  866. (defcustom org-startup-with-beamer-mode nil
  867. "Non-nil means turn on `org-beamer-mode' on startup.
  868. This can also be configured on a per-file basis by adding one of
  869. the following lines anywhere in the buffer:
  870. #+STARTUP: beamer"
  871. :group 'org-startup
  872. :version "24.1"
  873. :type 'boolean)
  874. (defcustom org-startup-align-all-tables nil
  875. "Non-nil means align all tables when visiting a file.
  876. This is useful when the column width in tables is forced with <N> cookies
  877. in table fields. Such tables will look correct only after the first re-align.
  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: align
  881. #+STARTUP: noalign"
  882. :group 'org-startup
  883. :type 'boolean)
  884. (defcustom org-startup-with-inline-images nil
  885. "Non-nil means show inline images when loading a new Org file.
  886. This can also be configured on a per-file basis by adding one of
  887. the following lines anywhere in the buffer:
  888. #+STARTUP: inlineimages
  889. #+STARTUP: noinlineimages"
  890. :group 'org-startup
  891. :version "24.1"
  892. :type 'boolean)
  893. (defcustom org-startup-with-latex-preview nil
  894. "Non-nil means preview LaTeX fragments when loading a new Org file.
  895. This can also be configured on a per-file basis by adding one of
  896. the following lines anywhere in the buffer:
  897. #+STARTUP: latexpreview
  898. #+STARTUP: nolatexpreview"
  899. :group 'org-startup
  900. :version "24.4"
  901. :package-version '(Org . "8.0")
  902. :type 'boolean)
  903. (defcustom org-insert-mode-line-in-empty-file nil
  904. "Non-nil means insert the first line setting Org mode in empty files.
  905. When the function `org-mode' is called interactively in an empty file, this
  906. normally means that the file name does not automatically trigger Org mode.
  907. To ensure that the file will always be in Org mode in the future, a
  908. line enforcing Org mode will be inserted into the buffer, if this option
  909. has been set."
  910. :group 'org-startup
  911. :type 'boolean)
  912. (defcustom org-replace-disputed-keys nil
  913. "Non-nil means use alternative key bindings for some keys.
  914. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  915. These keys are also used by other packages like shift-selection-mode'
  916. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  917. If you want to use Org mode together with one of these other modes,
  918. or more generally if you would like to move some Org mode commands to
  919. other keys, set this variable and configure the keys with the variable
  920. `org-disputed-keys'.
  921. This option is only relevant at load-time of Org mode, and must be set
  922. *before* org.el is loaded. Changing it requires a restart of Emacs to
  923. become effective."
  924. :group 'org-startup
  925. :type 'boolean)
  926. (defcustom org-use-extra-keys nil
  927. "Non-nil means use extra key sequence definitions for certain commands.
  928. This happens automatically if `window-system' is nil. This
  929. variable lets you do the same manually. You must set it before
  930. loading Org."
  931. :group 'org-startup
  932. :type 'boolean)
  933. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  934. (defcustom org-disputed-keys
  935. '(([(shift up)] . [(meta p)])
  936. ([(shift down)] . [(meta n)])
  937. ([(shift left)] . [(meta -)])
  938. ([(shift right)] . [(meta +)])
  939. ([(control shift right)] . [(meta shift +)])
  940. ([(control shift left)] . [(meta shift -)]))
  941. "Keys for which Org mode and other modes compete.
  942. This is an alist, cars are the default keys, second element specifies
  943. the alternative to use when `org-replace-disputed-keys' is t.
  944. Keys can be specified in any syntax supported by `define-key'.
  945. The value of this option takes effect only at Org mode startup,
  946. therefore you'll have to restart Emacs to apply it after changing."
  947. :group 'org-startup
  948. :type 'alist)
  949. (defun org-key (key)
  950. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  951. Or return the original if not disputed."
  952. (when org-replace-disputed-keys
  953. (let* ((nkey (key-description key))
  954. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  955. org-disputed-keys)))
  956. (setq key (if x (cdr x) key))))
  957. key)
  958. (defun org-defkey (keymap key def)
  959. "Define a key, possibly translated, as returned by `org-key'."
  960. (define-key keymap (org-key key) def))
  961. (defcustom org-ellipsis nil
  962. "The ellipsis to use in the Org mode outline.
  963. When nil, just use the standard three dots.
  964. When a string, use that string instead.
  965. The change affects only Org mode (which will then use its own display table).
  966. Changing this requires executing `\\[org-mode]' in a buffer to become
  967. effective."
  968. :group 'org-startup
  969. :type '(choice (const :tag "Default" nil)
  970. (string :tag "String" :value "...#"))
  971. :safe #'string-or-null-p)
  972. (defvar org-display-table nil
  973. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  974. (defgroup org-keywords nil
  975. "Keywords in Org mode."
  976. :tag "Org Keywords"
  977. :group 'org)
  978. (defcustom org-closed-keep-when-no-todo nil
  979. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  980. :group 'org-todo
  981. :group 'org-keywords
  982. :version "24.4"
  983. :package-version '(Org . "8.0")
  984. :type 'boolean)
  985. (defgroup org-structure nil
  986. "Options concerning the general structure of Org files."
  987. :tag "Org Structure"
  988. :group 'org)
  989. (defgroup org-reveal-location nil
  990. "Options about how to make context of a location visible."
  991. :tag "Org Reveal Location"
  992. :group 'org-structure)
  993. (defcustom org-show-context-detail '((agenda . local)
  994. (bookmark-jump . lineage)
  995. (isearch . lineage)
  996. (default . ancestors))
  997. "Alist between context and visibility span when revealing a location.
  998. \\<org-mode-map>Some actions may move point into invisible
  999. locations. As a consequence, Org always expose a neighborhood
  1000. around point. How much is shown depends on the initial action,
  1001. or context. Valid contexts are
  1002. agenda when exposing an entry from the agenda
  1003. org-goto when using the command `org-goto' (`\\[org-goto]')
  1004. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1005. tags-tree when constructing a sparse tree based on tags matches
  1006. link-search when exposing search matches associated with a link
  1007. mark-goto when exposing the jump goal of a mark
  1008. bookmark-jump when exposing a bookmark location
  1009. isearch when exiting from an incremental search
  1010. default default for all contexts not set explicitly
  1011. Allowed visibility spans are
  1012. minimal show current headline; if point is not on headline,
  1013. also show entry
  1014. local show current headline, entry and next headline
  1015. ancestors show current headline and its direct ancestors; if
  1016. point is not on headline, also show entry
  1017. lineage show current headline, its direct ancestors and all
  1018. their children; if point is not on headline, also show
  1019. entry and first child
  1020. tree show current headline, its direct ancestors and all
  1021. their children; if point is not on headline, also show
  1022. entry and all children
  1023. canonical show current headline, its direct ancestors along with
  1024. their entries and children; if point is not located on
  1025. the headline, also show current entry and all children
  1026. As special cases, a nil or t value means show all contexts in
  1027. `minimal' or `canonical' view, respectively.
  1028. Some views can make displayed information very compact, but also
  1029. make it harder to edit the location of the match. In such
  1030. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1031. more context."
  1032. :group 'org-reveal-location
  1033. :version "25.2"
  1034. :package-version '(Org . "9.0")
  1035. :type '(choice
  1036. (const :tag "Canonical" t)
  1037. (const :tag "Minimal" nil)
  1038. (repeat :greedy t :tag "Individual contexts"
  1039. (cons
  1040. (choice :tag "Context"
  1041. (const agenda)
  1042. (const org-goto)
  1043. (const occur-tree)
  1044. (const tags-tree)
  1045. (const link-search)
  1046. (const mark-goto)
  1047. (const bookmark-jump)
  1048. (const isearch)
  1049. (const default))
  1050. (choice :tag "Detail level"
  1051. (const minimal)
  1052. (const local)
  1053. (const ancestors)
  1054. (const lineage)
  1055. (const tree)
  1056. (const canonical))))))
  1057. (defcustom org-indirect-buffer-display 'other-window
  1058. "How should indirect tree buffers be displayed?
  1059. This applies to indirect buffers created with the commands
  1060. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1061. Valid values are:
  1062. current-window Display in the current window
  1063. other-window Just display in another window.
  1064. dedicated-frame Create one new frame, and re-use it each time.
  1065. new-frame Make a new frame each time. Note that in this case
  1066. previously-made indirect buffers are kept, and you need to
  1067. kill these buffers yourself."
  1068. :group 'org-structure
  1069. :group 'org-agenda-windows
  1070. :type '(choice
  1071. (const :tag "In current window" current-window)
  1072. (const :tag "In current frame, other window" other-window)
  1073. (const :tag "Each time a new frame" new-frame)
  1074. (const :tag "One dedicated frame" dedicated-frame)))
  1075. (defcustom org-use-speed-commands nil
  1076. "Non-nil means activate single letter commands at beginning of a headline.
  1077. This may also be a function to test for appropriate locations where speed
  1078. commands should be active.
  1079. For example, to activate speed commands when the point is on any
  1080. star at the beginning of the headline, you can do this:
  1081. (setq org-use-speed-commands
  1082. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1083. :group 'org-structure
  1084. :type '(choice
  1085. (const :tag "Never" nil)
  1086. (const :tag "At beginning of headline stars" t)
  1087. (function)))
  1088. (defcustom org-speed-commands-user nil
  1089. "Alist of additional speed commands.
  1090. This list will be checked before `org-speed-commands-default'
  1091. when the variable `org-use-speed-commands' is non-nil
  1092. and when the cursor is at the beginning of a headline.
  1093. The car if each entry is a string with a single letter, which must
  1094. be assigned to `self-insert-command' in the global map.
  1095. The cdr is either a command to be called interactively, a function
  1096. to be called, or a form to be evaluated.
  1097. An entry that is just a list with a single string will be interpreted
  1098. as a descriptive headline that will be added when listing the speed
  1099. commands in the Help buffer using the `?' speed command."
  1100. :group 'org-structure
  1101. :type '(repeat :value ("k" . ignore)
  1102. (choice :value ("k" . ignore)
  1103. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1104. (cons :tag "Letter and Command"
  1105. (string :tag "Command letter")
  1106. (choice
  1107. (function)
  1108. (sexp))))))
  1109. (defcustom org-bookmark-names-plist
  1110. '(:last-capture "org-capture-last-stored"
  1111. :last-refile "org-refile-last-stored"
  1112. :last-capture-marker "org-capture-last-stored-marker")
  1113. "Names for bookmarks automatically set by some Org commands.
  1114. This can provide strings as names for a number of bookmarks Org sets
  1115. automatically. The following keys are currently implemented:
  1116. :last-capture
  1117. :last-capture-marker
  1118. :last-refile
  1119. When a key does not show up in the property list, the corresponding bookmark
  1120. is not set."
  1121. :group 'org-structure
  1122. :type 'plist)
  1123. (defgroup org-cycle nil
  1124. "Options concerning visibility cycling in Org mode."
  1125. :tag "Org Cycle"
  1126. :group 'org-structure)
  1127. (defcustom org-cycle-skip-children-state-if-no-children t
  1128. "Non-nil means skip CHILDREN state in entries that don't have any."
  1129. :group 'org-cycle
  1130. :type 'boolean)
  1131. (defcustom org-cycle-max-level nil
  1132. "Maximum level which should still be subject to visibility cycling.
  1133. Levels higher than this will, for cycling, be treated as text, not a headline.
  1134. When `org-odd-levels-only' is set, a value of N in this variable actually
  1135. means 2N-1 stars as the limiting headline.
  1136. When nil, cycle all levels.
  1137. Note that the limiting level of cycling is also influenced by
  1138. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1139. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1140. than its value."
  1141. :group 'org-cycle
  1142. :type '(choice
  1143. (const :tag "No limit" nil)
  1144. (integer :tag "Maximum level")))
  1145. (defcustom org-hide-block-startup nil
  1146. "Non-nil means entering Org mode will fold all blocks.
  1147. This can also be set in on a per-file basis with
  1148. #+STARTUP: hideblocks
  1149. #+STARTUP: showblocks"
  1150. :group 'org-startup
  1151. :group 'org-cycle
  1152. :type 'boolean)
  1153. (defcustom org-cycle-global-at-bob nil
  1154. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1155. This makes it possible to do global cycling without having to use `S-TAB'
  1156. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1157. line of the buffer
  1158. must not be a headline -- it may be empty or some other text.
  1159. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1160. sure the cursor stays at the beginning of the buffer.
  1161. When this option is nil, don't do anything special at the beginning of
  1162. the buffer."
  1163. :group 'org-cycle
  1164. :type 'boolean)
  1165. (defcustom org-cycle-level-after-item/entry-creation t
  1166. "Non-nil means cycle entry level or item indentation in new empty entries.
  1167. When the cursor is at the end of an empty headline, i.e., with only stars
  1168. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1169. and then all possible ancestor states, before returning to the original state.
  1170. This makes data entry extremely fast: M-RET to create a new headline,
  1171. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1172. When the cursor is at the end of an empty plain list item, one TAB will
  1173. make it a subitem, two or more tabs will back up to make this an item
  1174. higher up in the item hierarchy."
  1175. :group 'org-cycle
  1176. :type 'boolean)
  1177. (defcustom org-cycle-emulate-tab t
  1178. "Where should `org-cycle' emulate TAB.
  1179. nil Never
  1180. white Only in completely white lines
  1181. whitestart Only at the beginning of lines, before the first non-white char
  1182. t Everywhere except in headlines
  1183. exc-hl-bol Everywhere except at the start of a headline
  1184. If TAB is used in a place where it does not emulate TAB, the current subtree
  1185. visibility is cycled."
  1186. :group 'org-cycle
  1187. :type '(choice (const :tag "Never" nil)
  1188. (const :tag "Only in completely white lines" white)
  1189. (const :tag "Before first char in a line" whitestart)
  1190. (const :tag "Everywhere except in headlines" t)
  1191. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1192. (defcustom org-cycle-separator-lines 2
  1193. "Number of empty lines needed to keep an empty line between collapsed trees.
  1194. If you leave an empty line between the end of a subtree and the following
  1195. headline, this empty line is hidden when the subtree is folded.
  1196. Org mode will leave (exactly) one empty line visible if the number of
  1197. empty lines is equal or larger to the number given in this variable.
  1198. So the default 2 means at least 2 empty lines after the end of a subtree
  1199. are needed to produce free space between a collapsed subtree and the
  1200. following headline.
  1201. If the number is negative, and the number of empty lines is at least -N,
  1202. all empty lines are shown.
  1203. Special case: when 0, never leave empty lines in collapsed view."
  1204. :group 'org-cycle
  1205. :type 'integer)
  1206. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1207. (defcustom org-pre-cycle-hook nil
  1208. "Hook that is run before visibility cycling is happening.
  1209. The function(s) in this hook must accept a single argument which indicates
  1210. the new state that will be set right after running this hook. The
  1211. argument is a symbol. Before a global state change, it can have the values
  1212. `overview', `content', or `all'. Before a local state change, it can have
  1213. the values `folded', `children', or `subtree'."
  1214. :group 'org-cycle
  1215. :type 'hook)
  1216. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1217. org-cycle-hide-drawers
  1218. org-cycle-show-empty-lines
  1219. org-optimize-window-after-visibility-change)
  1220. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1221. The function(s) in this hook must accept a single argument which indicates
  1222. the new state that was set by the most recent `org-cycle' command. The
  1223. argument is a symbol. After a global state change, it can have the values
  1224. `overview', `contents', or `all'. After a local state change, it can have
  1225. the values `folded', `children', or `subtree'."
  1226. :group 'org-cycle
  1227. :type 'hook
  1228. :version "25.2"
  1229. :package-version '(Org . "8.3"))
  1230. (defgroup org-edit-structure nil
  1231. "Options concerning structure editing in Org mode."
  1232. :tag "Org Edit Structure"
  1233. :group 'org-structure)
  1234. (defcustom org-odd-levels-only nil
  1235. "Non-nil means skip even levels and only use odd levels for the outline.
  1236. This has the effect that two stars are being added/taken away in
  1237. promotion/demotion commands. It also influences how levels are
  1238. handled by the exporters.
  1239. Changing it requires restart of `font-lock-mode' to become effective
  1240. for fontification also in regions already fontified.
  1241. You may also set this on a per-file basis by adding one of the following
  1242. lines to the buffer:
  1243. #+STARTUP: odd
  1244. #+STARTUP: oddeven"
  1245. :group 'org-edit-structure
  1246. :group 'org-appearance
  1247. :type 'boolean)
  1248. (defcustom org-adapt-indentation t
  1249. "Non-nil means adapt indentation to outline node level.
  1250. When this variable is set, Org assumes that you write outlines by
  1251. indenting text in each node to align with the headline (after the
  1252. stars). The following issues are influenced by this variable:
  1253. - The indentation is increased by one space in a demotion
  1254. command, and decreased by one in a promotion command. However,
  1255. in the latter case, if shifting some line in the entry body
  1256. would alter document structure (e.g., insert a new headline),
  1257. indentation is not changed at all.
  1258. - Property drawers and planning information is inserted indented
  1259. when this variable is set. When nil, they will not be indented.
  1260. - TAB indents a line relative to current level. The lines below
  1261. a headline will be indented when this variable is set.
  1262. Note that this is all about true indentation, by adding and
  1263. removing space characters. See also `org-indent.el' which does
  1264. level-dependent indentation in a virtual way, i.e. at display
  1265. time in Emacs."
  1266. :group 'org-edit-structure
  1267. :type 'boolean)
  1268. (defcustom org-special-ctrl-a/e nil
  1269. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1270. When t, `C-a' will bring back the cursor to the beginning of the
  1271. headline text, i.e. after the stars and after a possible TODO
  1272. keyword. In an item, this will be the position after bullet and
  1273. check-box, if any. When the cursor is already at that position,
  1274. another `C-a' will bring it to the beginning of the line.
  1275. `C-e' will jump to the end of the headline, ignoring the presence
  1276. of tags in the headline. A second `C-e' will then jump to the
  1277. true end of the line, after any tags. This also means that, when
  1278. this variable is non-nil, `C-e' also will never jump beyond the
  1279. end of the heading of a folded section, i.e. not after the
  1280. ellipses.
  1281. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1282. normally, going to the true line boundary first. Only a directly
  1283. following, identical keypress will bring the cursor to the
  1284. special positions.
  1285. This may also be a cons cell where the behavior for `C-a' and
  1286. `C-e' is set separately."
  1287. :group 'org-edit-structure
  1288. :type '(choice
  1289. (const :tag "off" nil)
  1290. (const :tag "on: after stars/bullet and before tags first" t)
  1291. (const :tag "reversed: true line boundary first" reversed)
  1292. (cons :tag "Set C-a and C-e separately"
  1293. (choice :tag "Special C-a"
  1294. (const :tag "off" nil)
  1295. (const :tag "on: after stars/bullet first" t)
  1296. (const :tag "reversed: before stars/bullet first" reversed))
  1297. (choice :tag "Special C-e"
  1298. (const :tag "off" nil)
  1299. (const :tag "on: before tags first" t)
  1300. (const :tag "reversed: after tags first" reversed)))))
  1301. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1302. (defcustom org-special-ctrl-k nil
  1303. "Non-nil means `C-k' will behave specially in headlines.
  1304. When nil, `C-k' will call the default `kill-line' command.
  1305. When t, the following will happen while the cursor is in the headline:
  1306. - When the cursor is at the beginning of a headline, kill the entire
  1307. line and possible the folded subtree below the line.
  1308. - When in the middle of the headline text, kill the headline up to the tags.
  1309. - When after the headline text, kill the tags."
  1310. :group 'org-edit-structure
  1311. :type 'boolean)
  1312. (defcustom org-ctrl-k-protect-subtree nil
  1313. "Non-nil means, do not delete a hidden subtree with C-k.
  1314. When set to the symbol `error', simply throw an error when C-k is
  1315. used to kill (part-of) a headline that has hidden text behind it.
  1316. Any other non-nil value will result in a query to the user, if it is
  1317. OK to kill that hidden subtree. When nil, kill without remorse."
  1318. :group 'org-edit-structure
  1319. :version "24.1"
  1320. :type '(choice
  1321. (const :tag "Do not protect hidden subtrees" nil)
  1322. (const :tag "Protect hidden subtrees with a security query" t)
  1323. (const :tag "Never kill a hidden subtree with C-k" error)))
  1324. (defcustom org-special-ctrl-o t
  1325. "Non-nil means, make `C-o' insert a row in tables."
  1326. :group 'org-edit-structure
  1327. :type 'boolean)
  1328. (defcustom org-catch-invisible-edits nil
  1329. "Check if in invisible region before inserting or deleting a character.
  1330. Valid values are:
  1331. nil Do not check, so just do invisible edits.
  1332. error Throw an error and do nothing.
  1333. show Make point visible, and do the requested edit.
  1334. show-and-error Make point visible, then throw an error and abort the edit.
  1335. smart Make point visible, and do insertion/deletion if it is
  1336. adjacent to visible text and the change feels predictable.
  1337. Never delete a previously invisible character or add in the
  1338. middle or right after an invisible region. Basically, this
  1339. allows insertion and backward-delete right before ellipses.
  1340. FIXME: maybe in this case we should not even show?"
  1341. :group 'org-edit-structure
  1342. :version "24.1"
  1343. :type '(choice
  1344. (const :tag "Do not check" nil)
  1345. (const :tag "Throw error when trying to edit" error)
  1346. (const :tag "Unhide, but do not do the edit" show-and-error)
  1347. (const :tag "Show invisible part and do the edit" show)
  1348. (const :tag "Be smart and do the right thing" smart)))
  1349. (defcustom org-yank-folded-subtrees t
  1350. "Non-nil means when yanking subtrees, fold them.
  1351. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1352. it starts with a heading and all other headings in it are either children
  1353. or siblings, then fold all the subtrees. However, do this only if no
  1354. text after the yank would be swallowed into a folded tree by this action."
  1355. :group 'org-edit-structure
  1356. :type 'boolean)
  1357. (defcustom org-yank-adjusted-subtrees nil
  1358. "Non-nil means when yanking subtrees, adjust the level.
  1359. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1360. this function for details."
  1361. :group 'org-edit-structure
  1362. :type 'boolean)
  1363. (defcustom org-M-RET-may-split-line '((default . t))
  1364. "Non-nil means M-RET will split the line at the cursor position.
  1365. When nil, it will go to the end of the line before making a
  1366. new line.
  1367. You may also set this option in a different way for different
  1368. contexts. Valid contexts are:
  1369. headline when creating a new headline
  1370. item when creating a new item
  1371. table in a table field
  1372. default the value to be used for all contexts not explicitly
  1373. customized"
  1374. :group 'org-structure
  1375. :group 'org-table
  1376. :type '(choice
  1377. (const :tag "Always" t)
  1378. (const :tag "Never" nil)
  1379. (repeat :greedy t :tag "Individual contexts"
  1380. (cons
  1381. (choice :tag "Context"
  1382. (const headline)
  1383. (const item)
  1384. (const table)
  1385. (const default))
  1386. (boolean)))))
  1387. (defcustom org-insert-heading-respect-content nil
  1388. "Non-nil means insert new headings after the current subtree.
  1389. \\<org-mode-map>
  1390. When nil, the new heading is created directly after the current line.
  1391. The commands `\\[org-insert-heading-respect-content]' and \
  1392. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1393. for the duration of the command."
  1394. :group 'org-structure
  1395. :type 'boolean)
  1396. (defcustom org-blank-before-new-entry '((heading . auto)
  1397. (plain-list-item . auto))
  1398. "Should `org-insert-heading' leave a blank line before new heading/item?
  1399. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1400. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1401. which case Org will look at the surrounding headings/items and try to
  1402. make an intelligent decision whether to insert a blank line or not."
  1403. :group 'org-edit-structure
  1404. :type '(list
  1405. (cons (const heading)
  1406. (choice (const :tag "Never" nil)
  1407. (const :tag "Always" t)
  1408. (const :tag "Auto" auto)))
  1409. (cons (const plain-list-item)
  1410. (choice (const :tag "Never" nil)
  1411. (const :tag "Always" t)
  1412. (const :tag "Auto" auto)))))
  1413. (defcustom org-insert-heading-hook nil
  1414. "Hook being run after inserting a new heading."
  1415. :group 'org-edit-structure
  1416. :type 'hook)
  1417. (defcustom org-enable-fixed-width-editor t
  1418. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1419. This currently only means they are never auto-wrapped.
  1420. When nil, such lines will be treated like ordinary lines."
  1421. :group 'org-edit-structure
  1422. :type 'boolean)
  1423. (defcustom org-goto-auto-isearch t
  1424. "Non-nil means typing characters in `org-goto' starts incremental search.
  1425. When nil, you can use these keybindings to navigate the buffer:
  1426. q Quit the org-goto interface
  1427. n Go to the next visible heading
  1428. p Go to the previous visible heading
  1429. f Go one heading forward on same level
  1430. b Go one heading backward on same level
  1431. u Go one heading up"
  1432. :group 'org-edit-structure
  1433. :type 'boolean)
  1434. (defgroup org-sparse-trees nil
  1435. "Options concerning sparse trees in Org mode."
  1436. :tag "Org Sparse Trees"
  1437. :group 'org-structure)
  1438. (defcustom org-highlight-sparse-tree-matches t
  1439. "Non-nil means highlight all matches that define a sparse tree.
  1440. The highlights will automatically disappear the next time the buffer is
  1441. changed by an edit command."
  1442. :group 'org-sparse-trees
  1443. :type 'boolean)
  1444. (defcustom org-remove-highlights-with-change t
  1445. "Non-nil means any change to the buffer will remove temporary highlights.
  1446. \\<org-mode-map>\
  1447. Such highlights are created by `org-occur' and `org-clock-display'.
  1448. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1449. to get rid of the highlights.
  1450. The highlights created by `org-toggle-latex-fragment' always need
  1451. `\\[org-toggle-latex-fragment]' to be removed."
  1452. :group 'org-sparse-trees
  1453. :group 'org-time
  1454. :type 'boolean)
  1455. (defcustom org-occur-case-fold-search t
  1456. "Non-nil means `org-occur' should be case-insensitive.
  1457. If set to `smart' the search will be case-insensitive only if it
  1458. doesn't specify any upper case character."
  1459. :group 'org-sparse-trees
  1460. :version "25.2"
  1461. :type '(choice
  1462. (const :tag "Case-sensitive" nil)
  1463. (const :tag "Case-insensitive" t)
  1464. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1465. (defcustom org-occur-hook '(org-first-headline-recenter)
  1466. "Hook that is run after `org-occur' has constructed a sparse tree.
  1467. This can be used to recenter the window to show as much of the structure
  1468. as possible."
  1469. :group 'org-sparse-trees
  1470. :type 'hook)
  1471. (defgroup org-imenu-and-speedbar nil
  1472. "Options concerning imenu and speedbar in Org mode."
  1473. :tag "Org Imenu and Speedbar"
  1474. :group 'org-structure)
  1475. (defcustom org-imenu-depth 2
  1476. "The maximum level for Imenu access to Org headlines.
  1477. This also applied for speedbar access."
  1478. :group 'org-imenu-and-speedbar
  1479. :type 'integer)
  1480. (defgroup org-table nil
  1481. "Options concerning tables in Org mode."
  1482. :tag "Org Table"
  1483. :group 'org)
  1484. (defcustom org-enable-table-editor 'optimized
  1485. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1486. When nil, such lines will be treated like ordinary lines.
  1487. When equal to the symbol `optimized', the table editor will be optimized to
  1488. do the following:
  1489. - Automatic overwrite mode in front of whitespace in table fields.
  1490. This makes the structure of the table stay in tact as long as the edited
  1491. field does not exceed the column width.
  1492. - Minimize the number of realigns. Normally, the table is aligned each time
  1493. TAB or RET are pressed to move to another field. With optimization this
  1494. happens only if changes to a field might have changed the column width.
  1495. Optimization requires replacing the functions `self-insert-command',
  1496. `delete-char', and `backward-delete-char' in Org buffers, with a
  1497. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1498. good at guessing when a re-align will be necessary, but you can always
  1499. force one with `\\[org-ctrl-c-ctrl-c]'.
  1500. If you would like to use the optimized version in Org mode, but the
  1501. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1502. This variable can be used to turn on and off the table editor during a session,
  1503. but in order to toggle optimization, a restart is required.
  1504. See also the variable `org-table-auto-blank-field'."
  1505. :group 'org-table
  1506. :type '(choice
  1507. (const :tag "off" nil)
  1508. (const :tag "on" t)
  1509. (const :tag "on, optimized" optimized)))
  1510. (defcustom org-self-insert-cluster-for-undo nil
  1511. "Non-nil means cluster self-insert commands for undo when possible.
  1512. If this is set, then, like in the Emacs command loop, 20 consecutive
  1513. characters will be undone together.
  1514. This is configurable, because there is some impact on typing performance."
  1515. :group 'org-table
  1516. :type 'boolean)
  1517. (defcustom org-table-tab-recognizes-table.el t
  1518. "Non-nil means TAB will automatically notice a table.el table.
  1519. When it sees such a table, it moves point into it and - if necessary -
  1520. calls `table-recognize-table'."
  1521. :group 'org-table-editing
  1522. :type 'boolean)
  1523. (defgroup org-link nil
  1524. "Options concerning links in Org mode."
  1525. :tag "Org Link"
  1526. :group 'org)
  1527. (defvar-local org-link-abbrev-alist-local nil
  1528. "Buffer-local version of `org-link-abbrev-alist', which see.
  1529. The value of this is taken from the #+LINK lines.")
  1530. (defcustom org-link-parameters
  1531. '(("doi" :follow org--open-doi-link)
  1532. ("elisp" :follow org--open-elisp-link)
  1533. ("file" :complete org-file-complete-link)
  1534. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1535. ("help" :follow org--open-help-link)
  1536. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1537. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1538. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1539. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1540. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1541. ("shell" :follow org--open-shell-link))
  1542. "An alist of properties that defines all the links in Org mode.
  1543. The key in each association is a string of the link type.
  1544. Subsequent optional elements make up a p-list of link properties.
  1545. :follow - A function that takes the link path as an argument.
  1546. :export - A function that takes the link path, description and
  1547. export-backend as arguments.
  1548. :store - A function responsible for storing the link. See the
  1549. function `org-store-link-functions'.
  1550. :complete - A function that inserts a link with completion. The
  1551. function takes one optional prefix arg.
  1552. :face - A face for the link, or a function that returns a face.
  1553. The function takes one argument which is the link path. The
  1554. default face is `org-link'.
  1555. :mouse-face - The mouse-face. The default is `highlight'.
  1556. :display - `full' will not fold the link in descriptive
  1557. display. Default is `org-link'.
  1558. :help-echo - A string or function that takes (window object position)
  1559. as arguments and returns a string.
  1560. :keymap - A keymap that is active on the link. The default is
  1561. `org-mouse-map'.
  1562. :htmlize-link - A function for the htmlize-link. Defaults
  1563. to (list :uri \"type:path\")
  1564. :activate-func - A function to run at the end of font-lock
  1565. activation. The function must accept (link-start link-end path bracketp)
  1566. as arguments."
  1567. :group 'org-link
  1568. :type '(alist :tag "Link display parameters"
  1569. :value-type plist))
  1570. (defun org-link-get-parameter (type key)
  1571. "Get TYPE link property for KEY.
  1572. TYPE is a string and KEY is a plist keyword."
  1573. (plist-get
  1574. (cdr (assoc type org-link-parameters))
  1575. key))
  1576. (defun org-link-set-parameters (type &rest parameters)
  1577. "Set link TYPE properties to PARAMETERS.
  1578. PARAMETERS should be :key val pairs."
  1579. (let ((data (assoc type org-link-parameters)))
  1580. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1581. (push (cons type parameters) org-link-parameters)
  1582. (org-make-link-regexps)
  1583. (org-element-update-syntax))))
  1584. (defun org-link-types ()
  1585. "Return a list of known link types."
  1586. (mapcar #'car org-link-parameters))
  1587. (defcustom org-link-abbrev-alist nil
  1588. "Alist of link abbreviations.
  1589. The car of each element is a string, to be replaced at the start of a link.
  1590. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1591. links in Org buffers can have an optional tag after a double colon, e.g.,
  1592. [[linkkey:tag][description]]
  1593. The `linkkey' must be a single word, starting with a letter, followed
  1594. by letters, numbers, `-' or `_'.
  1595. If REPLACE is a string, the tag will simply be appended to create the link.
  1596. If the string contains \"%s\", the tag will be inserted there. If the string
  1597. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1598. at that point (see the function `url-hexify-string'). If the string contains
  1599. the specifier \"%(my-function)\", then the custom function `my-function' will
  1600. be invoked: this function takes the tag as its only argument and must return
  1601. a string.
  1602. REPLACE may also be a function that will be called with the tag as the
  1603. only argument to create the link, which should be returned as a string.
  1604. See the manual for examples."
  1605. :group 'org-link
  1606. :type '(repeat
  1607. (cons
  1608. (string :tag "Protocol")
  1609. (choice
  1610. (string :tag "Format")
  1611. (function)))))
  1612. (defcustom org-descriptive-links t
  1613. "Non-nil means Org will display descriptive links.
  1614. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1615. \"Org Website\", hiding the link itself and just displaying its
  1616. description. When set to nil, Org will display the full links
  1617. literally.
  1618. You can interactively set the value of this variable by calling
  1619. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1620. :group 'org-link
  1621. :type 'boolean)
  1622. (defcustom org-link-file-path-type 'adaptive
  1623. "How the path name in file links should be stored.
  1624. Valid values are:
  1625. relative Relative to the current directory, i.e. the directory of the file
  1626. into which the link is being inserted.
  1627. absolute Absolute path, if possible with ~ for home directory.
  1628. noabbrev Absolute path, no abbreviation of home directory.
  1629. adaptive Use relative path for files in the current directory and sub-
  1630. directories of it. For other files, use an absolute path."
  1631. :group 'org-link
  1632. :type '(choice
  1633. (const relative)
  1634. (const absolute)
  1635. (const noabbrev)
  1636. (const adaptive)))
  1637. (defvaralias 'org-activate-links 'org-highlight-links)
  1638. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1639. "Types of links that should be highlighted in Org files.
  1640. This is a list of symbols, each one of them leading to the
  1641. highlighting of a certain link type.
  1642. You can still open links that are not highlighted.
  1643. In principle, it does not hurt to turn on highlighting for all
  1644. link types. There may be a small gain when turning off unused
  1645. link types. The types are:
  1646. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1647. angle Links in angular brackets that may contain whitespace like
  1648. <bbdb:Carsten Dominik>.
  1649. plain Plain links in normal text, no whitespace, like http://google.com.
  1650. radio Text that is matched by a radio target, see manual for details.
  1651. tag Tag settings in a headline (link to tag search).
  1652. date Time stamps (link to calendar).
  1653. footnote Footnote labels.
  1654. If you set this variable during an Emacs session, use `org-mode-restart'
  1655. in the Org buffer so that the change takes effect."
  1656. :group 'org-link
  1657. :group 'org-appearance
  1658. :type '(set :greedy t
  1659. (const :tag "Double bracket links" bracket)
  1660. (const :tag "Angular bracket links" angle)
  1661. (const :tag "Plain text links" plain)
  1662. (const :tag "Radio target matches" radio)
  1663. (const :tag "Tags" tag)
  1664. (const :tag "Timestamps" date)
  1665. (const :tag "Footnotes" footnote)))
  1666. (defcustom org-make-link-description-function nil
  1667. "Function to use for generating link descriptions from links.
  1668. When nil, the link location will be used. This function must take
  1669. two parameters: the first one is the link, the second one is the
  1670. description generated by `org-insert-link'. The function should
  1671. return the description to use."
  1672. :group 'org-link
  1673. :type '(choice (const nil) (function)))
  1674. (defgroup org-link-store nil
  1675. "Options concerning storing links in Org mode."
  1676. :tag "Org Store Link"
  1677. :group 'org-link)
  1678. (defcustom org-url-hexify-p t
  1679. "When non-nil, hexify URL when creating a link."
  1680. :type 'boolean
  1681. :version "24.3"
  1682. :group 'org-link-store)
  1683. (defcustom org-email-link-description-format "Email %c: %.30s"
  1684. "Format of the description part of a link to an email or usenet message.
  1685. The following %-escapes will be replaced by corresponding information:
  1686. %F full \"From\" field
  1687. %f name, taken from \"From\" field, address if no name
  1688. %T full \"To\" field
  1689. %t first name in \"To\" field, address if no name
  1690. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1691. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1692. %s subject
  1693. %d date
  1694. %m message-id.
  1695. You may use normal field width specification between the % and the letter.
  1696. This is for example useful to limit the length of the subject.
  1697. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1698. :group 'org-link-store
  1699. :type 'string)
  1700. (defcustom org-from-is-user-regexp
  1701. (let (r1 r2)
  1702. (when (and user-mail-address (not (string= user-mail-address "")))
  1703. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1704. (when (and user-full-name (not (string= user-full-name "")))
  1705. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1706. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1707. "Regexp matched against the \"From:\" header of an email or usenet message.
  1708. It should match if the message is from the user him/herself."
  1709. :group 'org-link-store
  1710. :type 'regexp)
  1711. (defcustom org-context-in-file-links t
  1712. "Non-nil means file links from `org-store-link' contain context.
  1713. \\<org-mode-map>
  1714. A search string will be added to the file name with :: as separator
  1715. and used to find the context when the link is activated by the command
  1716. `org-open-at-point'. When this option is t, the entire active region
  1717. will be placed in the search string of the file link. If set to a
  1718. positive integer, only the first n lines of context will be stored.
  1719. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1720. \\[org-store-link]')
  1721. negates this setting for the duration of the command."
  1722. :group 'org-link-store
  1723. :type '(choice boolean integer))
  1724. (defcustom org-keep-stored-link-after-insertion nil
  1725. "Non-nil means keep link in list for entire session.
  1726. \\<org-mode-map>
  1727. The command `org-store-link' adds a link pointing to the current
  1728. location to an internal list. These links accumulate during a session.
  1729. The command `org-insert-link' can be used to insert links into any
  1730. Org file (offering completion for all stored links).
  1731. When this option is nil, every link which has been inserted once using
  1732. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1733. unused
  1734. links more efficient."
  1735. :group 'org-link-store
  1736. :type 'boolean)
  1737. (defgroup org-link-follow nil
  1738. "Options concerning following links in Org mode."
  1739. :tag "Org Follow Link"
  1740. :group 'org-link)
  1741. (defcustom org-link-translation-function nil
  1742. "Function to translate links with different syntax to Org syntax.
  1743. This can be used to translate links created for example by the Planner
  1744. or emacs-wiki packages to Org syntax.
  1745. The function must accept two parameters, a TYPE containing the link
  1746. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1747. which is everything after the link protocol. It should return a cons
  1748. with possibly modified values of type and path.
  1749. Org contains a function for this, so if you set this variable to
  1750. `org-translate-link-from-planner', you should be able follow many
  1751. links created by planner."
  1752. :group 'org-link-follow
  1753. :type '(choice (const nil) (function)))
  1754. (defcustom org-follow-link-hook nil
  1755. "Hook that is run after a link has been followed."
  1756. :group 'org-link-follow
  1757. :type 'hook)
  1758. (defcustom org-tab-follows-link nil
  1759. "Non-nil means on links TAB will follow the link.
  1760. Needs to be set before org.el is loaded.
  1761. This really should not be used, it does not make sense, and the
  1762. implementation is bad."
  1763. :group 'org-link-follow
  1764. :type 'boolean)
  1765. (defcustom org-return-follows-link nil
  1766. "Non-nil means on links RET will follow the link.
  1767. In tables, the special behavior of RET has precedence."
  1768. :group 'org-link-follow
  1769. :type 'boolean)
  1770. (defcustom org-mouse-1-follows-link
  1771. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1772. "Non-nil means mouse-1 on a link will follow the link.
  1773. A longer mouse click will still set point. Needs to be set
  1774. before org.el is loaded."
  1775. :group 'org-link-follow
  1776. :version "24.4"
  1777. :package-version '(Org . "8.3")
  1778. :type '(choice
  1779. (const :tag "A double click follows the link" double)
  1780. (const :tag "Unconditionally follow the link with mouse-1" t)
  1781. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1782. (defcustom org-mark-ring-length 4
  1783. "Number of different positions to be recorded in the ring.
  1784. Changing this requires a restart of Emacs to work correctly."
  1785. :group 'org-link-follow
  1786. :type 'integer)
  1787. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1788. "Non-nil means internal links in Org files must exactly match a headline.
  1789. When nil, the link search tries to match a phrase with all words
  1790. in the search text."
  1791. :group 'org-link-follow
  1792. :version "24.1"
  1793. :type '(choice
  1794. (const :tag "Use fuzzy text search" nil)
  1795. (const :tag "Match only exact headline" t)
  1796. (const :tag "Match exact headline or query to create it"
  1797. query-to-create)))
  1798. (defcustom org-link-frame-setup
  1799. '((vm . vm-visit-folder-other-frame)
  1800. (vm-imap . vm-visit-imap-folder-other-frame)
  1801. (gnus . org-gnus-no-new-news)
  1802. (file . find-file-other-window)
  1803. (wl . wl-other-frame))
  1804. "Setup the frame configuration for following links.
  1805. When following a link with Emacs, it may often be useful to display
  1806. this link in another window or frame. This variable can be used to
  1807. set this up for the different types of links.
  1808. For VM, use any of
  1809. `vm-visit-folder'
  1810. `vm-visit-folder-other-window'
  1811. `vm-visit-folder-other-frame'
  1812. For Gnus, use any of
  1813. `gnus'
  1814. `gnus-other-frame'
  1815. `org-gnus-no-new-news'
  1816. For FILE, use any of
  1817. `find-file'
  1818. `find-file-other-window'
  1819. `find-file-other-frame'
  1820. For Wanderlust use any of
  1821. `wl'
  1822. `wl-other-frame'
  1823. For the calendar, use the variable `calendar-setup'.
  1824. For BBDB, it is currently only possible to display the matches in
  1825. another window."
  1826. :group 'org-link-follow
  1827. :type '(list
  1828. (cons (const vm)
  1829. (choice
  1830. (const vm-visit-folder)
  1831. (const vm-visit-folder-other-window)
  1832. (const vm-visit-folder-other-frame)))
  1833. (cons (const vm-imap)
  1834. (choice
  1835. (const vm-visit-imap-folder)
  1836. (const vm-visit-imap-folder-other-window)
  1837. (const vm-visit-imap-folder-other-frame)))
  1838. (cons (const gnus)
  1839. (choice
  1840. (const gnus)
  1841. (const gnus-other-frame)
  1842. (const org-gnus-no-new-news)))
  1843. (cons (const file)
  1844. (choice
  1845. (const find-file)
  1846. (const find-file-other-window)
  1847. (const find-file-other-frame)))
  1848. (cons (const wl)
  1849. (choice
  1850. (const wl)
  1851. (const wl-other-frame)))))
  1852. (defcustom org-display-internal-link-with-indirect-buffer nil
  1853. "Non-nil means use indirect buffer to display infile links.
  1854. Activating internal links (from one location in a file to another location
  1855. in the same file) normally just jumps to the location. When the link is
  1856. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1857. is displayed in
  1858. another window. When this option is set, the other window actually displays
  1859. an indirect buffer clone of the current buffer, to avoid any visibility
  1860. changes to the current buffer."
  1861. :group 'org-link-follow
  1862. :type 'boolean)
  1863. (defcustom org-open-non-existing-files nil
  1864. "Non-nil means `org-open-file' will open non-existing files.
  1865. When nil, an error will be generated.
  1866. This variable applies only to external applications because they
  1867. might choke on non-existing files. If the link is to a file that
  1868. will be opened in Emacs, the variable is ignored."
  1869. :group 'org-link-follow
  1870. :type 'boolean)
  1871. (defcustom org-open-directory-means-index-dot-org nil
  1872. "Non-nil means a link to a directory really means to index.org.
  1873. When nil, following a directory link will run dired or open a finder/explorer
  1874. window on that directory."
  1875. :group 'org-link-follow
  1876. :type 'boolean)
  1877. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1878. "Non-nil means ask for confirmation before executing shell links.
  1879. Shell links can be dangerous: just think about a link
  1880. [[shell:rm -rf ~/*][Google Search]]
  1881. This link would show up in your Org document as \"Google Search\",
  1882. but really it would remove your entire home directory.
  1883. Therefore we advise against setting this variable to nil.
  1884. Just change it to `y-or-n-p' if you want to confirm with a
  1885. single keystroke rather than having to type \"yes\"."
  1886. :group 'org-link-follow
  1887. :type '(choice
  1888. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1889. (const :tag "with y-or-n (faster)" y-or-n-p)
  1890. (const :tag "no confirmation (dangerous)" nil)))
  1891. (put 'org-confirm-shell-link-function
  1892. 'safe-local-variable
  1893. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1894. (defcustom org-confirm-shell-link-not-regexp ""
  1895. "A regexp to skip confirmation for shell links."
  1896. :group 'org-link-follow
  1897. :version "24.1"
  1898. :type 'regexp)
  1899. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1900. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1901. Elisp links can be dangerous: just think about a link
  1902. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1903. This link would show up in your Org document as \"Google Search\",
  1904. but really it would remove your entire home directory.
  1905. Therefore we advise against setting this variable to nil.
  1906. Just change it to `y-or-n-p' if you want to confirm with a
  1907. single keystroke rather than having to type \"yes\"."
  1908. :group 'org-link-follow
  1909. :type '(choice
  1910. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1911. (const :tag "with y-or-n (faster)" y-or-n-p)
  1912. (const :tag "no confirmation (dangerous)" nil)))
  1913. (put 'org-confirm-shell-link-function
  1914. 'safe-local-variable
  1915. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1916. (defcustom org-confirm-elisp-link-not-regexp ""
  1917. "A regexp to skip confirmation for Elisp links."
  1918. :group 'org-link-follow
  1919. :version "24.1"
  1920. :type 'regexp)
  1921. (defconst org-file-apps-defaults-gnu
  1922. '((remote . emacs)
  1923. (system . mailcap)
  1924. (t . mailcap))
  1925. "Default file applications on a UNIX or GNU/Linux system.
  1926. See `org-file-apps'.")
  1927. (defconst org-file-apps-defaults-macosx
  1928. '((remote . emacs)
  1929. (system . "open %s")
  1930. ("ps.gz" . "gv %s")
  1931. ("eps.gz" . "gv %s")
  1932. ("dvi" . "xdvi %s")
  1933. ("fig" . "xfig %s")
  1934. (t . "open %s"))
  1935. "Default file applications on a MacOS X system.
  1936. The system \"open\" is known as a default, but we use X11 applications
  1937. for some files for which the OS does not have a good default.
  1938. See `org-file-apps'.")
  1939. (defconst org-file-apps-defaults-windowsnt
  1940. (list '(remote . emacs)
  1941. (cons 'system (lambda (file _path)
  1942. (with-no-warnings (w32-shell-execute "open" file))))
  1943. (cons t (lambda (file _path)
  1944. (with-no-warnings (w32-shell-execute "open" file)))))
  1945. "Default file applications on a Windows NT system.
  1946. The system \"open\" is used for most files.
  1947. See `org-file-apps'.")
  1948. (defcustom org-file-apps
  1949. '((auto-mode . emacs)
  1950. ("\\.mm\\'" . default)
  1951. ("\\.x?html?\\'" . default)
  1952. ("\\.pdf\\'" . default))
  1953. "External applications for opening `file:path' items in a document.
  1954. \\<org-mode-map>\
  1955. Org mode uses system defaults for different file types, but
  1956. you can use this variable to set the application for a given file
  1957. extension. The entries in this list are cons cells where the car identifies
  1958. files and the cdr the corresponding command.
  1959. Possible values for the file identifier are:
  1960. \"string\" A string as a file identifier can be interpreted in different
  1961. ways, depending on its contents:
  1962. - Alphanumeric characters only:
  1963. Match links with this file extension.
  1964. Example: (\"pdf\" . \"evince %s\")
  1965. to open PDFs with evince.
  1966. - Regular expression: Match links where the
  1967. filename matches the regexp. If you want to
  1968. use groups here, use shy groups.
  1969. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1970. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1971. to open *.html and *.xhtml with firefox.
  1972. - Regular expression which contains (non-shy) groups:
  1973. Match links where the whole link, including \"::\", and
  1974. anything after that, matches the regexp.
  1975. In a custom command string, %1, %2, etc. are replaced with
  1976. the parts of the link that were matched by the groups.
  1977. For backwards compatibility, if a command string is given
  1978. that does not use any of the group matches, this case is
  1979. handled identically to the second one (i.e. match against
  1980. file name only).
  1981. In a custom function, you can access the group matches with
  1982. (match-string n link).
  1983. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1984. \"evince -p %1 %s\")
  1985. to open [[file:document.pdf::5]] with evince at page 5.
  1986. `directory' Matches a directory
  1987. `remote' Matches a remote file, accessible through tramp or efs.
  1988. Remote files most likely should be visited through Emacs
  1989. because external applications cannot handle such paths.
  1990. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1991. so all files Emacs knows how to handle. Using this with
  1992. command `emacs' will open most files in Emacs. Beware that this
  1993. will also open html files inside Emacs, unless you add
  1994. (\"html\" . default) to the list as well.
  1995. `system' The system command to open files, like `open' on Windows
  1996. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1997. that will be selected if you call `org-open-at-point' with a
  1998. double prefix argument (`\\[universal-argument] \
  1999. \\[universal-argument] \\[org-open-at-point]').
  2000. t Default for files not matched by any of the other options.
  2001. Possible values for the command are:
  2002. `emacs' The file will be visited by the current Emacs process.
  2003. `default' Use the default application for this file type, which is the
  2004. association for t in the list, most likely in the system-specific
  2005. part. This can be used to overrule an unwanted setting in the
  2006. system-specific variable.
  2007. `system' Use the system command for opening files, like \"open\".
  2008. This command is specified by the entry whose car is `system'.
  2009. Most likely, the system-specific version of this variable
  2010. does define this command, but you can overrule/replace it
  2011. here.
  2012. `mailcap' Use command specified in the mailcaps.
  2013. string A command to be executed by a shell; %s will be replaced
  2014. by the path to the file.
  2015. function A Lisp function, which will be called with two arguments:
  2016. the file path and the original link string, without the
  2017. \"file:\" prefix.
  2018. For more examples, see the system specific constants
  2019. `org-file-apps-defaults-macosx'
  2020. `org-file-apps-defaults-windowsnt'
  2021. `org-file-apps-defaults-gnu'."
  2022. :group 'org-link-follow
  2023. :type '(repeat
  2024. (cons (choice :value ""
  2025. (string :tag "Extension")
  2026. (const :tag "System command to open files" system)
  2027. (const :tag "Default for unrecognized files" t)
  2028. (const :tag "Remote file" remote)
  2029. (const :tag "Links to a directory" directory)
  2030. (const :tag "Any files that have Emacs modes"
  2031. auto-mode))
  2032. (choice :value ""
  2033. (const :tag "Visit with Emacs" emacs)
  2034. (const :tag "Use default" default)
  2035. (const :tag "Use the system command" system)
  2036. (string :tag "Command")
  2037. (function :tag "Function")))))
  2038. (defcustom org-doi-server-url "http://dx.doi.org/"
  2039. "The URL of the DOI server."
  2040. :type 'string
  2041. :version "24.3"
  2042. :group 'org-link-follow)
  2043. (defgroup org-refile nil
  2044. "Options concerning refiling entries in Org mode."
  2045. :tag "Org Refile"
  2046. :group 'org)
  2047. (defcustom org-directory "~/org"
  2048. "Directory with Org files.
  2049. This is just a default location to look for Org files. There is no need
  2050. at all to put your files into this directory. It is used in the
  2051. following situations:
  2052. 1. When a capture template specifies a target file that is not an
  2053. absolute path. The path will then be interpreted relative to
  2054. `org-directory'
  2055. 2. When the value of variable `org-agenda-files' is a single file, any
  2056. relative paths in this file will be taken as relative to
  2057. `org-directory'."
  2058. :group 'org-refile
  2059. :group 'org-capture
  2060. :type 'directory)
  2061. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2062. "Default target for storing notes.
  2063. Used as a fall back file for org-capture.el, for templates that
  2064. do not specify a target file."
  2065. :group 'org-refile
  2066. :group 'org-capture
  2067. :type 'file)
  2068. (defcustom org-goto-interface 'outline
  2069. "The default interface to be used for `org-goto'.
  2070. Allowed values are:
  2071. outline The interface shows an outline of the relevant file
  2072. and the correct heading is found by moving through
  2073. the outline or by searching with incremental search.
  2074. outline-path-completion Headlines in the current buffer are offered via
  2075. completion. This is the interface also used by
  2076. the refile command."
  2077. :group 'org-refile
  2078. :type '(choice
  2079. (const :tag "Outline" outline)
  2080. (const :tag "Outline-path-completion" outline-path-completion)))
  2081. (defcustom org-goto-max-level 5
  2082. "Maximum target level when running `org-goto' with refile interface."
  2083. :group 'org-refile
  2084. :type 'integer)
  2085. (defcustom org-reverse-note-order nil
  2086. "Non-nil means store new notes at the beginning of a file or entry.
  2087. When nil, new notes will be filed to the end of a file or entry.
  2088. This can also be a list with cons cells of regular expressions that
  2089. are matched against file names, and values."
  2090. :group 'org-capture
  2091. :group 'org-refile
  2092. :type '(choice
  2093. (const :tag "Reverse always" t)
  2094. (const :tag "Reverse never" nil)
  2095. (repeat :tag "By file name regexp"
  2096. (cons regexp boolean))))
  2097. (defcustom org-log-refile nil
  2098. "Information to record when a task is refiled.
  2099. Possible values are:
  2100. nil Don't add anything
  2101. time Add a time stamp to the task
  2102. note Prompt for a note and add it with template `org-log-note-headings'
  2103. This option can also be set with on a per-file-basis with
  2104. #+STARTUP: nologrefile
  2105. #+STARTUP: logrefile
  2106. #+STARTUP: lognoterefile
  2107. You can have local logging settings for a subtree by setting the LOGGING
  2108. property to one or more of these keywords.
  2109. When bulk-refiling from the agenda, the value `note' is forbidden and
  2110. will temporarily be changed to `time'."
  2111. :group 'org-refile
  2112. :group 'org-progress
  2113. :version "24.1"
  2114. :type '(choice
  2115. (const :tag "No logging" nil)
  2116. (const :tag "Record timestamp" time)
  2117. (const :tag "Record timestamp with note." note)))
  2118. (defcustom org-refile-targets nil
  2119. "Targets for refiling entries with `\\[org-refile]'.
  2120. This is a list of cons cells. Each cell contains:
  2121. - a specification of the files to be considered, either a list of files,
  2122. or a symbol whose function or variable value will be used to retrieve
  2123. a file name or a list of file names. If you use `org-agenda-files' for
  2124. that, all agenda files will be scanned for targets. Nil means consider
  2125. headings in the current buffer.
  2126. - A specification of how to find candidate refile targets. This may be
  2127. any of:
  2128. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2129. This tag has to be present in all target headlines, inheritance will
  2130. not be considered.
  2131. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2132. todo keyword.
  2133. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2134. headlines that are refiling targets.
  2135. - a cons cell (:level . N). Any headline of level N is considered a target.
  2136. Note that, when `org-odd-levels-only' is set, level corresponds to
  2137. order in hierarchy, not to the number of stars.
  2138. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2139. Note that, when `org-odd-levels-only' is set, level corresponds to
  2140. order in hierarchy, not to the number of stars.
  2141. Each element of this list generates a set of possible targets.
  2142. The union of these sets is presented (with completion) to
  2143. the user by `org-refile'.
  2144. You can set the variable `org-refile-target-verify-function' to a function
  2145. to verify each headline found by the simple criteria above.
  2146. When this variable is nil, all top-level headlines in the current buffer
  2147. are used, equivalent to the value `((nil . (:level . 1))'."
  2148. :group 'org-refile
  2149. :type '(repeat
  2150. (cons
  2151. (choice :value org-agenda-files
  2152. (const :tag "All agenda files" org-agenda-files)
  2153. (const :tag "Current buffer" nil)
  2154. (function) (variable) (file))
  2155. (choice :tag "Identify target headline by"
  2156. (cons :tag "Specific tag" (const :value :tag) (string))
  2157. (cons :tag "TODO keyword" (const :value :todo) (string))
  2158. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2159. (cons :tag "Level number" (const :value :level) (integer))
  2160. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2161. (defcustom org-refile-target-verify-function nil
  2162. "Function to verify if the headline at point should be a refile target.
  2163. The function will be called without arguments, with point at the
  2164. beginning of the headline. It should return t and leave point
  2165. where it is if the headline is a valid target for refiling.
  2166. If the target should not be selected, the function must return nil.
  2167. In addition to this, it may move point to a place from where the search
  2168. should be continued. For example, the function may decide that the entire
  2169. subtree of the current entry should be excluded and move point to the end
  2170. of the subtree."
  2171. :group 'org-refile
  2172. :type '(choice
  2173. (const nil)
  2174. (function)))
  2175. (defcustom org-refile-use-cache nil
  2176. "Non-nil means cache refile targets to speed up the process.
  2177. \\<org-mode-map>\
  2178. The cache for a particular file will be updated automatically when
  2179. the buffer has been killed, or when any of the marker used for flagging
  2180. refile targets no longer points at a live buffer.
  2181. If you have added new entries to a buffer that might themselves be targets,
  2182. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2183. if you find that easier, \
  2184. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2185. \\[org-refile]'."
  2186. :group 'org-refile
  2187. :version "24.1"
  2188. :type 'boolean)
  2189. (defcustom org-refile-use-outline-path nil
  2190. "Non-nil means provide refile targets as paths.
  2191. So a level 3 headline will be available as level1/level2/level3.
  2192. When the value is `file', also include the file name (without directory)
  2193. into the path. In this case, you can also stop the completion after
  2194. the file name, to get entries inserted as top level in the file.
  2195. When `full-file-path', include the full file path."
  2196. :group 'org-refile
  2197. :type '(choice
  2198. (const :tag "Not" nil)
  2199. (const :tag "Yes" t)
  2200. (const :tag "Start with file name" file)
  2201. (const :tag "Start with full file path" full-file-path)))
  2202. (defcustom org-outline-path-complete-in-steps t
  2203. "Non-nil means complete the outline path in hierarchical steps.
  2204. When Org uses the refile interface to select an outline path (see
  2205. `org-refile-use-outline-path'), the completion of the path can be
  2206. done in a single go, or it can be done in steps down the headline
  2207. hierarchy. Going in steps is probably the best if you do not use
  2208. a special completion package like `ido' or `icicles'. However,
  2209. when using these packages, going in one step can be very fast,
  2210. while still showing the whole path to the entry."
  2211. :group 'org-refile
  2212. :type 'boolean)
  2213. (defcustom org-refile-allow-creating-parent-nodes nil
  2214. "Non-nil means allow the creation of new nodes as refile targets.
  2215. New nodes are then created by adding \"/new node name\" to the completion
  2216. of an existing node. When the value of this variable is `confirm',
  2217. new node creation must be confirmed by the user (recommended).
  2218. When nil, the completion must match an existing entry.
  2219. Note that, if the new heading is not seen by the criteria
  2220. listed in `org-refile-targets', multiple instances of the same
  2221. heading would be created by trying again to file under the new
  2222. heading."
  2223. :group 'org-refile
  2224. :type '(choice
  2225. (const :tag "Never" nil)
  2226. (const :tag "Always" t)
  2227. (const :tag "Prompt for confirmation" confirm)))
  2228. (defcustom org-refile-active-region-within-subtree nil
  2229. "Non-nil means also refile active region within a subtree.
  2230. By default `org-refile' doesn't allow refiling regions if they
  2231. don't contain a set of subtrees, but it might be convenient to
  2232. do so sometimes: in that case, the first line of the region is
  2233. converted to a headline before refiling."
  2234. :group 'org-refile
  2235. :version "24.1"
  2236. :type 'boolean)
  2237. (defgroup org-todo nil
  2238. "Options concerning TODO items in Org mode."
  2239. :tag "Org TODO"
  2240. :group 'org)
  2241. (defgroup org-progress nil
  2242. "Options concerning Progress logging in Org mode."
  2243. :tag "Org Progress"
  2244. :group 'org-time)
  2245. (defvar org-todo-interpretation-widgets
  2246. '((:tag "Sequence (cycling hits every state)" sequence)
  2247. (:tag "Type (cycling directly to DONE)" type))
  2248. "The available interpretation symbols for customizing `org-todo-keywords'.
  2249. Interested libraries should add to this list.")
  2250. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2251. "List of TODO entry keyword sequences and their interpretation.
  2252. \\<org-mode-map>This is a list of sequences.
  2253. Each sequence starts with a symbol, either `sequence' or `type',
  2254. indicating if the keywords should be interpreted as a sequence of
  2255. action steps, or as different types of TODO items. The first
  2256. keywords are states requiring action - these states will select a headline
  2257. for inclusion into the global TODO list Org produces. If one of the
  2258. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2259. signify that no further action is necessary. If \"|\" is not found,
  2260. the last keyword is treated as the only DONE state of the sequence.
  2261. The command `\\[org-todo]' cycles an entry through these states, and one
  2262. additional state where no keyword is present. For details about this
  2263. cycling, see the manual.
  2264. TODO keywords and interpretation can also be set on a per-file basis with
  2265. the special #+SEQ_TODO and #+TYP_TODO lines.
  2266. Each keyword can optionally specify a character for fast state selection
  2267. \(in combination with the variable `org-use-fast-todo-selection')
  2268. and specifiers for state change logging, using the same syntax that
  2269. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2270. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2271. indicates to record a time stamp each time this state is selected.
  2272. Each keyword may also specify if a timestamp or a note should be
  2273. recorded when entering or leaving the state, by adding additional
  2274. characters in the parenthesis after the keyword. This looks like this:
  2275. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2276. record only the time of the state change. With X and Y being either
  2277. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2278. Y when leaving the state if and only if the *target* state does not
  2279. define X. You may omit any of the fast-selection key or X or /Y,
  2280. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2281. For backward compatibility, this variable may also be just a list
  2282. of keywords. In this case the interpretation (sequence or type) will be
  2283. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2284. :group 'org-todo
  2285. :group 'org-keywords
  2286. :type '(choice
  2287. (repeat :tag "Old syntax, just keywords"
  2288. (string :tag "Keyword"))
  2289. (repeat :tag "New syntax"
  2290. (cons
  2291. (choice
  2292. :tag "Interpretation"
  2293. ;;Quick and dirty way to see
  2294. ;;`org-todo-interpretations'. This takes the
  2295. ;;place of item arguments
  2296. :convert-widget
  2297. (lambda (widget)
  2298. (widget-put widget
  2299. :args (mapcar
  2300. (lambda (x)
  2301. (widget-convert
  2302. (cons 'const x)))
  2303. org-todo-interpretation-widgets))
  2304. widget))
  2305. (repeat
  2306. (string :tag "Keyword"))))))
  2307. (defvar-local org-todo-keywords-1 nil
  2308. "All TODO and DONE keywords active in a buffer.")
  2309. (defvar org-todo-keywords-for-agenda nil)
  2310. (defvar org-done-keywords-for-agenda nil)
  2311. (defvar org-todo-keyword-alist-for-agenda nil)
  2312. (defvar org-tag-alist-for-agenda nil
  2313. "Alist of all tags from all agenda files.")
  2314. (defvar org-tag-groups-alist-for-agenda nil
  2315. "Alist of all groups tags from all current agenda files.")
  2316. (defvar-local org-tag-groups-alist nil)
  2317. (defvar org-agenda-contributing-files nil)
  2318. (defvar-local org-current-tag-alist nil
  2319. "Alist of all tag groups in current buffer.
  2320. This variable takes into consideration `org-tag-alist',
  2321. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2322. (defvar-local org-not-done-keywords nil)
  2323. (defvar-local org-done-keywords nil)
  2324. (defvar-local org-todo-heads nil)
  2325. (defvar-local org-todo-sets nil)
  2326. (defvar-local org-todo-log-states nil)
  2327. (defvar-local org-todo-kwd-alist nil)
  2328. (defvar-local org-todo-key-alist nil)
  2329. (defvar-local org-todo-key-trigger nil)
  2330. (defcustom org-todo-interpretation 'sequence
  2331. "Controls how TODO keywords are interpreted.
  2332. This variable is in principle obsolete and is only used for
  2333. backward compatibility, if the interpretation of todo keywords is
  2334. not given already in `org-todo-keywords'. See that variable for
  2335. more information."
  2336. :group 'org-todo
  2337. :group 'org-keywords
  2338. :type '(choice (const sequence)
  2339. (const type)))
  2340. (defcustom org-use-fast-todo-selection t
  2341. "\\<org-mode-map>\
  2342. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2343. This variable describes if and under what circumstances the cycling
  2344. mechanism for TODO keywords will be replaced by a single-key, direct
  2345. selection scheme.
  2346. When nil, fast selection is never used.
  2347. When the symbol `prefix', it will be used when `org-todo' is called
  2348. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2349. in an Org buffer, and
  2350. `\\[universal-argument] t' in an agenda buffer.
  2351. When t, fast selection is used by default. In this case, the prefix
  2352. argument forces cycling instead.
  2353. In all cases, the special interface is only used if access keys have
  2354. actually been assigned by the user, i.e. if keywords in the configuration
  2355. are followed by a letter in parenthesis, like TODO(t)."
  2356. :group 'org-todo
  2357. :type '(choice
  2358. (const :tag "Never" nil)
  2359. (const :tag "By default" t)
  2360. (const :tag "Only with C-u C-c C-t" prefix)))
  2361. (defcustom org-provide-todo-statistics t
  2362. "Non-nil means update todo statistics after insert and toggle.
  2363. ALL-HEADLINES means update todo statistics by including headlines
  2364. with no TODO keyword as well, counting them as not done.
  2365. A list of TODO keywords means the same, but skip keywords that are
  2366. not in this list.
  2367. When set to a list of two lists, the first list contains keywords
  2368. to consider as TODO keywords, the second list contains keywords
  2369. to consider as DONE keywords.
  2370. When this is set, todo statistics is updated in the parent of the
  2371. current entry each time a todo state is changed."
  2372. :group 'org-todo
  2373. :type '(choice
  2374. (const :tag "Yes, only for TODO entries" t)
  2375. (const :tag "Yes, including all entries" all-headlines)
  2376. (repeat :tag "Yes, for TODOs in this list"
  2377. (string :tag "TODO keyword"))
  2378. (list :tag "Yes, for TODOs and DONEs in these lists"
  2379. (repeat (string :tag "TODO keyword"))
  2380. (repeat (string :tag "DONE keyword")))
  2381. (other :tag "No TODO statistics" nil)))
  2382. (defcustom org-hierarchical-todo-statistics t
  2383. "Non-nil means TODO statistics covers just direct children.
  2384. When nil, all entries in the subtree are considered.
  2385. This has only an effect if `org-provide-todo-statistics' is set.
  2386. To set this to nil for only a single subtree, use a COOKIE_DATA
  2387. property and include the word \"recursive\" into the value."
  2388. :group 'org-todo
  2389. :type 'boolean)
  2390. (defcustom org-after-todo-state-change-hook nil
  2391. "Hook which is run after the state of a TODO item was changed.
  2392. The new state (a string with a TODO keyword, or nil) is available in the
  2393. Lisp variable `org-state'."
  2394. :group 'org-todo
  2395. :type 'hook)
  2396. (defvar org-blocker-hook nil
  2397. "Hook for functions that are allowed to block a state change.
  2398. Functions in this hook should not modify the buffer.
  2399. Each function gets as its single argument a property list,
  2400. see `org-trigger-hook' for more information about this list.
  2401. If any of the functions in this hook returns nil, the state change
  2402. is blocked.")
  2403. (defvar org-trigger-hook nil
  2404. "Hook for functions that are triggered by a state change.
  2405. Each function gets as its single argument a property list with at
  2406. least the following elements:
  2407. (:type type-of-change :position pos-at-entry-start
  2408. :from old-state :to new-state)
  2409. Depending on the type, more properties may be present.
  2410. This mechanism is currently implemented for:
  2411. TODO state changes
  2412. ------------------
  2413. :type todo-state-change
  2414. :from previous state (keyword as a string), or nil, or a symbol
  2415. `todo' or `done', to indicate the general type of state.
  2416. :to new state, like in :from")
  2417. (defcustom org-enforce-todo-dependencies nil
  2418. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2419. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2420. be blocked if any prior sibling is not yet done.
  2421. Finally, if the parent is blocked because of ordered siblings of its own,
  2422. the child will also be blocked."
  2423. :set (lambda (var val)
  2424. (set var val)
  2425. (if val
  2426. (add-hook 'org-blocker-hook
  2427. 'org-block-todo-from-children-or-siblings-or-parent)
  2428. (remove-hook 'org-blocker-hook
  2429. 'org-block-todo-from-children-or-siblings-or-parent)))
  2430. :group 'org-todo
  2431. :type 'boolean)
  2432. (defcustom org-enforce-todo-checkbox-dependencies nil
  2433. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2434. When this is nil, checkboxes have no influence on switching TODO states.
  2435. When non-nil, you first need to check off all check boxes before the TODO
  2436. entry can be switched to DONE.
  2437. This variable needs to be set before org.el is loaded, and you need to
  2438. restart Emacs after a change to make the change effective. The only way
  2439. to change is while Emacs is running is through the customize interface."
  2440. :set (lambda (var val)
  2441. (set var val)
  2442. (if val
  2443. (add-hook 'org-blocker-hook
  2444. 'org-block-todo-from-checkboxes)
  2445. (remove-hook 'org-blocker-hook
  2446. 'org-block-todo-from-checkboxes)))
  2447. :group 'org-todo
  2448. :type 'boolean)
  2449. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2450. "Non-nil means inserting a TODO heading is treated as state change.
  2451. So when the command `\\[org-insert-todo-heading]' is used, state change
  2452. logging will apply if appropriate. When nil, the new TODO item will
  2453. be inserted directly, and no logging will take place."
  2454. :group 'org-todo
  2455. :type 'boolean)
  2456. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2457. "Non-nil means switching TODO states with S-cursor counts as state change.
  2458. This is the default behavior. However, setting this to nil allows a
  2459. convenient way to select a TODO state and bypass any logging associated
  2460. with that."
  2461. :group 'org-todo
  2462. :type 'boolean)
  2463. (defcustom org-todo-state-tags-triggers nil
  2464. "Tag changes that should be triggered by TODO state changes.
  2465. This is a list. Each entry is
  2466. (state-change (tag . flag) .......)
  2467. State-change can be a string with a state, and empty string to indicate the
  2468. state that has no TODO keyword, or it can be one of the symbols `todo'
  2469. or `done', meaning any not-done or done state, respectively."
  2470. :group 'org-todo
  2471. :group 'org-tags
  2472. :type '(repeat
  2473. (cons (choice :tag "When changing to"
  2474. (const :tag "Not-done state" todo)
  2475. (const :tag "Done state" done)
  2476. (string :tag "State"))
  2477. (repeat
  2478. (cons :tag "Tag action"
  2479. (string :tag "Tag")
  2480. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2481. (defcustom org-log-done nil
  2482. "Information to record when a task moves to the DONE state.
  2483. Possible values are:
  2484. nil Don't add anything, just change the keyword
  2485. time Add a time stamp to the task
  2486. note Prompt for a note and add it with template `org-log-note-headings'
  2487. This option can also be set with on a per-file-basis with
  2488. #+STARTUP: nologdone
  2489. #+STARTUP: logdone
  2490. #+STARTUP: lognotedone
  2491. You can have local logging settings for a subtree by setting the LOGGING
  2492. property to one or more of these keywords."
  2493. :group 'org-todo
  2494. :group 'org-progress
  2495. :type '(choice
  2496. (const :tag "No logging" nil)
  2497. (const :tag "Record CLOSED timestamp" time)
  2498. (const :tag "Record CLOSED timestamp with note." note)))
  2499. ;; Normalize old uses of org-log-done.
  2500. (cond
  2501. ((eq org-log-done t) (setq org-log-done 'time))
  2502. ((and (listp org-log-done) (memq 'done org-log-done))
  2503. (setq org-log-done 'note)))
  2504. (defcustom org-log-reschedule nil
  2505. "Information to record when the scheduling date of a tasks is modified.
  2506. Possible values are:
  2507. nil Don't add anything, just change the date
  2508. time Add a time stamp to the task
  2509. note Prompt for a note and add it with template `org-log-note-headings'
  2510. This option can also be set with on a per-file-basis with
  2511. #+STARTUP: nologreschedule
  2512. #+STARTUP: logreschedule
  2513. #+STARTUP: lognotereschedule"
  2514. :group 'org-todo
  2515. :group 'org-progress
  2516. :type '(choice
  2517. (const :tag "No logging" nil)
  2518. (const :tag "Record timestamp" time)
  2519. (const :tag "Record timestamp with note." note)))
  2520. (defcustom org-log-redeadline nil
  2521. "Information to record when the deadline date of a tasks is modified.
  2522. Possible values are:
  2523. nil Don't add anything, just change the date
  2524. time Add a time stamp to the task
  2525. note Prompt for a note and add it with template `org-log-note-headings'
  2526. This option can also be set with on a per-file-basis with
  2527. #+STARTUP: nologredeadline
  2528. #+STARTUP: logredeadline
  2529. #+STARTUP: lognoteredeadline
  2530. You can have local logging settings for a subtree by setting the LOGGING
  2531. property to one or more of these keywords."
  2532. :group 'org-todo
  2533. :group 'org-progress
  2534. :type '(choice
  2535. (const :tag "No logging" nil)
  2536. (const :tag "Record timestamp" time)
  2537. (const :tag "Record timestamp with note." note)))
  2538. (defcustom org-log-note-clock-out nil
  2539. "Non-nil means record a note when clocking out of an item.
  2540. This can also be configured on a per-file basis by adding one of
  2541. the following lines anywhere in the buffer:
  2542. #+STARTUP: lognoteclock-out
  2543. #+STARTUP: nolognoteclock-out"
  2544. :group 'org-todo
  2545. :group 'org-progress
  2546. :type 'boolean)
  2547. (defcustom org-log-done-with-time t
  2548. "Non-nil means the CLOSED time stamp will contain date and time.
  2549. When nil, only the date will be recorded."
  2550. :group 'org-progress
  2551. :type 'boolean)
  2552. (defcustom org-log-note-headings
  2553. '((done . "CLOSING NOTE %t")
  2554. (state . "State %-12s from %-12S %t")
  2555. (note . "Note taken on %t")
  2556. (reschedule . "Rescheduled from %S on %t")
  2557. (delschedule . "Not scheduled, was %S on %t")
  2558. (redeadline . "New deadline from %S on %t")
  2559. (deldeadline . "Removed deadline, was %S on %t")
  2560. (refile . "Refiled on %t")
  2561. (clock-out . ""))
  2562. "Headings for notes added to entries.
  2563. The value is an alist, with the car being a symbol indicating the
  2564. note context, and the cdr is the heading to be used. The heading
  2565. may also be the empty string. The following placeholders can be
  2566. used:
  2567. %t a time stamp.
  2568. %T an active time stamp instead the default inactive one
  2569. %d a short-format time stamp.
  2570. %D an active short-format time stamp.
  2571. %s the new TODO state or time stamp (inactive), in double quotes.
  2572. %S the old TODO state or time stamp (inactive), in double quotes.
  2573. %u the user name.
  2574. %U full user name.
  2575. In fact, it is not a good idea to change the `state' entry,
  2576. because Agenda Log mode depends on the format of these entries."
  2577. :group 'org-todo
  2578. :group 'org-progress
  2579. :type '(list :greedy t
  2580. (cons (const :tag "Heading when closing an item" done) string)
  2581. (cons (const :tag
  2582. "Heading when changing todo state (todo sequence only)"
  2583. state) string)
  2584. (cons (const :tag "Heading when just taking a note" note) string)
  2585. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2586. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2587. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2588. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2589. (cons (const :tag "Heading when refiling" refile) string)
  2590. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2591. (unless (assq 'note org-log-note-headings)
  2592. (push '(note . "%t") org-log-note-headings))
  2593. (defcustom org-log-into-drawer nil
  2594. "Non-nil means insert state change notes and time stamps into a drawer.
  2595. When nil, state changes notes will be inserted after the headline and
  2596. any scheduling and clock lines, but not inside a drawer.
  2597. The value of this variable should be the name of the drawer to use.
  2598. LOGBOOK is proposed as the default drawer for this purpose, you can
  2599. also set this to a string to define the drawer of your choice.
  2600. A value of t is also allowed, representing \"LOGBOOK\".
  2601. A value of t or nil can also be set with on a per-file-basis with
  2602. #+STARTUP: logdrawer
  2603. #+STARTUP: nologdrawer
  2604. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2605. will be ignored.
  2606. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2607. a subtree.
  2608. Do not check directly this variable in a Lisp program. Call
  2609. function `org-log-into-drawer' instead."
  2610. :group 'org-todo
  2611. :group 'org-progress
  2612. :type '(choice
  2613. (const :tag "Not into a drawer" nil)
  2614. (const :tag "LOGBOOK" t)
  2615. (string :tag "Other")))
  2616. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2617. (defun org-log-into-drawer ()
  2618. "Name of the log drawer, as a string, or nil.
  2619. This is the value of `org-log-into-drawer'. However, if the
  2620. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2621. be used instead of the default value."
  2622. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2623. (cond ((equal p "nil") nil)
  2624. ((equal p "t") "LOGBOOK")
  2625. ((stringp p) p)
  2626. (p "LOGBOOK")
  2627. ((stringp org-log-into-drawer) org-log-into-drawer)
  2628. (org-log-into-drawer "LOGBOOK"))))
  2629. (defcustom org-log-state-notes-insert-after-drawers nil
  2630. "Non-nil means insert state change notes after any drawers in entry.
  2631. Only the drawers that *immediately* follow the headline and the
  2632. deadline/scheduled line are skipped.
  2633. When nil, insert notes right after the heading and perhaps the line
  2634. with deadline/scheduling if present.
  2635. This variable will have no effect if `org-log-into-drawer' is
  2636. set."
  2637. :group 'org-todo
  2638. :group 'org-progress
  2639. :type 'boolean)
  2640. (defcustom org-log-states-order-reversed t
  2641. "Non-nil means the latest state note will be directly after heading.
  2642. When nil, the state change notes will be ordered according to time.
  2643. This option can also be set with on a per-file-basis with
  2644. #+STARTUP: logstatesreversed
  2645. #+STARTUP: nologstatesreversed"
  2646. :group 'org-todo
  2647. :group 'org-progress
  2648. :type 'boolean)
  2649. (defcustom org-todo-repeat-to-state nil
  2650. "The TODO state to which a repeater should return the repeating task.
  2651. By default this is the first task in a TODO sequence, or the previous state
  2652. in a TODO_TYP set. But you can specify another task here.
  2653. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2654. :group 'org-todo
  2655. :version "24.1"
  2656. :type '(choice (const :tag "Head of sequence" nil)
  2657. (string :tag "Specific state")))
  2658. (defcustom org-log-repeat 'time
  2659. "Non-nil means record moving through the DONE state when triggering repeat.
  2660. An auto-repeating task is immediately switched back to TODO when
  2661. marked DONE. If you are not logging state changes (by adding \"@\"
  2662. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2663. record a closing note, there will be no record of the task moving
  2664. through DONE. This variable forces taking a note anyway.
  2665. nil Don't force a record
  2666. time Record a time stamp
  2667. note Prompt for a note and add it with template `org-log-note-headings'
  2668. This option can also be set with on a per-file-basis with
  2669. #+STARTUP: nologrepeat
  2670. #+STARTUP: logrepeat
  2671. #+STARTUP: lognoterepeat
  2672. You can have local logging settings for a subtree by setting the LOGGING
  2673. property to one or more of these keywords."
  2674. :group 'org-todo
  2675. :group 'org-progress
  2676. :type '(choice
  2677. (const :tag "Don't force a record" nil)
  2678. (const :tag "Force recording the DONE state" time)
  2679. (const :tag "Force recording a note with the DONE state" note)))
  2680. (defgroup org-priorities nil
  2681. "Priorities in Org mode."
  2682. :tag "Org Priorities"
  2683. :group 'org-todo)
  2684. (defcustom org-enable-priority-commands t
  2685. "Non-nil means priority commands are active.
  2686. When nil, these commands will be disabled, so that you never accidentally
  2687. set a priority."
  2688. :group 'org-priorities
  2689. :type 'boolean)
  2690. (defcustom org-highest-priority ?A
  2691. "The highest priority of TODO items. A character like ?A, ?B etc.
  2692. Must have a smaller ASCII number than `org-lowest-priority'."
  2693. :group 'org-priorities
  2694. :type 'character)
  2695. (defcustom org-lowest-priority ?C
  2696. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2697. Must have a larger ASCII number than `org-highest-priority'."
  2698. :group 'org-priorities
  2699. :type 'character)
  2700. (defcustom org-default-priority ?B
  2701. "The default priority of TODO items.
  2702. This is the priority an item gets if no explicit priority is given.
  2703. When starting to cycle on an empty priority the first step in the cycle
  2704. depends on `org-priority-start-cycle-with-default'. The resulting first
  2705. step priority must not exceed the range from `org-highest-priority' to
  2706. `org-lowest-priority' which means that `org-default-priority' has to be
  2707. in this range exclusive or inclusive the range boundaries. Else the
  2708. first step refuses to set the default and the second will fall back
  2709. to (depending on the command used) the highest or lowest priority."
  2710. :group 'org-priorities
  2711. :type 'character)
  2712. (defcustom org-priority-start-cycle-with-default t
  2713. "Non-nil means start with default priority when starting to cycle.
  2714. When this is nil, the first step in the cycle will be (depending on the
  2715. command used) one higher or lower than the default priority.
  2716. See also `org-default-priority'."
  2717. :group 'org-priorities
  2718. :type 'boolean)
  2719. (defcustom org-get-priority-function nil
  2720. "Function to extract the priority from a string.
  2721. The string is normally the headline. If this is nil Org computes the
  2722. priority from the priority cookie like [#A] in the headline. It returns
  2723. an integer, increasing by 1000 for each priority level.
  2724. The user can set a different function here, which should take a string
  2725. as an argument and return the numeric priority."
  2726. :group 'org-priorities
  2727. :version "24.1"
  2728. :type '(choice
  2729. (const nil)
  2730. (function)))
  2731. (defgroup org-time nil
  2732. "Options concerning time stamps and deadlines in Org mode."
  2733. :tag "Org Time"
  2734. :group 'org)
  2735. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2736. "Number of minutes to round time stamps to.
  2737. \\<org-mode-map>\
  2738. These are two values, the first applies when first creating a time stamp.
  2739. The second applies when changing it with the commands `S-up' and `S-down'.
  2740. When changing the time stamp, this means that it will change in steps
  2741. of N minutes, as given by the second value.
  2742. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2743. numbers should be factors of 60, so for example 5, 10, 15.
  2744. When this is larger than 1, you can still force an exact time stamp by using
  2745. a double prefix argument to a time stamp command like \
  2746. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2747. and by using a prefix arg to `S-up/down' to specify the exact number
  2748. of minutes to shift."
  2749. :group 'org-time
  2750. :get (lambda (var) ; Make sure both elements are there
  2751. (if (integerp (default-value var))
  2752. (list (default-value var) 5)
  2753. (default-value var)))
  2754. :type '(list
  2755. (integer :tag "when inserting times")
  2756. (integer :tag "when modifying times")))
  2757. ;; Normalize old customizations of this variable.
  2758. (when (integerp org-time-stamp-rounding-minutes)
  2759. (setq org-time-stamp-rounding-minutes
  2760. (list org-time-stamp-rounding-minutes
  2761. org-time-stamp-rounding-minutes)))
  2762. (defcustom org-display-custom-times nil
  2763. "Non-nil means overlay custom formats over all time stamps.
  2764. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2765. To turn this on on a per-file basis, insert anywhere in the file:
  2766. #+STARTUP: customtime"
  2767. :group 'org-time
  2768. :set 'set-default
  2769. :type 'sexp)
  2770. (make-variable-buffer-local 'org-display-custom-times)
  2771. (defcustom org-time-stamp-custom-formats
  2772. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2773. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2774. These are overlaid over the default ISO format if the variable
  2775. `org-display-custom-times' is set. Time like %H:%M should be at the
  2776. end of the second format. The custom formats are also honored by export
  2777. commands, if custom time display is turned on at the time of export."
  2778. :group 'org-time
  2779. :type 'sexp)
  2780. (defun org-time-stamp-format (&optional long inactive)
  2781. "Get the right format for a time string."
  2782. (let ((f (if long (cdr org-time-stamp-formats)
  2783. (car org-time-stamp-formats))))
  2784. (if inactive
  2785. (concat "[" (substring f 1 -1) "]")
  2786. f)))
  2787. (defcustom org-time-clocksum-format
  2788. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2789. "The format string used when creating CLOCKSUM lines.
  2790. This is also used when Org mode generates a time duration.
  2791. The value can be a single format string containing two
  2792. %-sequences, which will be filled with the number of hours and
  2793. minutes in that order.
  2794. Alternatively, the value can be a plist associating any of the
  2795. keys :years, :months, :weeks, :days, :hours or :minutes with
  2796. format strings. The time duration is formatted using only the
  2797. time components that are needed and concatenating the results.
  2798. If a time unit in absent, it falls back to the next smallest
  2799. unit.
  2800. The keys :require-years, :require-months, :require-days,
  2801. :require-weeks, :require-hours, :require-minutes are also
  2802. meaningful. A non-nil value for these keys indicates that the
  2803. corresponding time component should always be included, even if
  2804. its value is 0.
  2805. For example,
  2806. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2807. :require-minutes t)
  2808. means durations longer than a day will be expressed in days,
  2809. hours and minutes, and durations less than a day will always be
  2810. expressed in hours and minutes (even for durations less than an
  2811. hour).
  2812. The value
  2813. (:days \"%dd\" :minutes \"%dm\")
  2814. means durations longer than a day will be expressed in days and
  2815. minutes, and durations less than a day will be expressed entirely
  2816. in minutes (even for durations longer than an hour)."
  2817. :group 'org-time
  2818. :group 'org-clock
  2819. :version "24.4"
  2820. :package-version '(Org . "8.0")
  2821. :type '(choice (string :tag "Format string")
  2822. (set :tag "Plist"
  2823. (group :inline t (const :tag "Years" :years)
  2824. (string :tag "Format string"))
  2825. (group :inline t
  2826. (const :tag "Always show years" :require-years)
  2827. (const t))
  2828. (group :inline t (const :tag "Months" :months)
  2829. (string :tag "Format string"))
  2830. (group :inline t
  2831. (const :tag "Always show months" :require-months)
  2832. (const t))
  2833. (group :inline t (const :tag "Weeks" :weeks)
  2834. (string :tag "Format string"))
  2835. (group :inline t
  2836. (const :tag "Always show weeks" :require-weeks)
  2837. (const t))
  2838. (group :inline t (const :tag "Days" :days)
  2839. (string :tag "Format string"))
  2840. (group :inline t
  2841. (const :tag "Always show days" :require-days)
  2842. (const t))
  2843. (group :inline t (const :tag "Hours" :hours)
  2844. (string :tag "Format string"))
  2845. (group :inline t
  2846. (const :tag "Always show hours" :require-hours)
  2847. (const t))
  2848. (group :inline t (const :tag "Minutes" :minutes)
  2849. (string :tag "Format string"))
  2850. (group :inline t
  2851. (const :tag "Always show minutes" :require-minutes)
  2852. (const t)))))
  2853. (defcustom org-time-clocksum-use-fractional nil
  2854. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2855. See `org-time-clocksum-format' for more on time clock formats."
  2856. :group 'org-time
  2857. :group 'org-clock
  2858. :version "24.3"
  2859. :type 'boolean)
  2860. (defcustom org-time-clocksum-use-effort-durations nil
  2861. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2862. E.g. by default, one day is considered to be a 8 hours effort,
  2863. so a task that has been clocked for 16 hours will be displayed
  2864. as during 2 days in the clock display or in the clocktable.
  2865. See `org-effort-durations' on how to set effort durations
  2866. and `org-time-clocksum-format' for more on time clock formats."
  2867. :group 'org-time
  2868. :group 'org-clock
  2869. :version "24.4"
  2870. :package-version '(Org . "8.0")
  2871. :type 'boolean)
  2872. (defcustom org-time-clocksum-fractional-format "%.2f"
  2873. "The format string used when creating CLOCKSUM lines,
  2874. or when Org mode generates a time duration, if
  2875. `org-time-clocksum-use-fractional' is enabled.
  2876. The value can be a single format string containing one
  2877. %-sequence, which will be filled with the number of hours as
  2878. a float.
  2879. Alternatively, the value can be a plist associating any of the
  2880. keys :years, :months, :weeks, :days, :hours or :minutes with
  2881. a format string. The time duration is formatted using the
  2882. largest time unit which gives a non-zero integer part. If all
  2883. specified formats have zero integer part, the smallest time unit
  2884. is used."
  2885. :group 'org-time
  2886. :type '(choice (string :tag "Format string")
  2887. (set (group :inline t (const :tag "Years" :years)
  2888. (string :tag "Format string"))
  2889. (group :inline t (const :tag "Months" :months)
  2890. (string :tag "Format string"))
  2891. (group :inline t (const :tag "Weeks" :weeks)
  2892. (string :tag "Format string"))
  2893. (group :inline t (const :tag "Days" :days)
  2894. (string :tag "Format string"))
  2895. (group :inline t (const :tag "Hours" :hours)
  2896. (string :tag "Format string"))
  2897. (group :inline t (const :tag "Minutes" :minutes)
  2898. (string :tag "Format string")))))
  2899. (defcustom org-deadline-warning-days 14
  2900. "Number of days before expiration during which a deadline becomes active.
  2901. This variable governs the display in sparse trees and in the agenda.
  2902. When 0 or negative, it means use this number (the absolute value of it)
  2903. even if a deadline has a different individual lead time specified.
  2904. Custom commands can set this variable in the options section."
  2905. :group 'org-time
  2906. :group 'org-agenda-daily/weekly
  2907. :type 'integer)
  2908. (defcustom org-scheduled-delay-days 0
  2909. "Number of days before a scheduled item becomes active.
  2910. This variable governs the display in sparse trees and in the agenda.
  2911. The default value (i.e. 0) means: don't delay scheduled item.
  2912. When negative, it means use this number (the absolute value of it)
  2913. even if a scheduled item has a different individual delay time
  2914. specified.
  2915. Custom commands can set this variable in the options section."
  2916. :group 'org-time
  2917. :group 'org-agenda-daily/weekly
  2918. :version "24.4"
  2919. :package-version '(Org . "8.0")
  2920. :type 'integer)
  2921. (defcustom org-read-date-prefer-future t
  2922. "Non-nil means assume future for incomplete date input from user.
  2923. This affects the following situations:
  2924. 1. The user gives a month but not a year.
  2925. For example, if it is April and you enter \"feb 2\", this will be read
  2926. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2927. 2. The user gives a day, but no month.
  2928. For example, if today is the 15th, and you enter \"3\", Org will read
  2929. this as the third of *next* month. However, if you enter \"17\",
  2930. it will be considered as *this* month.
  2931. If you set this variable to the symbol `time', then also the following
  2932. will work:
  2933. 3. If the user gives a time.
  2934. If the time is before now, it will be interpreted as tomorrow.
  2935. Currently none of this works for ISO week specifications.
  2936. When this option is nil, the current day, month and year will always be
  2937. used as defaults.
  2938. See also `org-agenda-jump-prefer-future'."
  2939. :group 'org-time
  2940. :type '(choice
  2941. (const :tag "Never" nil)
  2942. (const :tag "Check month and day" t)
  2943. (const :tag "Check month, day, and time" time)))
  2944. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2945. "Should the agenda jump command prefer the future for incomplete dates?
  2946. The default is to do the same as configured in `org-read-date-prefer-future'.
  2947. But you can also set a deviating value here.
  2948. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2949. :group 'org-agenda
  2950. :group 'org-time
  2951. :version "24.1"
  2952. :type '(choice
  2953. (const :tag "Use org-read-date-prefer-future"
  2954. org-read-date-prefer-future)
  2955. (const :tag "Never" nil)
  2956. (const :tag "Always" t)))
  2957. (defcustom org-read-date-force-compatible-dates t
  2958. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2959. Depending on the system Emacs is running on, certain dates cannot
  2960. be represented with the type used internally to represent time.
  2961. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2962. correctly. Some systems allow for earlier dates, some for later,
  2963. some for both. One way to find out it to insert any date into an
  2964. Org buffer, putting the cursor on the year and hitting S-up and
  2965. S-down to test the range.
  2966. When this variable is set to t, the date/time prompt will not let
  2967. you specify dates outside the 1970-2037 range, so it is certain that
  2968. these dates will work in whatever version of Emacs you are
  2969. running, and also that you can move a file from one Emacs implementation
  2970. to another. WHenever Org is forcing the year for you, it will display
  2971. a message and beep.
  2972. When this variable is nil, Org will check if the date is
  2973. representable in the specific Emacs implementation you are using.
  2974. If not, it will force a year, usually the current year, and beep
  2975. to remind you. Currently this setting is not recommended because
  2976. the likelihood that you will open your Org files in an Emacs that
  2977. has limited date range is not negligible.
  2978. A workaround for this problem is to use diary sexp dates for time
  2979. stamps outside of this range."
  2980. :group 'org-time
  2981. :version "24.1"
  2982. :type 'boolean)
  2983. (defcustom org-read-date-display-live t
  2984. "Non-nil means display current interpretation of date prompt live.
  2985. This display will be in an overlay, in the minibuffer."
  2986. :group 'org-time
  2987. :type 'boolean)
  2988. (defcustom org-read-date-popup-calendar t
  2989. "Non-nil means pop up a calendar when prompting for a date.
  2990. In the calendar, the date can be selected with mouse-1. However, the
  2991. minibuffer will also be active, and you can simply enter the date as well.
  2992. When nil, only the minibuffer will be available."
  2993. :group 'org-time
  2994. :type 'boolean)
  2995. (defvaralias 'org-popup-calendar-for-date-prompt
  2996. 'org-read-date-popup-calendar)
  2997. (defcustom org-extend-today-until 0
  2998. "The hour when your day really ends. Must be an integer.
  2999. This has influence for the following applications:
  3000. - When switching the agenda to \"today\". It it is still earlier than
  3001. the time given here, the day recognized as TODAY is actually yesterday.
  3002. - When a date is read from the user and it is still before the time given
  3003. here, the current date and time will be assumed to be yesterday, 23:59.
  3004. Also, timestamps inserted in capture templates follow this rule.
  3005. IMPORTANT: This is a feature whose implementation is and likely will
  3006. remain incomplete. Really, it is only here because past midnight seems to
  3007. be the favorite working time of John Wiegley :-)"
  3008. :group 'org-time
  3009. :type 'integer)
  3010. (defcustom org-use-effective-time nil
  3011. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3012. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3013. \"effective time\" of any timestamps between midnight and 8am will be
  3014. 23:59 of the previous day."
  3015. :group 'org-time
  3016. :version "24.1"
  3017. :type 'boolean)
  3018. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3019. "When non-nil, use the last clock out time for `org-todo'.
  3020. Note that this option has precedence over the combined use of
  3021. `org-use-effective-time' and `org-extend-today-until'."
  3022. :group 'org-time
  3023. :version "24.4"
  3024. :package-version '(Org . "8.0")
  3025. :type 'boolean)
  3026. (defcustom org-edit-timestamp-down-means-later nil
  3027. "Non-nil means S-down will increase the time in a time stamp.
  3028. When nil, S-up will increase."
  3029. :group 'org-time
  3030. :type 'boolean)
  3031. (defcustom org-calendar-follow-timestamp-change t
  3032. "Non-nil means make the calendar window follow timestamp changes.
  3033. When a timestamp is modified and the calendar window is visible, it will be
  3034. moved to the new date."
  3035. :group 'org-time
  3036. :type 'boolean)
  3037. (defgroup org-tags nil
  3038. "Options concerning tags in Org mode."
  3039. :tag "Org Tags"
  3040. :group 'org)
  3041. (defcustom org-tag-alist nil
  3042. "Default tags available in Org files.
  3043. The value of this variable is an alist. Associations either:
  3044. (TAG)
  3045. (TAG . SELECT)
  3046. (SPECIAL)
  3047. where TAG is a tag as a string, SELECT is a case-sensitive
  3048. letter, used to select that tag through the fast tag selection
  3049. interface, and SPECIAL is one of the following keywords:
  3050. `:startgroup', `:startgrouptag', `:grouptags', `:engroup',
  3051. `:endgrouptag' or `:newline'. These keywords are used to define
  3052. a hierarchy of tags. See manual for details.
  3053. When this variable is nil, Org mode bases tag input on what is
  3054. already in the buffer. The value can be overridden locally by
  3055. using a TAGS keyword, e.g.,
  3056. #+TAGS: tag1 tag2
  3057. See also `org-tag-persistent-alist' to sidestep this behavior."
  3058. :group 'org-tags
  3059. :type '(repeat
  3060. (choice
  3061. (cons (string :tag "Tag name")
  3062. (character :tag "Access char"))
  3063. (const :tag "Start radio group" (:startgroup))
  3064. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3065. (const :tag "Group tags delimiter" (:grouptags))
  3066. (const :tag "End radio group" (:endgroup))
  3067. (const :tag "End tag group, non distinct" (:endgrouptag))
  3068. (const :tag "New line" (:newline)))))
  3069. (defcustom org-tag-persistent-alist nil
  3070. "Tags always available in Org files.
  3071. The value of this variable is an alist. Associations either:
  3072. (TAG)
  3073. (TAG . SELECT)
  3074. (SPECIAL)
  3075. where TAG is a tag as a string, SELECT is a character, used to
  3076. select that tag through the fast tag selection interface, and
  3077. SPECIAL is one of the following keywords: `:startgroup',
  3078. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3079. `:newline'. These keywords are used to define a hierarchy of
  3080. tags. See manual for details.
  3081. Unlike to `org-tag-alist', tags defined in this variable do not
  3082. depend on a local TAGS keyword. Instead, to disable these tags
  3083. on a per-file basis, insert anywhere in the file:
  3084. #+STARTUP: noptag"
  3085. :group 'org-tags
  3086. :type '(repeat
  3087. (choice
  3088. (cons (string :tag "Tag name")
  3089. (character :tag "Access char"))
  3090. (const :tag "Start radio group" (:startgroup))
  3091. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3092. (const :tag "Group tags delimiter" (:grouptags))
  3093. (const :tag "End radio group" (:endgroup))
  3094. (const :tag "End tag group, non distinct" (:endgrouptag))
  3095. (const :tag "New line" (:newline)))))
  3096. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3097. "If non-nil, always offer completion for all tags of all agenda files.
  3098. Instead of customizing this variable directly, you might want to
  3099. set it locally for capture buffers, because there no list of
  3100. tags in that file can be created dynamically (there are none).
  3101. (add-hook \\='org-capture-mode-hook
  3102. (lambda ()
  3103. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3104. :group 'org-tags
  3105. :version "24.1"
  3106. :type 'boolean)
  3107. (defvar org-file-tags nil
  3108. "List of tags that can be inherited by all entries in the file.
  3109. The tags will be inherited if the variable `org-use-tag-inheritance'
  3110. says they should be.
  3111. This variable is populated from #+FILETAGS lines.")
  3112. (defcustom org-use-fast-tag-selection 'auto
  3113. "Non-nil means use fast tag selection scheme.
  3114. This is a special interface to select and deselect tags with single keys.
  3115. When nil, fast selection is never used.
  3116. When the symbol `auto', fast selection is used if and only if selection
  3117. characters for tags have been configured, either through the variable
  3118. `org-tag-alist' or through a #+TAGS line in the buffer.
  3119. When t, fast selection is always used and selection keys are assigned
  3120. automatically if necessary."
  3121. :group 'org-tags
  3122. :type '(choice
  3123. (const :tag "Always" t)
  3124. (const :tag "Never" nil)
  3125. (const :tag "When selection characters are configured" auto)))
  3126. (defcustom org-fast-tag-selection-single-key nil
  3127. "Non-nil means fast tag selection exits after first change.
  3128. When nil, you have to press RET to exit it.
  3129. During fast tag selection, you can toggle this flag with `C-c'.
  3130. This variable can also have the value `expert'. In this case, the window
  3131. displaying the tags menu is not even shown, until you press C-c again."
  3132. :group 'org-tags
  3133. :type '(choice
  3134. (const :tag "No" nil)
  3135. (const :tag "Yes" t)
  3136. (const :tag "Expert" expert)))
  3137. (defvar org-fast-tag-selection-include-todo nil
  3138. "Non-nil means fast tags selection interface will also offer TODO states.
  3139. This is an undocumented feature, you should not rely on it.")
  3140. (defcustom org-tags-column -77
  3141. "The column to which tags should be indented in a headline.
  3142. If this number is positive, it specifies the column. If it is negative,
  3143. it means that the tags should be flushright to that column. For example,
  3144. -80 works well for a normal 80 character screen.
  3145. When 0, place tags directly after headline text, with only one space in
  3146. between."
  3147. :group 'org-tags
  3148. :type 'integer)
  3149. (defcustom org-auto-align-tags t
  3150. "Non-nil keeps tags aligned when modifying headlines.
  3151. Some operations (i.e. demoting) change the length of a headline and
  3152. therefore shift the tags around. With this option turned on, after
  3153. each such operation the tags are again aligned to `org-tags-column'."
  3154. :group 'org-tags
  3155. :type 'boolean)
  3156. (defcustom org-use-tag-inheritance t
  3157. "Non-nil means tags in levels apply also for sublevels.
  3158. When nil, only the tags directly given in a specific line apply there.
  3159. This may also be a list of tags that should be inherited, or a regexp that
  3160. matches tags that should be inherited. Additional control is possible
  3161. with the variable `org-tags-exclude-from-inheritance' which gives an
  3162. explicit list of tags to be excluded from inheritance, even if the value of
  3163. `org-use-tag-inheritance' would select it for inheritance.
  3164. If this option is t, a match early-on in a tree can lead to a large
  3165. number of matches in the subtree when constructing the agenda or creating
  3166. a sparse tree. If you only want to see the first match in a tree during
  3167. a search, check out the variable `org-tags-match-list-sublevels'."
  3168. :group 'org-tags
  3169. :type '(choice
  3170. (const :tag "Not" nil)
  3171. (const :tag "Always" t)
  3172. (repeat :tag "Specific tags" (string :tag "Tag"))
  3173. (regexp :tag "Tags matched by regexp")))
  3174. (defcustom org-tags-exclude-from-inheritance nil
  3175. "List of tags that should never be inherited.
  3176. This is a way to exclude a few tags from inheritance. For way to do
  3177. the opposite, to actively allow inheritance for selected tags,
  3178. see the variable `org-use-tag-inheritance'."
  3179. :group 'org-tags
  3180. :type '(repeat (string :tag "Tag")))
  3181. (defun org-tag-inherit-p (tag)
  3182. "Check if TAG is one that should be inherited."
  3183. (cond
  3184. ((member tag org-tags-exclude-from-inheritance) nil)
  3185. ((eq org-use-tag-inheritance t) t)
  3186. ((not org-use-tag-inheritance) nil)
  3187. ((stringp org-use-tag-inheritance)
  3188. (string-match org-use-tag-inheritance tag))
  3189. ((listp org-use-tag-inheritance)
  3190. (member tag org-use-tag-inheritance))
  3191. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3192. (defcustom org-tags-match-list-sublevels t
  3193. "Non-nil means list also sublevels of headlines matching a search.
  3194. This variable applies to tags/property searches, and also to stuck
  3195. projects because this search is based on a tags match as well.
  3196. When set to the symbol `indented', sublevels are indented with
  3197. leading dots.
  3198. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3199. the sublevels of a headline matching a tag search often also match
  3200. the same search. Listing all of them can create very long lists.
  3201. Setting this variable to nil causes subtrees of a match to be skipped.
  3202. This variable is semi-obsolete and probably should always be true. It
  3203. is better to limit inheritance to certain tags using the variables
  3204. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3205. :group 'org-tags
  3206. :type '(choice
  3207. (const :tag "No, don't list them" nil)
  3208. (const :tag "Yes, do list them" t)
  3209. (const :tag "List them, indented with leading dots" indented)))
  3210. (defcustom org-tags-sort-function nil
  3211. "When set, tags are sorted using this function as a comparator."
  3212. :group 'org-tags
  3213. :type '(choice
  3214. (const :tag "No sorting" nil)
  3215. (const :tag "Alphabetical" string<)
  3216. (const :tag "Reverse alphabetical" string>)
  3217. (function :tag "Custom function" nil)))
  3218. (defvar org-tags-history nil
  3219. "History of minibuffer reads for tags.")
  3220. (defvar org-last-tags-completion-table nil
  3221. "The last used completion table for tags.")
  3222. (defvar org-after-tags-change-hook nil
  3223. "Hook that is run after the tags in a line have changed.")
  3224. (defgroup org-properties nil
  3225. "Options concerning properties in Org mode."
  3226. :tag "Org Properties"
  3227. :group 'org)
  3228. (defcustom org-property-format "%-10s %s"
  3229. "How property key/value pairs should be formatted by `indent-line'.
  3230. When `indent-line' hits a property definition, it will format the line
  3231. according to this format, mainly to make sure that the values are
  3232. lined-up with respect to each other."
  3233. :group 'org-properties
  3234. :type 'string)
  3235. (defcustom org-properties-postprocess-alist nil
  3236. "Alist of properties and functions to adjust inserted values.
  3237. Elements of this alist must be of the form
  3238. ([string] [function])
  3239. where [string] must be a property name and [function] must be a
  3240. lambda expression: this lambda expression must take one argument,
  3241. the value to adjust, and return the new value as a string.
  3242. For example, this element will allow the property \"Remaining\"
  3243. to be updated wrt the relation between the \"Effort\" property
  3244. and the clock summary:
  3245. ((\"Remaining\" (lambda(value)
  3246. (let ((clocksum (org-clock-sum-current-item))
  3247. (effort (org-duration-string-to-minutes
  3248. (org-entry-get (point) \"Effort\"))))
  3249. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3250. :group 'org-properties
  3251. :version "24.1"
  3252. :type '(alist :key-type (string :tag "Property")
  3253. :value-type (function :tag "Function")))
  3254. (defcustom org-use-property-inheritance nil
  3255. "Non-nil means properties apply also for sublevels.
  3256. This setting is chiefly used during property searches. Turning it on can
  3257. cause significant overhead when doing a search, which is why it is not
  3258. on by default.
  3259. When nil, only the properties directly given in the current entry count.
  3260. When t, every property is inherited. The value may also be a list of
  3261. properties that should have inheritance, or a regular expression matching
  3262. properties that should be inherited.
  3263. However, note that some special properties use inheritance under special
  3264. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3265. and the properties ending in \"_ALL\" when they are used as descriptor
  3266. for valid values of a property.
  3267. Note for programmers:
  3268. When querying an entry with `org-entry-get', you can control if inheritance
  3269. should be used. By default, `org-entry-get' looks only at the local
  3270. properties. You can request inheritance by setting the inherit argument
  3271. to t (to force inheritance) or to `selective' (to respect the setting
  3272. in this variable)."
  3273. :group 'org-properties
  3274. :type '(choice
  3275. (const :tag "Not" nil)
  3276. (const :tag "Always" t)
  3277. (repeat :tag "Specific properties" (string :tag "Property"))
  3278. (regexp :tag "Properties matched by regexp")))
  3279. (defun org-property-inherit-p (property)
  3280. "Check if PROPERTY is one that should be inherited."
  3281. (cond
  3282. ((eq org-use-property-inheritance t) t)
  3283. ((not org-use-property-inheritance) nil)
  3284. ((stringp org-use-property-inheritance)
  3285. (string-match org-use-property-inheritance property))
  3286. ((listp org-use-property-inheritance)
  3287. (member property org-use-property-inheritance))
  3288. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3289. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3290. "The default column format, if no other format has been defined.
  3291. This variable can be set on the per-file basis by inserting a line
  3292. #+COLUMNS: %25ITEM ....."
  3293. :group 'org-properties
  3294. :type 'string)
  3295. (defcustom org-columns-ellipses ".."
  3296. "The ellipses to be used when a field in column view is truncated.
  3297. When this is the empty string, as many characters as possible are shown,
  3298. but then there will be no visual indication that the field has been truncated.
  3299. When this is a string of length N, the last N characters of a truncated
  3300. field are replaced by this string. If the column is narrower than the
  3301. ellipses string, only part of the ellipses string will be shown."
  3302. :group 'org-properties
  3303. :type 'string)
  3304. (defconst org-global-properties-fixed
  3305. '(("VISIBILITY_ALL" . "folded children content all")
  3306. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3307. "List of property/value pairs that can be inherited by any entry.
  3308. These are fixed values, for the preset properties. The user variable
  3309. that can be used to add to this list is `org-global-properties'.
  3310. The entries in this list are cons cells where the car is a property
  3311. name and cdr is a string with the value. If the value represents
  3312. multiple items like an \"_ALL\" property, separate the items by
  3313. spaces.")
  3314. (defcustom org-global-properties nil
  3315. "List of property/value pairs that can be inherited by any entry.
  3316. This list will be combined with the constant `org-global-properties-fixed'.
  3317. The entries in this list are cons cells where the car is a property
  3318. name and cdr is a string with the value.
  3319. You can set buffer-local values for the same purpose in the variable
  3320. `org-file-properties' this by adding lines like
  3321. #+PROPERTY: NAME VALUE"
  3322. :group 'org-properties
  3323. :type '(repeat
  3324. (cons (string :tag "Property")
  3325. (string :tag "Value"))))
  3326. (defvar-local org-file-properties nil
  3327. "List of property/value pairs that can be inherited by any entry.
  3328. Valid for the current buffer.
  3329. This variable is populated from #+PROPERTY lines.")
  3330. (defgroup org-agenda nil
  3331. "Options concerning agenda views in Org mode."
  3332. :tag "Org Agenda"
  3333. :group 'org)
  3334. (defvar-local org-category nil
  3335. "Variable used by org files to set a category for agenda display.
  3336. Such files should use a file variable to set it, for example
  3337. # -*- mode: org; org-category: \"ELisp\"
  3338. or contain a special line
  3339. #+CATEGORY: ELisp
  3340. If the file does not specify a category, then file's base name
  3341. is used instead.")
  3342. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3343. (defcustom org-agenda-files nil
  3344. "The files to be used for agenda display.
  3345. If an entry is a directory, all files in that directory that are matched
  3346. by `org-agenda-file-regexp' will be part of the file list.
  3347. If the value of the variable is not a list but a single file name, then
  3348. the list of agenda files is actually stored and maintained in that file,
  3349. one agenda file per line. In this file paths can be given relative to
  3350. `org-directory'. Tilde expansion and environment variable substitution
  3351. are also made.
  3352. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3353. and removed with `\\[org-remove-file]'."
  3354. :group 'org-agenda
  3355. :type '(choice
  3356. (repeat :tag "List of files and directories" file)
  3357. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3358. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3359. "Regular expression to match files for `org-agenda-files'.
  3360. If any element in the list in that variable contains a directory instead
  3361. of a normal file, all files in that directory that are matched by this
  3362. regular expression will be included."
  3363. :group 'org-agenda
  3364. :type 'regexp)
  3365. (defcustom org-agenda-text-search-extra-files nil
  3366. "List of extra files to be searched by text search commands.
  3367. These files will be searched in addition to the agenda files by the
  3368. commands `org-search-view' (`\\[org-agenda] s') \
  3369. and `org-occur-in-agenda-files'.
  3370. Note that these files will only be searched for text search commands,
  3371. not for the other agenda views like todo lists, tag searches or the weekly
  3372. agenda. This variable is intended to list notes and possibly archive files
  3373. that should also be searched by these two commands.
  3374. In fact, if the first element in the list is the symbol `agenda-archives',
  3375. then all archive files of all agenda files will be added to the search
  3376. scope."
  3377. :group 'org-agenda
  3378. :type '(set :greedy t
  3379. (const :tag "Agenda Archives" agenda-archives)
  3380. (repeat :inline t (file))))
  3381. (defvaralias 'org-agenda-multi-occur-extra-files
  3382. 'org-agenda-text-search-extra-files)
  3383. (defcustom org-agenda-skip-unavailable-files nil
  3384. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3385. A nil value means to remove them, after a query, from the list."
  3386. :group 'org-agenda
  3387. :type 'boolean)
  3388. (defcustom org-calendar-to-agenda-key [?c]
  3389. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3390. The command `org-calendar-goto-agenda' will be bound to this key. The
  3391. default is the character `c' because then `c' can be used to switch back and
  3392. forth between agenda and calendar."
  3393. :group 'org-agenda
  3394. :type 'sexp)
  3395. (defcustom org-calendar-insert-diary-entry-key [?i]
  3396. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3397. This option is irrelevant until `org-agenda-diary-file' has been configured
  3398. to point to an Org file. When that is the case, the command
  3399. `org-agenda-diary-entry' will be bound to the key given here, by default
  3400. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3401. if you want to continue doing this, you need to change this to a different
  3402. key."
  3403. :group 'org-agenda
  3404. :type 'sexp)
  3405. (defcustom org-agenda-diary-file 'diary-file
  3406. "File to which to add new entries with the `i' key in agenda and calendar.
  3407. When this is the symbol `diary-file', the functionality in the Emacs
  3408. calendar will be used to add entries to the `diary-file'. But when this
  3409. points to a file, `org-agenda-diary-entry' will be used instead."
  3410. :group 'org-agenda
  3411. :type '(choice
  3412. (const :tag "The standard Emacs diary file" diary-file)
  3413. (file :tag "Special Org file diary entries")))
  3414. (eval-after-load "calendar"
  3415. '(progn
  3416. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3417. 'org-calendar-goto-agenda)
  3418. (add-hook 'calendar-mode-hook
  3419. (lambda ()
  3420. (unless (eq org-agenda-diary-file 'diary-file)
  3421. (define-key calendar-mode-map
  3422. org-calendar-insert-diary-entry-key
  3423. 'org-agenda-diary-entry))))))
  3424. (defgroup org-latex nil
  3425. "Options for embedding LaTeX code into Org mode."
  3426. :tag "Org LaTeX"
  3427. :group 'org)
  3428. (defcustom org-format-latex-options
  3429. '(:foreground default :background default :scale 1.0
  3430. :html-foreground "Black" :html-background "Transparent"
  3431. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3432. "Options for creating images from LaTeX fragments.
  3433. This is a property list with the following properties:
  3434. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3435. `default' means use the foreground of the default face.
  3436. `auto' means use the foreground from the text face.
  3437. :background the background color, or \"Transparent\".
  3438. `default' means use the background of the default face.
  3439. `auto' means use the background from the text face.
  3440. :scale a scaling factor for the size of the images, to get more pixels
  3441. :html-foreground, :html-background, :html-scale
  3442. the same numbers for HTML export.
  3443. :matchers a list indicating which matchers should be used to
  3444. find LaTeX fragments. Valid members of this list are:
  3445. \"begin\" find environments
  3446. \"$1\" find single characters surrounded by $.$
  3447. \"$\" find math expressions surrounded by $...$
  3448. \"$$\" find math expressions surrounded by $$....$$
  3449. \"\\(\" find math expressions surrounded by \\(...\\)
  3450. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3451. :group 'org-latex
  3452. :type 'plist)
  3453. (defcustom org-format-latex-signal-error t
  3454. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3455. When nil, just push out a message."
  3456. :group 'org-latex
  3457. :version "24.1"
  3458. :type 'boolean)
  3459. (defcustom org-latex-to-mathml-jar-file nil
  3460. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3461. Use this to specify additional executable file say a jar file.
  3462. When using MathToWeb as the converter, specify the full-path to
  3463. your mathtoweb.jar file."
  3464. :group 'org-latex
  3465. :version "24.1"
  3466. :type '(choice
  3467. (const :tag "None" nil)
  3468. (file :tag "JAR file" :must-match t)))
  3469. (defcustom org-latex-to-mathml-convert-command nil
  3470. "Command to convert LaTeX fragments to MathML.
  3471. Replace format-specifiers in the command as noted below and use
  3472. `shell-command' to convert LaTeX to MathML.
  3473. %j: Executable file in fully expanded form as specified by
  3474. `org-latex-to-mathml-jar-file'.
  3475. %I: Input LaTeX file in fully expanded form.
  3476. %i: The latex fragment to be converted.
  3477. %o: Output MathML file.
  3478. This command is used by `org-create-math-formula'.
  3479. When using MathToWeb as the converter, set this option to
  3480. \"java -jar %j -unicode -force -df %o %I\".
  3481. When using LaTeXML set this option to
  3482. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3483. :group 'org-latex
  3484. :version "24.1"
  3485. :type '(choice
  3486. (const :tag "None" nil)
  3487. (string :tag "\nShell command")))
  3488. (defcustom org-preview-latex-default-process 'dvipng
  3489. "The default process to convert LaTeX fragments to image files.
  3490. All available processes and theirs documents can be found in
  3491. `org-preview-latex-process-alist', which see."
  3492. :group 'org-latex
  3493. :version "25.2"
  3494. :package-version '(Org . "9.0")
  3495. :type 'symbol)
  3496. (defcustom org-preview-latex-process-alist
  3497. '((dvipng
  3498. :programs ("latex" "dvipng" "gs")
  3499. :description "dvi > png"
  3500. :message "you need to install the programs: latex, dvipng and ghostscript."
  3501. :image-input-type "dvi"
  3502. :image-output-type "png"
  3503. :image-size-adjust (1.0 . 1.0)
  3504. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3505. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
  3506. (dvisvgm
  3507. :programs ("latex" "dvisvgm" "gs")
  3508. :description "dvi > svg"
  3509. :message "you need to install the programs: latex, dvisvgm and ghostscript."
  3510. :use-xcolor t
  3511. :image-input-type "dvi"
  3512. :image-output-type "svg"
  3513. :image-size-adjust (1.7 . 1.5)
  3514. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3515. :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
  3516. (imagemagick
  3517. :programs ("latex" "convert" "gs")
  3518. :description "pdf > png"
  3519. :message
  3520. "you need to install the programs: latex, imagemagick and ghostscript."
  3521. :use-xcolor t
  3522. :image-input-type "pdf"
  3523. :image-output-type "png"
  3524. :image-size-adjust (1.0 . 1.0)
  3525. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3526. :image-converter
  3527. ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
  3528. "Definitions of external processes for LaTeX previewing.
  3529. Org mode can use some external commands to generate TeX snippet's images for
  3530. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3531. `org-create-formula-image' how to call them.
  3532. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3533. PROPERTIES accepts the following attributes:
  3534. :programs list of strings, required programs.
  3535. :description string, describe the process.
  3536. :message string, message it when required programs cannot be found.
  3537. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3538. :image-output-type string, output file type of image converter (e.g., \"png\").
  3539. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3540. deal with background and foreground color of image.
  3541. Otherwise, dvipng style background and foregroud color
  3542. format are generated. You may then refer to them in
  3543. command options with \"%F\" and \"%B\".
  3544. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3545. image size showed in buffer and the cdr element is for
  3546. HTML file. This option is only useful for process
  3547. developers, users should use variable
  3548. `org-format-latex-options' instead.
  3549. :post-clean list of strings, files matched are to be cleaned up once
  3550. the image is generated. When nil, the files with \".dvi\",
  3551. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3552. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3553. be cleaned up.
  3554. :latex-header list of strings, the LaTeX header of the snippet file.
  3555. When nil, the fallback value is used instead, which is
  3556. controlled by `org-format-latex-header',
  3557. `org-latex-default-packages-alist' and
  3558. `org-latex-packages-alist', which see.
  3559. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3560. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3561. replaced with values defined below.
  3562. :image-converter list of image converter commands strings. Each of them is
  3563. given to the shell and supports any of the following
  3564. place-holders defined below.
  3565. Place-holders used by `:image-converter' and `:latex-compiler':
  3566. %f input file name.
  3567. %b base name of input file.
  3568. %o base directory of input file.
  3569. Place-holders only used by `:image-converter':
  3570. %F foreground of image
  3571. %B background of image
  3572. %D dpi, which is used to adjust image size by some processing commands.
  3573. %S the image size scale ratio, which is used to adjust image size by some
  3574. processing commands."
  3575. :group 'org-latex
  3576. :version "25.2"
  3577. :package-version '(Org . "9.0")
  3578. :type '(alist :tag "LaTeX to image backends"
  3579. :value-type (plist)))
  3580. (defcustom org-preview-latex-image-directory "ltximg/"
  3581. "Path to store latex preview images.
  3582. A relative path here creates many directories relative to the
  3583. processed org files paths. An absolute path puts all preview
  3584. images at the same place."
  3585. :group 'org-latex
  3586. :version "25.2"
  3587. :package-version '(Org . "9.0")
  3588. :type 'string)
  3589. (defun org-format-latex-mathml-available-p ()
  3590. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3591. (save-match-data
  3592. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3593. org-latex-to-mathml-convert-command)
  3594. (let ((executable (car (split-string
  3595. org-latex-to-mathml-convert-command))))
  3596. (when (executable-find executable)
  3597. (if (string-match
  3598. "%j" org-latex-to-mathml-convert-command)
  3599. (file-readable-p org-latex-to-mathml-jar-file)
  3600. t))))))
  3601. (defcustom org-format-latex-header "\\documentclass{article}
  3602. \\usepackage[usenames]{color}
  3603. \[PACKAGES]
  3604. \[DEFAULT-PACKAGES]
  3605. \\pagestyle{empty} % do not remove
  3606. % The settings below are copied from fullpage.sty
  3607. \\setlength{\\textwidth}{\\paperwidth}
  3608. \\addtolength{\\textwidth}{-3cm}
  3609. \\setlength{\\oddsidemargin}{1.5cm}
  3610. \\addtolength{\\oddsidemargin}{-2.54cm}
  3611. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3612. \\setlength{\\textheight}{\\paperheight}
  3613. \\addtolength{\\textheight}{-\\headheight}
  3614. \\addtolength{\\textheight}{-\\headsep}
  3615. \\addtolength{\\textheight}{-\\footskip}
  3616. \\addtolength{\\textheight}{-3cm}
  3617. \\setlength{\\topmargin}{1.5cm}
  3618. \\addtolength{\\topmargin}{-2.54cm}"
  3619. "The document header used for processing LaTeX fragments.
  3620. It is imperative that this header make sure that no page number
  3621. appears on the page. The package defined in the variables
  3622. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3623. will either replace the placeholder \"[PACKAGES]\" in this
  3624. header, or they will be appended."
  3625. :group 'org-latex
  3626. :type 'string)
  3627. (defun org-set-packages-alist (var val)
  3628. "Set the packages alist and make sure it has 3 elements per entry."
  3629. (set var (mapcar (lambda (x)
  3630. (if (and (consp x) (= (length x) 2))
  3631. (list (car x) (nth 1 x) t)
  3632. x))
  3633. val)))
  3634. (defun org-get-packages-alist (var)
  3635. "Get the packages alist and make sure it has 3 elements per entry."
  3636. (mapcar (lambda (x)
  3637. (if (and (consp x) (= (length x) 2))
  3638. (list (car x) (nth 1 x) t)
  3639. x))
  3640. (default-value var)))
  3641. (defcustom org-latex-default-packages-alist
  3642. '(("AUTO" "inputenc" t ("pdflatex"))
  3643. ("T1" "fontenc" t ("pdflatex"))
  3644. ("" "graphicx" t)
  3645. ("" "grffile" t)
  3646. ("" "longtable" nil)
  3647. ("" "wrapfig" nil)
  3648. ("" "rotating" nil)
  3649. ("normalem" "ulem" t)
  3650. ("" "amsmath" t)
  3651. ("" "textcomp" t)
  3652. ("" "amssymb" t)
  3653. ("" "capt-of" nil)
  3654. ("" "hyperref" nil))
  3655. "Alist of default packages to be inserted in the header.
  3656. Change this only if one of the packages here causes an
  3657. incompatibility with another package you are using.
  3658. The packages in this list are needed by one part or another of
  3659. Org mode to function properly:
  3660. - inputenc, fontenc: for basic font and character selection
  3661. - graphicx: for including images
  3662. - grffile: allow periods and spaces in graphics file names
  3663. - longtable: For multipage tables
  3664. - wrapfig: for figure placement
  3665. - rotating: for sideways figures and tables
  3666. - ulem: for underline and strike-through
  3667. - amsmath: for subscript and superscript and math environments
  3668. - textcomp, amssymb: for various symbols used
  3669. for interpreting the entities in `org-entities'. You can skip
  3670. some of these packages if you don't use any of their symbols.
  3671. - capt-of: for captions outside of floats
  3672. - hyperref: for cross references
  3673. Therefore you should not modify this variable unless you know
  3674. what you are doing. The one reason to change it anyway is that
  3675. you might be loading some other package that conflicts with one
  3676. of the default packages. Each element is either a cell or
  3677. a string.
  3678. A cell is of the format
  3679. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3680. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3681. when compiling LaTeX snippets into images for inclusion into
  3682. non-LaTeX output. COMPILERS is a list of compilers that should
  3683. include the package, see `org-latex-compiler'. If the document
  3684. compiler is not in the list, and the list is non-nil, the package
  3685. will not be inserted in the final document.
  3686. A string will be inserted as-is in the header of the document."
  3687. :group 'org-latex
  3688. :group 'org-export-latex
  3689. :set 'org-set-packages-alist
  3690. :get 'org-get-packages-alist
  3691. :version "25.2"
  3692. :package-version '(Org . "8.3")
  3693. :type '(repeat
  3694. (choice
  3695. (list :tag "options/package pair"
  3696. (string :tag "options")
  3697. (string :tag "package")
  3698. (boolean :tag "Snippet"))
  3699. (string :tag "A line of LaTeX"))))
  3700. (defcustom org-latex-packages-alist nil
  3701. "Alist of packages to be inserted in every LaTeX header.
  3702. These will be inserted after `org-latex-default-packages-alist'.
  3703. Each element is either a cell or a string.
  3704. A cell is of the format:
  3705. (\"options\" \"package\" SNIPPET-FLAG)
  3706. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3707. needed when turning LaTeX snippets into images for inclusion into
  3708. non-LaTeX output.
  3709. A string will be inserted as-is in the header of the document.
  3710. Make sure that you only list packages here which:
  3711. - you want in every file;
  3712. - do not conflict with the setup in `org-format-latex-header';
  3713. - do not conflict with the default packages in
  3714. `org-latex-default-packages-alist'."
  3715. :group 'org-latex
  3716. :group 'org-export-latex
  3717. :set 'org-set-packages-alist
  3718. :get 'org-get-packages-alist
  3719. :type '(repeat
  3720. (choice
  3721. (list :tag "options/package pair"
  3722. (string :tag "options")
  3723. (string :tag "package")
  3724. (boolean :tag "Snippet"))
  3725. (string :tag "A line of LaTeX"))))
  3726. (defgroup org-appearance nil
  3727. "Settings for Org mode appearance."
  3728. :tag "Org Appearance"
  3729. :group 'org)
  3730. (defcustom org-level-color-stars-only nil
  3731. "Non-nil means fontify only the stars in each headline.
  3732. When nil, the entire headline is fontified.
  3733. Changing it requires restart of `font-lock-mode' to become effective
  3734. also in regions already fontified."
  3735. :group 'org-appearance
  3736. :type 'boolean)
  3737. (defcustom org-hide-leading-stars nil
  3738. "Non-nil means hide the first N-1 stars in a headline.
  3739. This works by using the face `org-hide' for these stars. This
  3740. face is white for a light background, and black for a dark
  3741. background. You may have to customize the face `org-hide' to
  3742. make this work.
  3743. Changing it requires restart of `font-lock-mode' to become effective
  3744. also in regions already fontified.
  3745. You may also set this on a per-file basis by adding one of the following
  3746. lines to the buffer:
  3747. #+STARTUP: hidestars
  3748. #+STARTUP: showstars"
  3749. :group 'org-appearance
  3750. :type 'boolean)
  3751. (defcustom org-hidden-keywords nil
  3752. "List of symbols corresponding to keywords to be hidden the org buffer.
  3753. For example, a value \\='(title) for this list will make the document's title
  3754. appear in the buffer without the initial #+TITLE: keyword."
  3755. :group 'org-appearance
  3756. :version "24.1"
  3757. :type '(set (const :tag "#+AUTHOR" author)
  3758. (const :tag "#+DATE" date)
  3759. (const :tag "#+EMAIL" email)
  3760. (const :tag "#+TITLE" title)))
  3761. (defcustom org-custom-properties nil
  3762. "List of properties (as strings) with a special meaning.
  3763. The default use of these custom properties is to let the user
  3764. hide them with `org-toggle-custom-properties-visibility'."
  3765. :group 'org-properties
  3766. :group 'org-appearance
  3767. :version "24.3"
  3768. :type '(repeat (string :tag "Property Name")))
  3769. (defcustom org-fontify-done-headline nil
  3770. "Non-nil means change the face of a headline if it is marked DONE.
  3771. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3772. When this is non-nil, the headline after the keyword is set to the
  3773. `org-headline-done' as an additional indication."
  3774. :group 'org-appearance
  3775. :type 'boolean)
  3776. (defcustom org-fontify-emphasized-text t
  3777. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3778. Changing this variable requires a restart of Emacs to take effect."
  3779. :group 'org-appearance
  3780. :type 'boolean)
  3781. (defcustom org-fontify-whole-heading-line nil
  3782. "Non-nil means fontify the whole line for headings.
  3783. This is useful when setting a background color for the
  3784. org-level-* faces."
  3785. :group 'org-appearance
  3786. :type 'boolean)
  3787. (defcustom org-highlight-latex-and-related nil
  3788. "Non-nil means highlight LaTeX related syntax in the buffer.
  3789. When non nil, the value should be a list containing any of the
  3790. following symbols:
  3791. `latex' Highlight LaTeX snippets and environments.
  3792. `script' Highlight subscript and superscript.
  3793. `entities' Highlight entities."
  3794. :group 'org-appearance
  3795. :version "24.4"
  3796. :package-version '(Org . "8.0")
  3797. :type '(choice
  3798. (const :tag "No highlighting" nil)
  3799. (set :greedy t :tag "Highlight"
  3800. (const :tag "LaTeX snippets and environments" latex)
  3801. (const :tag "Subscript and superscript" script)
  3802. (const :tag "Entities" entities))))
  3803. (defcustom org-hide-emphasis-markers nil
  3804. "Non-nil mean font-lock should hide the emphasis marker characters."
  3805. :group 'org-appearance
  3806. :type 'boolean)
  3807. (defcustom org-hide-macro-markers nil
  3808. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3809. :group 'org-appearance
  3810. :type 'boolean)
  3811. (defcustom org-pretty-entities nil
  3812. "Non-nil means show entities as UTF8 characters.
  3813. When nil, the \\name form remains in the buffer."
  3814. :group 'org-appearance
  3815. :version "24.1"
  3816. :type 'boolean)
  3817. (defcustom org-pretty-entities-include-sub-superscripts t
  3818. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3819. :group 'org-appearance
  3820. :version "24.1"
  3821. :type 'boolean)
  3822. (defvar org-emph-re nil
  3823. "Regular expression for matching emphasis.
  3824. After a match, the match groups contain these elements:
  3825. 0 The match of the full regular expression, including the characters
  3826. before and after the proper match
  3827. 1 The character before the proper match, or empty at beginning of line
  3828. 2 The proper match, including the leading and trailing markers
  3829. 3 The leading marker like * or /, indicating the type of highlighting
  3830. 4 The text between the emphasis markers, not including the markers
  3831. 5 The character after the match, empty at the end of a line")
  3832. (defvar org-verbatim-re nil
  3833. "Regular expression for matching verbatim text.")
  3834. (defvar org-emphasis-regexp-components) ; defined just below
  3835. (defvar org-emphasis-alist) ; defined just below
  3836. (defun org-set-emph-re (var val)
  3837. "Set variable and compute the emphasis regular expression."
  3838. (set var val)
  3839. (when (and (boundp 'org-emphasis-alist)
  3840. (boundp 'org-emphasis-regexp-components)
  3841. org-emphasis-alist org-emphasis-regexp-components)
  3842. (let* ((e org-emphasis-regexp-components)
  3843. (pre (car e))
  3844. (post (nth 1 e))
  3845. (border (nth 2 e))
  3846. (body (nth 3 e))
  3847. (nl (nth 4 e))
  3848. (body1 (concat body "*?"))
  3849. (markers (mapconcat 'car org-emphasis-alist ""))
  3850. (vmarkers (mapconcat
  3851. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3852. org-emphasis-alist "")))
  3853. ;; make sure special characters appear at the right position in the class
  3854. (if (string-match "\\^" markers)
  3855. (setq markers (concat (replace-match "" t t markers) "^")))
  3856. (if (string-match "-" markers)
  3857. (setq markers (concat (replace-match "" t t markers) "-")))
  3858. (if (string-match "\\^" vmarkers)
  3859. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3860. (if (string-match "-" vmarkers)
  3861. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3862. (if (> nl 0)
  3863. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3864. (int-to-string nl) "\\}")))
  3865. ;; Make the regexp
  3866. (setq org-emph-re
  3867. (concat "\\([" pre "]\\|^\\)"
  3868. "\\("
  3869. "\\([" markers "]\\)"
  3870. "\\("
  3871. "[^" border "]\\|"
  3872. "[^" border "]"
  3873. body1
  3874. "[^" border "]"
  3875. "\\)"
  3876. "\\3\\)"
  3877. "\\([" post "]\\|$\\)"))
  3878. (setq org-verbatim-re
  3879. (concat "\\([" pre "]\\|^\\)"
  3880. "\\("
  3881. "\\([" vmarkers "]\\)"
  3882. "\\("
  3883. "[^" border "]\\|"
  3884. "[^" border "]"
  3885. body1
  3886. "[^" border "]"
  3887. "\\)"
  3888. "\\3\\)"
  3889. "\\([" post "]\\|$\\)")))))
  3890. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3891. ;; set this option proved cumbersome. See this message/thread:
  3892. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3893. (defvar org-emphasis-regexp-components
  3894. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3895. "Components used to build the regular expression for emphasis.
  3896. This is a list with five entries. Terminology: In an emphasis string
  3897. like \" *strong word* \", we call the initial space PREMATCH, the final
  3898. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3899. and \"trong wor\" is the body. The different components in this variable
  3900. specify what is allowed/forbidden in each part:
  3901. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3902. post Chars allowed as postmatch. End of line will be allowed too.
  3903. border The chars *forbidden* as border characters.
  3904. body-regexp A regexp like \".\" to match a body character. Don't use
  3905. non-shy groups here, and don't allow newline here.
  3906. newline The maximum number of newlines allowed in an emphasis exp.
  3907. You need to reload Org or to restart Emacs after customizing this.")
  3908. (defcustom org-emphasis-alist
  3909. '(("*" bold)
  3910. ("/" italic)
  3911. ("_" underline)
  3912. ("=" org-verbatim verbatim)
  3913. ("~" org-code verbatim)
  3914. ("+" (:strike-through t)))
  3915. "Alist of characters and faces to emphasize text.
  3916. Text starting and ending with a special character will be emphasized,
  3917. for example *bold*, _underlined_ and /italic/. This variable sets the
  3918. marker characters and the face to be used by font-lock for highlighting
  3919. in Org buffers.
  3920. You need to reload Org or to restart Emacs after customizing this."
  3921. :group 'org-appearance
  3922. :set 'org-set-emph-re
  3923. :version "24.4"
  3924. :package-version '(Org . "8.0")
  3925. :type '(repeat
  3926. (list
  3927. (string :tag "Marker character")
  3928. (choice
  3929. (face :tag "Font-lock-face")
  3930. (plist :tag "Face property list"))
  3931. (option (const verbatim)))))
  3932. (defvar org-protecting-blocks '("src" "example" "export")
  3933. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3934. This is needed for font-lock setup.")
  3935. ;;; Functions and variables from their packages
  3936. ;; Declared here to avoid compiler warnings
  3937. (defvar mark-active)
  3938. ;; Various packages
  3939. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3940. (declare-function calendar-forward-day "cal-move" (arg))
  3941. (declare-function calendar-goto-date "cal-move" (date))
  3942. (declare-function calendar-goto-today "cal-move" ())
  3943. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3944. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3945. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3946. (declare-function cdlatex-tab "ext:cdlatex" ())
  3947. (declare-function dired-get-filename
  3948. "dired"
  3949. (&optional localp no-error-if-not-filep))
  3950. (declare-function iswitchb-read-buffer
  3951. "iswitchb"
  3952. (prompt &optional
  3953. default require-match _predicate start matches-set))
  3954. (declare-function org-agenda-change-all-lines
  3955. "org-agenda"
  3956. (newhead hdmarker &optional fixface just-this))
  3957. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3958. "org-agenda"
  3959. (&optional end))
  3960. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3961. (declare-function org-agenda-format-item
  3962. "org-agenda"
  3963. (extra txt &optional level category tags dotime
  3964. remove-re habitp))
  3965. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3966. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3967. (declare-function org-agenda-save-markers-for-cut-and-paste
  3968. "org-agenda"
  3969. (beg end))
  3970. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3971. (declare-function org-agenda-skip "org-agenda" ())
  3972. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3973. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3974. (declare-function org-indent-mode "org-indent" (&optional arg))
  3975. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3976. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3977. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3978. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3979. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3980. (declare-function parse-time-string "parse-time" (string))
  3981. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3982. (defvar align-mode-rules-list)
  3983. (defvar calc-embedded-close-formula)
  3984. (defvar calc-embedded-open-formula)
  3985. (defvar calc-embedded-open-mode)
  3986. (defvar font-lock-unfontify-region-function)
  3987. (defvar iswitchb-temp-buflist)
  3988. (defvar org-agenda-tags-todo-honor-ignore-options)
  3989. (defvar remember-data-file)
  3990. (defvar texmathp-why)
  3991. ;;;###autoload
  3992. (defun turn-on-orgtbl ()
  3993. "Unconditionally turn on `orgtbl-mode'."
  3994. (require 'org-table)
  3995. (orgtbl-mode 1))
  3996. (defun org-at-table-p (&optional table-type)
  3997. "Non-nil if the cursor is inside an Org table.
  3998. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3999. If `org-enable-table-editor' is nil, return nil unconditionally."
  4000. (and
  4001. org-enable-table-editor
  4002. (save-excursion
  4003. (beginning-of-line)
  4004. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  4005. (or (not (derived-mode-p 'org-mode))
  4006. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  4007. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  4008. (defun org-at-table.el-p ()
  4009. "Non-nil when point is at a table.el table."
  4010. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4011. (let ((element (org-element-at-point)))
  4012. (and (eq (org-element-type element) 'table)
  4013. (eq (org-element-property :type element) 'table.el)))))
  4014. (defun org-at-table-hline-p ()
  4015. "Non-nil when point is inside a hline in a table.
  4016. Assume point is already in a table. If `org-enable-table-editor'
  4017. is nil, return nil unconditionally."
  4018. (and org-enable-table-editor
  4019. (save-excursion
  4020. (beginning-of-line)
  4021. (looking-at org-table-hline-regexp))))
  4022. (defun org-table-map-tables (function &optional quietly)
  4023. "Apply FUNCTION to the start of all tables in the buffer."
  4024. (org-with-wide-buffer
  4025. (goto-char (point-min))
  4026. (while (re-search-forward org-table-any-line-regexp nil t)
  4027. (unless quietly
  4028. (message "Mapping tables: %d%%"
  4029. (floor (* 100.0 (point)) (buffer-size))))
  4030. (beginning-of-line 1)
  4031. (when (and (looking-at org-table-line-regexp)
  4032. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4033. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4034. (save-excursion (funcall function))
  4035. (or (looking-at org-table-line-regexp)
  4036. (forward-char 1)))
  4037. (re-search-forward org-table-any-border-regexp nil 1)))
  4038. (unless quietly (message "Mapping tables: done")))
  4039. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4040. (declare-function org-clock-update-mode-line "org-clock" ())
  4041. (declare-function org-resolve-clocks "org-clock"
  4042. (&optional also-non-dangling-p prompt last-valid))
  4043. (defun org-at-TBLFM-p (&optional pos)
  4044. "Non-nil when point (or POS) is in #+TBLFM line."
  4045. (save-excursion
  4046. (goto-char (or pos (point)))
  4047. (beginning-of-line)
  4048. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4049. (eq (org-element-type (org-element-at-point)) 'table))))
  4050. (defvar org-clock-start-time)
  4051. (defvar org-clock-marker (make-marker)
  4052. "Marker recording the last clock-in.")
  4053. (defvar org-clock-hd-marker (make-marker)
  4054. "Marker recording the last clock-in, but the headline position.")
  4055. (defvar org-clock-heading ""
  4056. "The heading of the current clock entry.")
  4057. (defun org-clock-is-active ()
  4058. "Return the buffer where the clock is currently running.
  4059. Return nil if no clock is running."
  4060. (marker-buffer org-clock-marker))
  4061. (defun org-check-running-clock ()
  4062. "Check if the current buffer contains the running clock.
  4063. If yes, offer to stop it and to save the buffer with the changes."
  4064. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4065. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4066. (buffer-name))))
  4067. (org-clock-out)
  4068. (when (y-or-n-p "Save changed buffer?")
  4069. (save-buffer))))
  4070. (defun org-clocktable-try-shift (dir n)
  4071. "Check if this line starts a clock table, if yes, shift the time block."
  4072. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4073. (org-clocktable-shift dir n)))
  4074. ;;;###autoload
  4075. (defun org-clock-persistence-insinuate ()
  4076. "Set up hooks for clock persistence."
  4077. (require 'org-clock)
  4078. (add-hook 'org-mode-hook 'org-clock-load)
  4079. (add-hook 'kill-emacs-hook 'org-clock-save))
  4080. (defgroup org-archive nil
  4081. "Options concerning archiving in Org mode."
  4082. :tag "Org Archive"
  4083. :group 'org-structure)
  4084. (defcustom org-archive-location "%s_archive::"
  4085. "The location where subtrees should be archived.
  4086. The value of this variable is a string, consisting of two parts,
  4087. separated by a double-colon. The first part is a filename and
  4088. the second part is a headline.
  4089. When the filename is omitted, archiving happens in the same file.
  4090. %s in the filename will be replaced by the current file
  4091. name (without the directory part). Archiving to a different file
  4092. is useful to keep archived entries from contributing to the
  4093. Org Agenda.
  4094. The archived entries will be filed as subtrees of the specified
  4095. headline. When the headline is omitted, the subtrees are simply
  4096. filed away at the end of the file, as top-level entries. Also in
  4097. the heading you can use %s to represent the file name, this can be
  4098. useful when using the same archive for a number of different files.
  4099. Here are a few examples:
  4100. \"%s_archive::\"
  4101. If the current file is Projects.org, archive in file
  4102. Projects.org_archive, as top-level trees. This is the default.
  4103. \"::* Archived Tasks\"
  4104. Archive in the current file, under the top-level headline
  4105. \"* Archived Tasks\".
  4106. \"~/org/archive.org::\"
  4107. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4108. \"~/org/archive.org::* From %s\"
  4109. Archive in file ~/org/archive.org (absolute path), under headlines
  4110. \"From FILENAME\" where file name is the current file name.
  4111. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4112. The \"datetree/\" string is special, signifying to archive
  4113. items to the datetree. Items are placed in either the CLOSED
  4114. date of the item, or the current date if there is no CLOSED date.
  4115. The heading will be a subentry to the current date. There doesn't
  4116. need to be a heading, but there always needs to be a slash after
  4117. datetree. For example, to store archived items directly in the
  4118. datetree, use \"~/org/datetree.org::datetree/\".
  4119. \"basement::** Finished Tasks\"
  4120. Archive in file ./basement (relative path), as level 3 trees
  4121. below the level 2 heading \"** Finished Tasks\".
  4122. You may set this option on a per-file basis by adding to the buffer a
  4123. line like
  4124. #+ARCHIVE: basement::** Finished Tasks
  4125. You may also define it locally for a subtree by setting an ARCHIVE property
  4126. in the entry. If such a property is found in an entry, or anywhere up
  4127. the hierarchy, it will be used."
  4128. :group 'org-archive
  4129. :type 'string)
  4130. (defcustom org-agenda-skip-archived-trees t
  4131. "Non-nil means the agenda will skip any items located in archived trees.
  4132. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4133. variable is no longer recommended, you should leave it at the value t.
  4134. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4135. :group 'org-archive
  4136. :group 'org-agenda-skip
  4137. :type 'boolean)
  4138. (defcustom org-columns-skip-archived-trees t
  4139. "Non-nil means ignore archived trees when creating column view."
  4140. :group 'org-archive
  4141. :group 'org-properties
  4142. :type 'boolean)
  4143. (defcustom org-cycle-open-archived-trees nil
  4144. "Non-nil means `org-cycle' will open archived trees.
  4145. An archived tree is a tree marked with the tag ARCHIVE.
  4146. When nil, archived trees will stay folded. You can still open them with
  4147. normal outline commands like `show-all', but not with the cycling commands."
  4148. :group 'org-archive
  4149. :group 'org-cycle
  4150. :type 'boolean)
  4151. (defcustom org-sparse-tree-open-archived-trees nil
  4152. "Non-nil means sparse tree construction shows matches in archived trees.
  4153. When nil, matches in these trees are highlighted, but the trees are kept in
  4154. collapsed state."
  4155. :group 'org-archive
  4156. :group 'org-sparse-trees
  4157. :type 'boolean)
  4158. (defcustom org-sparse-tree-default-date-type nil
  4159. "The default date type when building a sparse tree.
  4160. When this is nil, a date is a scheduled or a deadline timestamp.
  4161. Otherwise, these types are allowed:
  4162. all: all timestamps
  4163. active: only active timestamps (<...>)
  4164. inactive: only inactive timestamps ([...])
  4165. scheduled: only scheduled timestamps
  4166. deadline: only deadline timestamps"
  4167. :type '(choice (const :tag "Scheduled or deadline" nil)
  4168. (const :tag "All timestamps" all)
  4169. (const :tag "Only active timestamps" active)
  4170. (const :tag "Only inactive timestamps" inactive)
  4171. (const :tag "Only scheduled timestamps" scheduled)
  4172. (const :tag "Only deadline timestamps" deadline)
  4173. (const :tag "Only closed timestamps" closed))
  4174. :version "25.2"
  4175. :package-version '(Org . "8.3")
  4176. :group 'org-sparse-trees)
  4177. (defun org-cycle-hide-archived-subtrees (state)
  4178. "Re-hide all archived subtrees after a visibility state change."
  4179. (when (and (not org-cycle-open-archived-trees)
  4180. (not (memq state '(overview folded))))
  4181. (save-excursion
  4182. (let* ((globalp (memq state '(contents all)))
  4183. (beg (if globalp (point-min) (point)))
  4184. (end (if globalp (point-max) (org-end-of-subtree t))))
  4185. (org-hide-archived-subtrees beg end)
  4186. (goto-char beg)
  4187. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4188. (message "%s" (substitute-command-keys
  4189. "Subtree is archived and stays closed. Use \
  4190. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4191. (defun org-force-cycle-archived ()
  4192. "Cycle subtree even if it is archived."
  4193. (interactive)
  4194. (setq this-command 'org-cycle)
  4195. (let ((org-cycle-open-archived-trees t))
  4196. (call-interactively 'org-cycle)))
  4197. (defun org-hide-archived-subtrees (beg end)
  4198. "Re-hide all archived subtrees after a visibility state change."
  4199. (org-with-wide-buffer
  4200. (let ((case-fold-search nil)
  4201. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4202. (goto-char beg)
  4203. ;; Include headline point is currently on.
  4204. (beginning-of-line)
  4205. (while (and (< (point) end) (re-search-forward re end t))
  4206. (when (member org-archive-tag (org-get-tags))
  4207. (org-flag-subtree t)
  4208. (org-end-of-subtree t))))))
  4209. (declare-function outline-end-of-heading "outline" ())
  4210. (declare-function outline-flag-region "outline" (from to flag))
  4211. (defun org-flag-subtree (flag)
  4212. (save-excursion
  4213. (org-back-to-heading t)
  4214. (outline-end-of-heading)
  4215. (outline-flag-region (point)
  4216. (progn (org-end-of-subtree t) (point))
  4217. flag)))
  4218. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4219. ;; Declare Column View Code
  4220. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4221. (declare-function org-columns-compute "org-colview" (property))
  4222. ;; Declare ID code
  4223. (declare-function org-id-store-link "org-id")
  4224. (declare-function org-id-locations-load "org-id")
  4225. (declare-function org-id-locations-save "org-id")
  4226. (defvar org-id-track-globally)
  4227. ;;; Variables for pre-computed regular expressions, all buffer local
  4228. (defvar-local org-todo-regexp nil
  4229. "Matches any of the TODO state keywords.")
  4230. (defvar-local org-not-done-regexp nil
  4231. "Matches any of the TODO state keywords except the last one.")
  4232. (defvar-local org-not-done-heading-regexp nil
  4233. "Matches a TODO headline that is not done.")
  4234. (defvar-local org-todo-line-regexp nil
  4235. "Matches a headline and puts TODO state into group 2 if present.")
  4236. (defvar-local org-complex-heading-regexp nil
  4237. "Matches a headline and puts everything into groups:
  4238. group 1: the stars
  4239. group 2: The todo keyword, maybe
  4240. group 3: Priority cookie
  4241. group 4: True headline
  4242. group 5: Tags
  4243. Since TODO keywords are case-sensitive, `case-fold-search' is
  4244. expected to be bound to nil when matching this regexp.")
  4245. (defvar-local org-complex-heading-regexp-format nil
  4246. "Printf format to make regexp to match an exact headline.
  4247. This regexp will match the headline of any node which has the
  4248. exact headline text that is put into the format, but may have any
  4249. TODO state, priority and tags.")
  4250. (defvar-local org-todo-line-tags-regexp nil
  4251. "Matches a headline and puts TODO state into group 2 if present.
  4252. Also put tags into group 4 if tags are present.")
  4253. (defconst org-plain-time-of-day-regexp
  4254. (concat
  4255. "\\(\\<[012]?[0-9]"
  4256. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4257. "\\(--?"
  4258. "\\(\\<[012]?[0-9]"
  4259. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4260. "\\)?")
  4261. "Regular expression to match a plain time or time range.
  4262. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4263. groups carry important information:
  4264. 0 the full match
  4265. 1 the first time, range or not
  4266. 8 the second time, if it is a range.")
  4267. (defconst org-plain-time-extension-regexp
  4268. (concat
  4269. "\\(\\<[012]?[0-9]"
  4270. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4271. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4272. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4273. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4274. groups carry important information:
  4275. 0 the full match
  4276. 7 hours of duration
  4277. 9 minutes of duration")
  4278. (defconst org-stamp-time-of-day-regexp
  4279. (concat
  4280. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4281. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4282. "\\(--?"
  4283. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4284. "Regular expression to match a timestamp time or time range.
  4285. After a match, the following groups carry important information:
  4286. 0 the full match
  4287. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4288. 2 the first time, range or not
  4289. 4 the second time, if it is a range.")
  4290. (defconst org-startup-options
  4291. '(("fold" org-startup-folded t)
  4292. ("overview" org-startup-folded t)
  4293. ("nofold" org-startup-folded nil)
  4294. ("showall" org-startup-folded nil)
  4295. ("showeverything" org-startup-folded showeverything)
  4296. ("content" org-startup-folded content)
  4297. ("indent" org-startup-indented t)
  4298. ("noindent" org-startup-indented nil)
  4299. ("hidestars" org-hide-leading-stars t)
  4300. ("showstars" org-hide-leading-stars nil)
  4301. ("odd" org-odd-levels-only t)
  4302. ("oddeven" org-odd-levels-only nil)
  4303. ("align" org-startup-align-all-tables t)
  4304. ("noalign" org-startup-align-all-tables nil)
  4305. ("inlineimages" org-startup-with-inline-images t)
  4306. ("noinlineimages" org-startup-with-inline-images nil)
  4307. ("latexpreview" org-startup-with-latex-preview t)
  4308. ("nolatexpreview" org-startup-with-latex-preview nil)
  4309. ("customtime" org-display-custom-times t)
  4310. ("logdone" org-log-done time)
  4311. ("lognotedone" org-log-done note)
  4312. ("nologdone" org-log-done nil)
  4313. ("lognoteclock-out" org-log-note-clock-out t)
  4314. ("nolognoteclock-out" org-log-note-clock-out nil)
  4315. ("logrepeat" org-log-repeat state)
  4316. ("lognoterepeat" org-log-repeat note)
  4317. ("logdrawer" org-log-into-drawer t)
  4318. ("nologdrawer" org-log-into-drawer nil)
  4319. ("logstatesreversed" org-log-states-order-reversed t)
  4320. ("nologstatesreversed" org-log-states-order-reversed nil)
  4321. ("nologrepeat" org-log-repeat nil)
  4322. ("logreschedule" org-log-reschedule time)
  4323. ("lognotereschedule" org-log-reschedule note)
  4324. ("nologreschedule" org-log-reschedule nil)
  4325. ("logredeadline" org-log-redeadline time)
  4326. ("lognoteredeadline" org-log-redeadline note)
  4327. ("nologredeadline" org-log-redeadline nil)
  4328. ("logrefile" org-log-refile time)
  4329. ("lognoterefile" org-log-refile note)
  4330. ("nologrefile" org-log-refile nil)
  4331. ("fninline" org-footnote-define-inline t)
  4332. ("nofninline" org-footnote-define-inline nil)
  4333. ("fnlocal" org-footnote-section nil)
  4334. ("fnauto" org-footnote-auto-label t)
  4335. ("fnprompt" org-footnote-auto-label nil)
  4336. ("fnconfirm" org-footnote-auto-label confirm)
  4337. ("fnplain" org-footnote-auto-label plain)
  4338. ("fnadjust" org-footnote-auto-adjust t)
  4339. ("nofnadjust" org-footnote-auto-adjust nil)
  4340. ("constcgs" constants-unit-system cgs)
  4341. ("constSI" constants-unit-system SI)
  4342. ("noptag" org-tag-persistent-alist nil)
  4343. ("hideblocks" org-hide-block-startup t)
  4344. ("nohideblocks" org-hide-block-startup nil)
  4345. ("beamer" org-startup-with-beamer-mode t)
  4346. ("entitiespretty" org-pretty-entities t)
  4347. ("entitiesplain" org-pretty-entities nil))
  4348. "Variable associated with STARTUP options for org-mode.
  4349. Each element is a list of three items: the startup options (as written
  4350. in the #+STARTUP line), the corresponding variable, and the value to set
  4351. this variable to if the option is found. An optional forth element PUSH
  4352. means to push this value onto the list in the variable.")
  4353. (defcustom org-group-tags t
  4354. "When non-nil (the default), use group tags.
  4355. This can be turned on/off through `org-toggle-tags-groups'."
  4356. :group 'org-tags
  4357. :group 'org-startup
  4358. :type 'boolean)
  4359. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4360. (defun org-toggle-tags-groups ()
  4361. "Toggle support for group tags.
  4362. Support for group tags is controlled by the option
  4363. `org-group-tags', which is non-nil by default."
  4364. (interactive)
  4365. (setq org-group-tags (not org-group-tags))
  4366. (cond ((and (derived-mode-p 'org-agenda-mode)
  4367. org-group-tags)
  4368. (org-agenda-redo))
  4369. ((derived-mode-p 'org-mode)
  4370. (let ((org-inhibit-startup t)) (org-mode))))
  4371. (message "Groups tags support has been turned %s"
  4372. (if org-group-tags "on" "off")))
  4373. (defun org-set-regexps-and-options (&optional tags-only)
  4374. "Precompute regular expressions used in the current buffer.
  4375. When optional argument TAGS-ONLY is non-nil, only compute tags
  4376. related expressions."
  4377. (when (derived-mode-p 'org-mode)
  4378. (let ((alist (org--setup-collect-keywords
  4379. (org-make-options-regexp
  4380. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4381. (and (not tags-only)
  4382. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4383. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4384. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4385. ;; Startup options. Get this early since it does change
  4386. ;; behavior for other options (e.g., tags).
  4387. (let ((startup (cdr (assq 'startup alist))))
  4388. (dolist (option startup)
  4389. (let ((entry (assoc-string option org-startup-options t)))
  4390. (when entry
  4391. (let ((var (nth 1 entry))
  4392. (val (nth 2 entry)))
  4393. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4394. (unless (listp (symbol-value var))
  4395. (set (make-local-variable var) nil))
  4396. (add-to-list var val)))))))
  4397. (setq-local org-file-tags
  4398. (mapcar #'org-add-prop-inherited
  4399. (cdr (assq 'filetags alist))))
  4400. (setq org-current-tag-alist
  4401. (append org-tag-persistent-alist
  4402. (let ((tags (cdr (assq 'tags alist))))
  4403. (if tags (org-tag-string-to-alist tags)
  4404. org-tag-alist))))
  4405. (setq org-tag-groups-alist
  4406. (org-tag-alist-to-groups org-current-tag-alist))
  4407. (unless tags-only
  4408. ;; File properties.
  4409. (setq-local org-file-properties (cdr (assq 'property alist)))
  4410. ;; Archive location.
  4411. (let ((archive (cdr (assq 'archive alist))))
  4412. (when archive (setq-local org-archive-location archive)))
  4413. ;; Category.
  4414. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4415. (when cat
  4416. (setq-local org-category (intern cat))
  4417. (setq-local org-file-properties
  4418. (org--update-property-plist
  4419. "CATEGORY" cat org-file-properties))))
  4420. ;; Columns.
  4421. (let ((column (cdr (assq 'columns alist))))
  4422. (when column (setq-local org-columns-default-format column)))
  4423. ;; Constants.
  4424. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4425. ;; Link abbreviations.
  4426. (let ((links (cdr (assq 'link alist))))
  4427. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4428. ;; Priorities.
  4429. (let ((priorities (cdr (assq 'priorities alist))))
  4430. (when priorities
  4431. (setq-local org-highest-priority (nth 0 priorities))
  4432. (setq-local org-lowest-priority (nth 1 priorities))
  4433. (setq-local org-default-priority (nth 2 priorities))))
  4434. ;; Scripts.
  4435. (let ((scripts (assq 'scripts alist)))
  4436. (when scripts
  4437. (setq-local org-use-sub-superscripts (cdr scripts))))
  4438. ;; TODO keywords.
  4439. (setq-local org-todo-kwd-alist nil)
  4440. (setq-local org-todo-key-alist nil)
  4441. (setq-local org-todo-key-trigger nil)
  4442. (setq-local org-todo-keywords-1 nil)
  4443. (setq-local org-done-keywords nil)
  4444. (setq-local org-todo-heads nil)
  4445. (setq-local org-todo-sets nil)
  4446. (setq-local org-todo-log-states nil)
  4447. (let ((todo-sequences
  4448. (or (nreverse (cdr (assq 'todo alist)))
  4449. (let ((d (default-value 'org-todo-keywords)))
  4450. (if (not (stringp (car d))) d
  4451. ;; XXX: Backward compatibility code.
  4452. (list (cons org-todo-interpretation d)))))))
  4453. (dolist (sequence todo-sequences)
  4454. (let* ((sequence (or (run-hook-with-args-until-success
  4455. 'org-todo-setup-filter-hook sequence)
  4456. sequence))
  4457. (sequence-type (car sequence))
  4458. (keywords (cdr sequence))
  4459. (sep (member "|" keywords))
  4460. names alist)
  4461. (dolist (k (remove "|" keywords))
  4462. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4463. k)
  4464. (error "Invalid TODO keyword %s" k))
  4465. (let ((name (match-string 1 k))
  4466. (key (match-string 2 k))
  4467. (log (org-extract-log-state-settings k)))
  4468. (push name names)
  4469. (push (cons name (and key (string-to-char key))) alist)
  4470. (when log (push log org-todo-log-states))))
  4471. (let* ((names (nreverse names))
  4472. (done (if sep (org-remove-keyword-keys (cdr sep))
  4473. (last names)))
  4474. (head (car names))
  4475. (tail (list sequence-type head (car done) (org-last done))))
  4476. (add-to-list 'org-todo-heads head 'append)
  4477. (push names org-todo-sets)
  4478. (setq org-done-keywords (append org-done-keywords done nil))
  4479. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4480. (setq org-todo-key-alist
  4481. (append org-todo-key-alist
  4482. (and alist
  4483. (append '((:startgroup))
  4484. (nreverse alist)
  4485. '((:endgroup))))))
  4486. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4487. (setq org-todo-sets (nreverse org-todo-sets)
  4488. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4489. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4490. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4491. ;; Compute the regular expressions and other local variables.
  4492. ;; Using `org-outline-regexp-bol' would complicate them much,
  4493. ;; because of the fixed white space at the end of that string.
  4494. (unless org-done-keywords
  4495. (setq org-done-keywords
  4496. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4497. (setq org-not-done-keywords
  4498. (org-delete-all org-done-keywords
  4499. (copy-sequence org-todo-keywords-1))
  4500. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4501. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4502. org-not-done-heading-regexp
  4503. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4504. org-todo-line-regexp
  4505. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4506. org-complex-heading-regexp
  4507. (concat "^\\(\\*+\\)"
  4508. "\\(?: +" org-todo-regexp "\\)?"
  4509. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4510. "\\(?: +\\(.*?\\)\\)??"
  4511. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4512. "[ \t]*$")
  4513. org-complex-heading-regexp-format
  4514. (concat "^\\(\\*+\\)"
  4515. "\\(?: +" org-todo-regexp "\\)?"
  4516. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4517. "\\(?: +"
  4518. ;; Stats cookies can be stuck to body.
  4519. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4520. "\\(%s\\)"
  4521. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4522. "\\)"
  4523. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4524. "[ \t]*$")
  4525. org-todo-line-tags-regexp
  4526. (concat "^\\(\\*+\\)"
  4527. "\\(?: +" org-todo-regexp "\\)?"
  4528. "\\(?: +\\(.*?\\)\\)??"
  4529. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4530. "[ \t]*$"))
  4531. (org-compute-latex-and-related-regexp)))))
  4532. (defun org--setup-collect-keywords (regexp &optional files alist)
  4533. "Return setup keywords values as an alist.
  4534. REGEXP matches a subset of setup keywords. FILES is a list of
  4535. file names already visited. It is used to avoid circular setup
  4536. files. ALIST, when non-nil, is the alist computed so far.
  4537. Return value contains the following keys: `archive', `category',
  4538. `columns', `constants', `filetags', `link', `priorities',
  4539. `property', `scripts', `startup', `tags' and `todo'."
  4540. (org-with-wide-buffer
  4541. (goto-char (point-min))
  4542. (let ((case-fold-search t))
  4543. (while (re-search-forward regexp nil t)
  4544. (let ((element (org-element-at-point)))
  4545. (when (eq (org-element-type element) 'keyword)
  4546. (let ((key (org-element-property :key element))
  4547. (value (org-element-property :value element)))
  4548. (cond
  4549. ((equal key "ARCHIVE")
  4550. (when (org-string-nw-p value)
  4551. (push (cons 'archive value) alist)))
  4552. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4553. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4554. ((equal key "CONSTANTS")
  4555. (let* ((constants (assq 'constants alist))
  4556. (store (cdr constants)))
  4557. (dolist (pair (org-split-string value))
  4558. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4559. pair)
  4560. (let* ((name (match-string 1 pair))
  4561. (value (match-string 2 pair))
  4562. (old (assoc name store)))
  4563. (if old (setcdr old value)
  4564. (push (cons name value) store)))))
  4565. (if constants (setcdr constants store)
  4566. (push (cons 'constants store) alist))))
  4567. ((equal key "FILETAGS")
  4568. (when (org-string-nw-p value)
  4569. (let ((old (assq 'filetags alist))
  4570. (new (apply #'nconc
  4571. (mapcar (lambda (x) (org-split-string x ":"))
  4572. (org-split-string value)))))
  4573. (if old (setcdr old (append new (cdr old)))
  4574. (push (cons 'filetags new) alist)))))
  4575. ((equal key "LINK")
  4576. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4577. (let ((links (assq 'link alist))
  4578. (pair (cons (match-string-no-properties 1 value)
  4579. (match-string-no-properties 2 value))))
  4580. (if links (push pair (cdr links))
  4581. (push (list 'link pair) alist)))))
  4582. ((equal key "OPTIONS")
  4583. (when (and (org-string-nw-p value)
  4584. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4585. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4586. ((equal key "PRIORITIES")
  4587. (push (cons 'priorities
  4588. (let ((prio (org-split-string value)))
  4589. (if (< (length prio) 3) '(?A ?C ?B)
  4590. (mapcar #'string-to-char prio))))
  4591. alist))
  4592. ((equal key "PROPERTY")
  4593. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4594. (let* ((property (assq 'property alist))
  4595. (value (org--update-property-plist
  4596. (match-string-no-properties 1 value)
  4597. (match-string-no-properties 2 value)
  4598. (cdr property))))
  4599. (if property (setcdr property value)
  4600. (push (cons 'property value) alist)))))
  4601. ((equal key "STARTUP")
  4602. (let ((startup (assq 'startup alist)))
  4603. (if startup
  4604. (setcdr startup
  4605. (append (cdr startup) (org-split-string value)))
  4606. (push (cons 'startup (org-split-string value)) alist))))
  4607. ((equal key "TAGS")
  4608. (let ((tag-cell (assq 'tags alist)))
  4609. (if tag-cell
  4610. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4611. (push (cons 'tags value) alist))))
  4612. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4613. (let ((todo (assq 'todo alist))
  4614. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4615. (org-split-string value))))
  4616. (if todo (push value (cdr todo))
  4617. (push (list 'todo value) alist))))
  4618. ((equal key "SETUPFILE")
  4619. (unless buffer-read-only ; Do not check in Gnus messages.
  4620. (let ((f (and (org-string-nw-p value)
  4621. (expand-file-name
  4622. (org-unbracket-string "\"" "\"" value)))))
  4623. (when (and f (file-readable-p f) (not (member f files)))
  4624. (with-temp-buffer
  4625. (setq default-directory (file-name-directory f))
  4626. (insert-file-contents f)
  4627. (setq alist
  4628. ;; Fake Org mode to benefit from cache
  4629. ;; without recurring needlessly.
  4630. (let ((major-mode 'org-mode))
  4631. (org--setup-collect-keywords
  4632. regexp (cons f files) alist)))))))))))))))
  4633. alist)
  4634. (defun org-tag-string-to-alist (s)
  4635. "Return tag alist associated to string S.
  4636. S is a value for TAGS keyword or produced with
  4637. `org-tag-alist-to-string'. Return value is an alist suitable for
  4638. `org-tag-alist' or `org-tag-persistent-alist'."
  4639. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4640. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4641. "\\|{.+?}\\)" ; regular expression
  4642. "\\(?:(\\(.\\))\\)?\\'"))
  4643. alist group-flag)
  4644. (dolist (tokens lines (cdr (nreverse alist)))
  4645. (push '(:newline) alist)
  4646. (while tokens
  4647. (let ((token (pop tokens)))
  4648. (pcase token
  4649. ("{"
  4650. (push '(:startgroup) alist)
  4651. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4652. ("}"
  4653. (push '(:endgroup) alist)
  4654. (setq group-flag nil))
  4655. ("["
  4656. (push '(:startgrouptag) alist)
  4657. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4658. ("]"
  4659. (push '(:endgrouptag) alist)
  4660. (setq group-flag nil))
  4661. (":"
  4662. (push '(:grouptags) alist))
  4663. ((guard (string-match tag-re token))
  4664. (let ((tag (match-string 1 token))
  4665. (key (and (match-beginning 2)
  4666. (string-to-char (match-string 2 token)))))
  4667. ;; Push all tags in groups, no matter if they already
  4668. ;; appear somewhere else in the list.
  4669. (when (or group-flag (not (assoc tag alist)))
  4670. (push (cons tag key) alist))))))))))
  4671. (defun org-tag-alist-to-string (alist &optional skip-key)
  4672. "Return tag string associated to ALIST.
  4673. ALIST is an alist, as defined in `org-tag-alist' or
  4674. `org-tag-persistent-alist', or produced with
  4675. `org-tag-string-to-alist'.
  4676. Return value is a string suitable as a value for \"TAGS\"
  4677. keyword.
  4678. When optional argument SKIP-KEY is non-nil, skip selection keys
  4679. next to tags."
  4680. (mapconcat (lambda (token)
  4681. (pcase token
  4682. (`(:startgroup) "{")
  4683. (`(:endgroup) "}")
  4684. (`(:startgrouptag) "[")
  4685. (`(:endgrouptag) "]")
  4686. (`(:grouptags) ":")
  4687. (`(:newline) "\\n")
  4688. ((and
  4689. (guard (not skip-key))
  4690. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4691. (format "%s(%c)" tag key))
  4692. (`(,(and tag (pred stringp)) . ,_) tag)
  4693. (_ (user-error "Invalid tag token: %S" token))))
  4694. alist
  4695. " "))
  4696. (defun org-tag-alist-to-groups (alist)
  4697. "Return group alist from tag ALIST.
  4698. ALIST is an alist, as defined in `org-tag-alist' or
  4699. `org-tag-persistent-alist', or produced with
  4700. `org-tag-string-to-alist'. Return value is an alist following
  4701. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4702. a string, summarizing TAGS, as a list of strings."
  4703. (let (groups group-status current-group)
  4704. (dolist (token alist (nreverse groups))
  4705. (pcase token
  4706. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4707. (`(,(or :endgroup :endgrouptag))
  4708. (when (eq group-status 'append)
  4709. (push (nreverse current-group) groups))
  4710. (setq group-status nil))
  4711. (`(:grouptags) (setq group-status 'append))
  4712. ((and `(,tag . ,_) (guard group-status))
  4713. (if (eq group-status 'append) (push tag current-group)
  4714. (setq current-group (list tag))))
  4715. (_ nil)))))
  4716. (defun org-file-contents (file &optional noerror)
  4717. "Return the contents of FILE, as a string."
  4718. (if (and file (file-readable-p file))
  4719. (with-temp-buffer
  4720. (insert-file-contents file)
  4721. (buffer-string))
  4722. (funcall (if noerror 'message 'error)
  4723. "Cannot read file \"%s\"%s"
  4724. file
  4725. (let ((from (buffer-file-name (buffer-base-buffer))))
  4726. (if from (concat " (referenced in file \"" from "\")") "")))))
  4727. (defun org-extract-log-state-settings (x)
  4728. "Extract the log state setting from a TODO keyword string.
  4729. This will extract info from a string like \"WAIT(w@/!)\"."
  4730. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4731. (let ((kw (match-string 1 x))
  4732. (log1 (and (match-end 3) (match-string 3 x)))
  4733. (log2 (and (match-end 4) (match-string 4 x))))
  4734. (and (or log1 log2)
  4735. (list kw
  4736. (and log1 (if (equal log1 "!") 'time 'note))
  4737. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4738. (defun org-remove-keyword-keys (list)
  4739. "Remove a pair of parenthesis at the end of each string in LIST."
  4740. (mapcar (lambda (x)
  4741. (if (string-match "(.*)$" x)
  4742. (substring x 0 (match-beginning 0))
  4743. x))
  4744. list))
  4745. (defun org-assign-fast-keys (alist)
  4746. "Assign fast keys to a keyword-key alist.
  4747. Respect keys that are already there."
  4748. (let (new e (alt ?0))
  4749. (while (setq e (pop alist))
  4750. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4751. (cdr e)) ;; Key already assigned.
  4752. (push e new)
  4753. (let ((clist (string-to-list (downcase (car e))))
  4754. (used (append new alist)))
  4755. (when (= (car clist) ?@)
  4756. (pop clist))
  4757. (while (and clist (rassoc (car clist) used))
  4758. (pop clist))
  4759. (unless clist
  4760. (while (rassoc alt used)
  4761. (cl-incf alt)))
  4762. (push (cons (car e) (or (car clist) alt)) new))))
  4763. (nreverse new)))
  4764. ;;; Some variables used in various places
  4765. (defvar org-window-configuration nil
  4766. "Used in various places to store a window configuration.")
  4767. (defvar org-selected-window nil
  4768. "Used in various places to store a window configuration.")
  4769. (defvar org-finish-function nil
  4770. "Function to be called when `C-c C-c' is used.
  4771. This is for getting out of special buffers like capture.")
  4772. (defvar org-last-state)
  4773. ;; Defined somewhere in this file, but used before definition.
  4774. (defvar org-entities) ;; defined in org-entities.el
  4775. (defvar org-struct-menu)
  4776. (defvar org-org-menu)
  4777. (defvar org-tbl-menu)
  4778. ;;;; Define the Org mode
  4779. ;; We use a before-change function to check if a table might need
  4780. ;; an update.
  4781. (defvar org-table-may-need-update t
  4782. "Indicates that a table might need an update.
  4783. This variable is set by `org-before-change-function'.
  4784. `org-table-align' sets it back to nil.")
  4785. (defun org-before-change-function (_beg _end)
  4786. "Every change indicates that a table might need an update."
  4787. (setq org-table-may-need-update t))
  4788. (defvar org-mode-map)
  4789. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4790. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4791. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4792. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4793. (defvar org-table-buffer-is-an nil)
  4794. (defvar bidi-paragraph-direction)
  4795. (defvar buffer-face-mode-face)
  4796. (require 'outline)
  4797. ;; Other stuff we need.
  4798. (require 'time-date)
  4799. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4800. (require 'easymenu)
  4801. (autoload 'easy-menu-add "easymenu")
  4802. (require 'overlay)
  4803. ;; (require 'org-macs) moved higher up in the file before it is first used
  4804. (require 'org-entities)
  4805. ;; (require 'org-compat) moved higher up in the file before it is first used
  4806. (require 'org-faces)
  4807. (require 'org-list)
  4808. (require 'org-pcomplete)
  4809. (require 'org-src)
  4810. (require 'org-footnote)
  4811. (require 'org-macro)
  4812. ;; babel
  4813. (require 'ob)
  4814. ;;;###autoload
  4815. (define-derived-mode org-mode outline-mode "Org"
  4816. "Outline-based notes management and organizer, alias
  4817. \"Carsten's outline-mode for keeping track of everything.\"
  4818. Org mode develops organizational tasks around a NOTES file which
  4819. contains information about projects as plain text. Org mode is
  4820. implemented on top of Outline mode, which is ideal to keep the content
  4821. of large files well structured. It supports ToDo items, deadlines and
  4822. time stamps, which magically appear in the diary listing of the Emacs
  4823. calendar. Tables are easily created with a built-in table editor.
  4824. Plain text URL-like links connect to websites, emails (VM), Usenet
  4825. messages (Gnus), BBDB entries, and any files related to the project.
  4826. For printing and sharing of notes, an Org file (or a part of it)
  4827. can be exported as a structured ASCII or HTML file.
  4828. The following commands are available:
  4829. \\{org-mode-map}"
  4830. ;; Get rid of Outline menus, they are not needed
  4831. ;; Need to do this here because define-derived-mode sets up
  4832. ;; the keymap so late. Still, it is a waste to call this each time
  4833. ;; we switch another buffer into Org mode.
  4834. (define-key org-mode-map [menu-bar headings] 'undefined)
  4835. (define-key org-mode-map [menu-bar hide] 'undefined)
  4836. (define-key org-mode-map [menu-bar show] 'undefined)
  4837. (org-load-modules-maybe)
  4838. (org-install-agenda-files-menu)
  4839. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4840. (add-to-invisibility-spec '(org-cwidth))
  4841. (add-to-invisibility-spec '(org-hide-block . t))
  4842. (setq-local outline-regexp org-outline-regexp)
  4843. (setq-local outline-level 'org-outline-level)
  4844. (setq bidi-paragraph-direction 'left-to-right)
  4845. (when (and org-ellipsis
  4846. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4847. (fboundp 'make-glyph-code))
  4848. (unless org-display-table
  4849. (setq org-display-table (make-display-table)))
  4850. (set-display-table-slot
  4851. org-display-table 4
  4852. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4853. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4854. (setq buffer-display-table org-display-table))
  4855. (org-set-regexps-and-options)
  4856. (org-set-font-lock-defaults)
  4857. (when (and org-tag-faces (not org-tags-special-faces-re))
  4858. ;; tag faces set outside customize.... force initialization.
  4859. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4860. ;; Calc embedded
  4861. (setq-local calc-embedded-open-mode "# ")
  4862. ;; Modify a few syntax entries
  4863. (modify-syntax-entry ?@ "w")
  4864. (modify-syntax-entry ?\" "\"")
  4865. (modify-syntax-entry ?\\ "_")
  4866. (modify-syntax-entry ?~ "_")
  4867. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4868. ;; Activate before-change-function
  4869. (setq-local org-table-may-need-update t)
  4870. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4871. ;; Check for running clock before killing a buffer
  4872. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4873. ;; Initialize macros templates.
  4874. (org-macro-initialize-templates)
  4875. ;; Initialize radio targets.
  4876. (org-update-radio-target-regexp)
  4877. ;; Indentation.
  4878. (setq-local indent-line-function 'org-indent-line)
  4879. (setq-local indent-region-function 'org-indent-region)
  4880. ;; Filling and auto-filling.
  4881. (org-setup-filling)
  4882. ;; Comments.
  4883. (org-setup-comments-handling)
  4884. ;; Initialize cache.
  4885. (org-element-cache-reset)
  4886. ;; Beginning/end of defun
  4887. (setq-local beginning-of-defun-function 'org-backward-element)
  4888. (setq-local end-of-defun-function
  4889. (lambda ()
  4890. (if (not (org-at-heading-p))
  4891. (org-forward-element)
  4892. (org-forward-element)
  4893. (forward-char -1))))
  4894. ;; Next error for sparse trees
  4895. (setq-local next-error-function 'org-occur-next-match)
  4896. ;; Make sure dependence stuff works reliably, even for users who set it
  4897. ;; too late :-(
  4898. (if org-enforce-todo-dependencies
  4899. (add-hook 'org-blocker-hook
  4900. 'org-block-todo-from-children-or-siblings-or-parent)
  4901. (remove-hook 'org-blocker-hook
  4902. 'org-block-todo-from-children-or-siblings-or-parent))
  4903. (if org-enforce-todo-checkbox-dependencies
  4904. (add-hook 'org-blocker-hook
  4905. 'org-block-todo-from-checkboxes)
  4906. (remove-hook 'org-blocker-hook
  4907. 'org-block-todo-from-checkboxes))
  4908. ;; Align options lines
  4909. (setq-local
  4910. align-mode-rules-list
  4911. '((org-in-buffer-settings
  4912. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4913. (modes . '(org-mode)))))
  4914. ;; Imenu
  4915. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4916. ;; Make isearch reveal context
  4917. (setq-local outline-isearch-open-invisible-function
  4918. (lambda (&rest _) (org-show-context 'isearch)))
  4919. ;; Setup the pcomplete hooks
  4920. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4921. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4922. (setq-local pcomplete-default-completion-function 'ignore)
  4923. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4924. (setq-local pcomplete-termination-string "")
  4925. (setq-local buffer-face-mode-face 'org-default)
  4926. ;; If empty file that did not turn on Org mode automatically, make
  4927. ;; it to.
  4928. (when (and org-insert-mode-line-in-empty-file
  4929. (called-interactively-p 'any)
  4930. (= (point-min) (point-max)))
  4931. (insert "# -*- mode: org -*-\n\n"))
  4932. (unless org-inhibit-startup
  4933. (org-unmodified
  4934. (when org-startup-with-beamer-mode (org-beamer-mode))
  4935. (when org-startup-align-all-tables
  4936. (org-table-map-tables #'org-table-align t))
  4937. (when org-startup-with-inline-images (org-display-inline-images))
  4938. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4939. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4940. (when org-startup-truncated (setq truncate-lines t))
  4941. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4942. (org-refresh-effort-properties)))
  4943. ;; Try to set `org-hide' face correctly.
  4944. (let ((foreground (org-find-invisible-foreground)))
  4945. (when foreground
  4946. (set-face-foreground 'org-hide foreground))))
  4947. ;; Update `customize-package-emacs-version-alist'
  4948. (add-to-list 'customize-package-emacs-version-alist
  4949. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4950. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4951. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4952. ("9.0" . "25.2")))
  4953. (defvar org-mode-transpose-word-syntax-table
  4954. (let ((st (make-syntax-table text-mode-syntax-table)))
  4955. (dolist (c org-emphasis-alist st)
  4956. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4957. (when (fboundp 'abbrev-table-put)
  4958. (abbrev-table-put org-mode-abbrev-table
  4959. :parents (list text-mode-abbrev-table)))
  4960. (defun org-find-invisible-foreground ()
  4961. (let ((candidates (remove
  4962. "unspecified-bg"
  4963. (nconc
  4964. (list (face-background 'default)
  4965. (face-background 'org-default))
  4966. (mapcar
  4967. (lambda (alist)
  4968. (when (boundp alist)
  4969. (cdr (assq 'background-color (symbol-value alist)))))
  4970. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4971. (list (face-foreground 'org-hide))))))
  4972. (car (remove nil candidates))))
  4973. (defun org-current-time (&optional rounding-minutes past)
  4974. "Current time, possibly rounded to ROUNDING-MINUTES.
  4975. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4976. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4977. the rounding returns a past time."
  4978. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4979. (car org-time-stamp-rounding-minutes)))
  4980. (time (decode-time)) res)
  4981. (if (< r 1)
  4982. (current-time)
  4983. (setq res
  4984. (apply 'encode-time
  4985. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4986. (nthcdr 2 time))))
  4987. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4988. (seconds-to-time (- (float-time res) (* r 60)))
  4989. res))))
  4990. (defun org-today ()
  4991. "Return today date, considering `org-extend-today-until'."
  4992. (time-to-days
  4993. (time-subtract (current-time)
  4994. (list 0 (* 3600 org-extend-today-until) 0))))
  4995. ;;;; Font-Lock stuff, including the activators
  4996. (defvar org-mouse-map (make-sparse-keymap))
  4997. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4998. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4999. (when org-mouse-1-follows-link
  5000. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5001. (when org-tab-follows-link
  5002. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5003. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5004. (require 'font-lock)
  5005. (defconst org-non-link-chars "]\t\n\r<>")
  5006. (defvar org-link-types-re nil
  5007. "Matches a link that has a url-like prefix like \"http:\"")
  5008. (defvar org-link-re-with-space nil
  5009. "Matches a link with spaces, optional angular brackets around it.")
  5010. (defvar org-link-re-with-space2 nil
  5011. "Matches a link with spaces, optional angular brackets around it.")
  5012. (defvar org-link-re-with-space3 nil
  5013. "Matches a link with spaces, only for internal part in bracket links.")
  5014. (defvar org-angle-link-re nil
  5015. "Matches link with angular brackets, spaces are allowed.")
  5016. (defvar org-plain-link-re nil
  5017. "Matches plain link, without spaces.")
  5018. (defvar org-bracket-link-regexp nil
  5019. "Matches a link in double brackets.")
  5020. (defvar org-bracket-link-analytic-regexp nil
  5021. "Regular expression used to analyze links.
  5022. Here is what the match groups contain after a match:
  5023. 1: http:
  5024. 2: http
  5025. 3: path
  5026. 4: [desc]
  5027. 5: desc")
  5028. (defvar org-bracket-link-analytic-regexp++ nil
  5029. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5030. (defvar org-any-link-re nil
  5031. "Regular expression matching any link.")
  5032. (defconst org-match-sexp-depth 3
  5033. "Number of stacked braces for sub/superscript matching.")
  5034. (defun org-create-multibrace-regexp (left right n)
  5035. "Create a regular expression which will match a balanced sexp.
  5036. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5037. as single character strings.
  5038. The regexp returned will match the entire expression including the
  5039. delimiters. It will also define a single group which contains the
  5040. match except for the outermost delimiters. The maximum depth of
  5041. stacked delimiters is N. Escaping delimiters is not possible."
  5042. (let* ((nothing (concat "[^" left right "]*?"))
  5043. (or "\\|")
  5044. (re nothing)
  5045. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5046. (while (> n 1)
  5047. (setq n (1- n)
  5048. re (concat re or next)
  5049. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5050. (concat left "\\(" re "\\)" right)))
  5051. (defconst org-match-substring-regexp
  5052. (concat
  5053. "\\(\\S-\\)\\([_^]\\)\\("
  5054. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5055. "\\|"
  5056. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5057. "\\|"
  5058. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5059. "The regular expression matching a sub- or superscript.")
  5060. (defconst org-match-substring-with-braces-regexp
  5061. (concat
  5062. "\\(\\S-\\)\\([_^]\\)"
  5063. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5064. "The regular expression matching a sub- or superscript, forcing braces.")
  5065. (defun org-make-link-regexps ()
  5066. "Update the link regular expressions.
  5067. This should be called after the variable `org-link-parameters' has changed."
  5068. (let ((types-re (regexp-opt (org-link-types) t)))
  5069. (setq org-link-types-re
  5070. (concat "\\`" types-re ":")
  5071. org-link-re-with-space
  5072. (concat "<?" types-re ":"
  5073. "\\([^" org-non-link-chars " ]"
  5074. "[^" org-non-link-chars "]*"
  5075. "[^" org-non-link-chars " ]\\)>?")
  5076. org-link-re-with-space2
  5077. (concat "<?" types-re ":"
  5078. "\\([^" org-non-link-chars " ]"
  5079. "[^\t\n\r]*"
  5080. "[^" org-non-link-chars " ]\\)>?")
  5081. org-link-re-with-space3
  5082. (concat "<?" types-re ":"
  5083. "\\([^" org-non-link-chars " ]"
  5084. "[^\t\n\r]*\\)")
  5085. org-angle-link-re
  5086. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5087. types-re)
  5088. org-plain-link-re
  5089. (concat
  5090. "\\<" types-re ":"
  5091. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5092. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5093. org-bracket-link-regexp
  5094. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5095. org-bracket-link-analytic-regexp
  5096. (concat
  5097. "\\[\\["
  5098. "\\(" types-re ":\\)?"
  5099. "\\([^]]+\\)"
  5100. "\\]"
  5101. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5102. "\\]")
  5103. org-bracket-link-analytic-regexp++
  5104. (concat
  5105. "\\[\\["
  5106. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5107. "\\([^]]+\\)"
  5108. "\\]"
  5109. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5110. "\\]")
  5111. org-any-link-re
  5112. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5113. org-angle-link-re "\\)\\|\\("
  5114. org-plain-link-re "\\)"))))
  5115. (org-make-link-regexps)
  5116. (defvar org-emph-face nil)
  5117. (defun org-do-emphasis-faces (limit)
  5118. "Run through the buffer and emphasize strings."
  5119. (let (rtn a)
  5120. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5121. (let* ((border (char-after (match-beginning 3)))
  5122. (bre (regexp-quote (char-to-string border))))
  5123. (when (and (not (= border (char-after (match-beginning 4))))
  5124. (not (string-match-p (concat bre ".*" bre)
  5125. (replace-regexp-in-string
  5126. "\n" " "
  5127. (substring (match-string 2) 1 -1)))))
  5128. (setq rtn t)
  5129. (setq a (assoc (match-string 3) org-emphasis-alist))
  5130. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5131. 'face
  5132. (nth 1 a))
  5133. (and (nth 2 a)
  5134. (org-remove-flyspell-overlays-in
  5135. (match-beginning 0) (match-end 0)))
  5136. (add-text-properties (match-beginning 2) (match-end 2)
  5137. '(font-lock-multiline t org-emphasis t))
  5138. (when org-hide-emphasis-markers
  5139. (add-text-properties (match-end 4) (match-beginning 5)
  5140. '(invisible org-link))
  5141. (add-text-properties (match-beginning 3) (match-end 3)
  5142. '(invisible org-link)))))
  5143. (goto-char (1+ (match-beginning 0))))
  5144. rtn))
  5145. (defun org-emphasize (&optional char)
  5146. "Insert or change an emphasis, i.e. a font like bold or italic.
  5147. If there is an active region, change that region to a new emphasis.
  5148. If there is no region, just insert the marker characters and position
  5149. the cursor between them.
  5150. CHAR should be the marker character. If it is a space, it means to
  5151. remove the emphasis of the selected region.
  5152. If CHAR is not given (for example in an interactive call) it will be
  5153. prompted for."
  5154. (interactive)
  5155. (let ((erc org-emphasis-regexp-components)
  5156. (string "") beg end move s)
  5157. (if (org-region-active-p)
  5158. (setq beg (region-beginning)
  5159. end (region-end)
  5160. string (buffer-substring beg end))
  5161. (setq move t))
  5162. (unless char
  5163. (message "Emphasis marker or tag: [%s]"
  5164. (mapconcat #'car org-emphasis-alist ""))
  5165. (setq char (read-char-exclusive)))
  5166. (if (equal char ?\s)
  5167. (setq s ""
  5168. move nil)
  5169. (unless (assoc (char-to-string char) org-emphasis-alist)
  5170. (user-error "No such emphasis marker: \"%c\"" char))
  5171. (setq s (char-to-string char)))
  5172. (while (and (> (length string) 1)
  5173. (equal (substring string 0 1) (substring string -1))
  5174. (assoc (substring string 0 1) org-emphasis-alist))
  5175. (setq string (substring string 1 -1)))
  5176. (setq string (concat s string s))
  5177. (when beg (delete-region beg end))
  5178. (unless (or (bolp)
  5179. (string-match (concat "[" (nth 0 erc) "\n]")
  5180. (char-to-string (char-before (point)))))
  5181. (insert " "))
  5182. (unless (or (eobp)
  5183. (string-match (concat "[" (nth 1 erc) "\n]")
  5184. (char-to-string (char-after (point)))))
  5185. (insert " ") (backward-char 1))
  5186. (insert string)
  5187. (and move (backward-char 1))))
  5188. (defconst org-nonsticky-props
  5189. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5190. (defsubst org-rear-nonsticky-at (pos)
  5191. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5192. (defun org-activate-plain-links (limit)
  5193. "Add link properties for plain links."
  5194. (when (and (re-search-forward org-plain-link-re limit t)
  5195. (not (org-in-src-block-p)))
  5196. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5197. 'face))
  5198. (link (match-string-no-properties 0))
  5199. (type (match-string-no-properties 1))
  5200. (path (match-string-no-properties 2))
  5201. (link-start (match-beginning 0))
  5202. (link-end (match-end 0))
  5203. (link-face (org-link-get-parameter type :face))
  5204. (help-echo (org-link-get-parameter type :help-echo))
  5205. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5206. (activate-func (org-link-get-parameter type :activate-func)))
  5207. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5208. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5209. (add-text-properties (match-beginning 0) (match-end 0)
  5210. (list
  5211. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5212. 'highlight)
  5213. 'face (cond
  5214. ;; A function that returns a face
  5215. ((functionp link-face)
  5216. (funcall link-face path))
  5217. ;; a face
  5218. ((facep link-face)
  5219. link-face)
  5220. ;; An anonymous face
  5221. ((consp link-face)
  5222. link-face)
  5223. ;; default
  5224. (t
  5225. 'org-link))
  5226. 'help-echo (cond
  5227. ((stringp help-echo)
  5228. help-echo)
  5229. ((functionp help-echo)
  5230. help-echo)
  5231. (t
  5232. (concat "LINK: "
  5233. (save-match-data
  5234. (org-link-unescape link)))))
  5235. 'htmlize-link (cond
  5236. ((functionp htmlize-link)
  5237. (funcall htmlize-link path))
  5238. (t
  5239. `(:uri ,link)))
  5240. 'keymap (or (org-link-get-parameter type :keymap)
  5241. org-mouse-map)
  5242. 'org-link-start (match-beginning 0)))
  5243. (org-rear-nonsticky-at (match-end 0))
  5244. (when activate-func
  5245. (funcall activate-func link-start link-end path nil))
  5246. t))))
  5247. (defun org-activate-code (limit)
  5248. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5249. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5250. (remove-text-properties (match-beginning 0) (match-end 0)
  5251. '(display t invisible t intangible t))
  5252. t))
  5253. (defcustom org-src-fontify-natively t
  5254. "When non-nil, fontify code in code blocks.
  5255. See also the `org-block' face."
  5256. :type 'boolean
  5257. :version "24.4"
  5258. :package-version '(Org . "8.3")
  5259. :group 'org-appearance
  5260. :group 'org-babel)
  5261. (defcustom org-allow-promoting-top-level-subtree nil
  5262. "When non-nil, allow promoting a top level subtree.
  5263. The leading star of the top level headline will be replaced
  5264. by a #."
  5265. :type 'boolean
  5266. :version "24.1"
  5267. :group 'org-appearance)
  5268. (defun org-fontify-meta-lines-and-blocks (limit)
  5269. (condition-case nil
  5270. (org-fontify-meta-lines-and-blocks-1 limit)
  5271. (error (message "org-mode fontification error in %S at %d"
  5272. (current-buffer)
  5273. (line-number-at-pos)))))
  5274. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5275. "Fontify #+ lines and blocks."
  5276. (let ((case-fold-search t))
  5277. (when (re-search-forward
  5278. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5279. limit t)
  5280. (let ((beg (match-beginning 0))
  5281. (block-start (match-end 0))
  5282. (block-end nil)
  5283. (lang (match-string 7))
  5284. (beg1 (line-beginning-position 2))
  5285. (dc1 (downcase (match-string 2)))
  5286. (dc3 (downcase (match-string 3)))
  5287. end end1 quoting block-type)
  5288. (cond
  5289. ((and (match-end 4) (equal dc3 "+begin"))
  5290. ;; Truly a block
  5291. (setq block-type (downcase (match-string 5))
  5292. quoting (member block-type org-protecting-blocks))
  5293. (when (re-search-forward
  5294. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5295. nil t) ;; on purpose, we look further than LIMIT
  5296. (setq end (min (point-max) (match-end 0))
  5297. end1 (min (point-max) (1- (match-beginning 0))))
  5298. (setq block-end (match-beginning 0))
  5299. (when quoting
  5300. (org-remove-flyspell-overlays-in beg1 end1)
  5301. (remove-text-properties beg end
  5302. '(display t invisible t intangible t)))
  5303. (add-text-properties
  5304. beg end '(font-lock-fontified t font-lock-multiline t))
  5305. (add-text-properties beg beg1 '(face org-meta-line))
  5306. (org-remove-flyspell-overlays-in beg beg1)
  5307. (add-text-properties ; For end_src
  5308. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5309. (org-remove-flyspell-overlays-in end1 end)
  5310. (cond
  5311. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5312. (org-src-font-lock-fontify-block lang block-start block-end)
  5313. (add-text-properties beg1 block-end '(src-block t)))
  5314. (quoting
  5315. (add-text-properties beg1 (min (point-max) (1+ end1))
  5316. (list 'face
  5317. (list :inherit
  5318. (let ((face-name
  5319. (intern (format "org-block-%s" lang))))
  5320. (append (and (facep face-name) (list face-name))
  5321. '(org-block))))))) ; end of source block
  5322. ((not org-fontify-quote-and-verse-blocks))
  5323. ((string= block-type "quote")
  5324. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5325. ((string= block-type "verse")
  5326. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5327. (add-text-properties beg beg1 '(face org-block-begin-line))
  5328. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5329. '(face org-block-end-line))
  5330. t))
  5331. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5332. (org-remove-flyspell-overlays-in
  5333. (match-beginning 0)
  5334. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5335. (add-text-properties
  5336. beg (match-end 3)
  5337. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5338. '(font-lock-fontified t invisible t)
  5339. '(font-lock-fontified t face org-document-info-keyword)))
  5340. (add-text-properties
  5341. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5342. (if (string-equal dc1 "+title:")
  5343. '(font-lock-fontified t face org-document-title)
  5344. '(font-lock-fontified t face org-document-info))))
  5345. ((string-prefix-p "+caption" dc1)
  5346. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5347. (remove-text-properties (match-beginning 0) (match-end 0)
  5348. '(display t invisible t intangible t))
  5349. ;; Handle short captions.
  5350. (save-excursion
  5351. (beginning-of-line)
  5352. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5353. (add-text-properties (line-beginning-position) (match-end 1)
  5354. '(font-lock-fontified t face org-meta-line))
  5355. (add-text-properties (match-end 0) (line-end-position)
  5356. '(font-lock-fontified t face org-block))
  5357. t)
  5358. ((member dc3 '(" " ""))
  5359. (org-remove-flyspell-overlays-in beg (match-end 0))
  5360. (add-text-properties
  5361. beg (match-end 0)
  5362. '(font-lock-fontified t face font-lock-comment-face)))
  5363. (t ;; just any other in-buffer setting, but not indented
  5364. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5365. (remove-text-properties (match-beginning 0) (match-end 0)
  5366. '(display t invisible t intangible t))
  5367. (add-text-properties beg (match-end 0)
  5368. '(font-lock-fontified t face org-meta-line))
  5369. t))))))
  5370. (defun org-fontify-drawers (limit)
  5371. "Fontify drawers."
  5372. (when (re-search-forward org-drawer-regexp limit t)
  5373. (add-text-properties
  5374. (match-beginning 0) (match-end 0)
  5375. '(font-lock-fontified t face org-special-keyword))
  5376. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5377. t))
  5378. (defun org-fontify-macros (limit)
  5379. "Fontify macros."
  5380. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5381. (add-text-properties
  5382. (match-beginning 0) (match-end 0)
  5383. '(font-lock-fontified t face org-macro))
  5384. (when org-hide-macro-markers
  5385. (add-text-properties (match-end 2) (match-beginning 2)
  5386. '(invisible t))
  5387. (add-text-properties (match-beginning 1) (match-end 1)
  5388. '(invisible t)))
  5389. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5390. t))
  5391. (defun org-activate-angle-links (limit)
  5392. "Add text properties for angle links."
  5393. (when (and (re-search-forward org-angle-link-re limit t)
  5394. (not (org-in-src-block-p)))
  5395. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5396. (add-text-properties (match-beginning 0) (match-end 0)
  5397. (list 'mouse-face 'highlight
  5398. 'keymap org-mouse-map
  5399. 'font-lock-multiline t))
  5400. (org-rear-nonsticky-at (match-end 0))
  5401. t))
  5402. (defun org-activate-footnote-links (limit)
  5403. "Add text properties for footnotes."
  5404. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5405. (when fn
  5406. (let* ((beg (nth 1 fn))
  5407. (end (nth 2 fn))
  5408. (label (car fn))
  5409. (referencep (/= (line-beginning-position) beg)))
  5410. (when (and referencep (nth 3 fn))
  5411. (save-excursion
  5412. (goto-char beg)
  5413. (search-forward (or label "fn:"))
  5414. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5415. (add-text-properties beg end
  5416. (list 'mouse-face 'highlight
  5417. 'keymap org-mouse-map
  5418. 'help-echo
  5419. (if referencep "Footnote reference"
  5420. "Footnote definition")
  5421. 'font-lock-fontified t
  5422. 'font-lock-multiline t
  5423. 'face 'org-footnote))))))
  5424. (defun org-activate-bracket-links (limit)
  5425. "Add text properties for bracketed links."
  5426. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5427. (not (org-in-src-block-p)))
  5428. (let* ((hl (save-match-data
  5429. (org-link-expand-abbrev (match-string-no-properties 1))))
  5430. (type (save-match-data
  5431. (and (string-match org-plain-link-re hl)
  5432. (match-string-no-properties 1 hl))))
  5433. (path (save-match-data
  5434. (and (string-match org-plain-link-re hl)
  5435. (match-string-no-properties 2 hl))))
  5436. (link-start (match-beginning 0))
  5437. (link-end (match-end 0))
  5438. (bracketp t)
  5439. (help-echo (org-link-get-parameter type :help-echo))
  5440. (help (cond
  5441. ((stringp help-echo)
  5442. help-echo)
  5443. ((functionp help-echo)
  5444. help-echo)
  5445. (t
  5446. (concat "LINK: "
  5447. (save-match-data
  5448. (org-link-unescape hl))))))
  5449. (link-face (org-link-get-parameter type :face))
  5450. (face (cond
  5451. ;; A function that returns a face
  5452. ((functionp link-face)
  5453. (funcall link-face path))
  5454. ;; a face
  5455. ((facep link-face)
  5456. link-face)
  5457. ;; An anonymous face
  5458. ((consp link-face)
  5459. link-face)
  5460. ;; default
  5461. (t
  5462. 'org-link)))
  5463. (keymap (or (org-link-get-parameter type :keymap)
  5464. org-mouse-map))
  5465. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5466. 'highlight))
  5467. (htmlize (org-link-get-parameter type :htmlize-link))
  5468. (htmlize-link (cond
  5469. ((functionp htmlize)
  5470. (funcall htmlize))
  5471. (t
  5472. `(:uri ,(format "%s:%s" type path)))))
  5473. (activate-func (org-link-get-parameter type :activate-func))
  5474. ;; invisible part
  5475. (ip (list 'invisible (or
  5476. (org-link-get-parameter type :display)
  5477. 'org-link)
  5478. 'face face
  5479. 'keymap keymap
  5480. 'mouse-face mouse-face
  5481. 'font-lock-multiline t
  5482. 'help-echo help
  5483. 'htmlize-link htmlize-link))
  5484. ;; visible part
  5485. (vp (list 'keymap keymap
  5486. 'face face
  5487. 'mouse-face mouse-face
  5488. 'font-lock-multiline t
  5489. 'help-echo help
  5490. 'htmlize-link htmlize-link)))
  5491. ;; We need to remove the invisible property here. Table narrowing
  5492. ;; may have made some of this invisible.
  5493. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5494. (remove-text-properties (match-beginning 0) (match-end 0)
  5495. '(invisible nil))
  5496. (if (match-end 3)
  5497. (progn
  5498. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5499. (org-rear-nonsticky-at (match-beginning 3))
  5500. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5501. (org-rear-nonsticky-at (match-end 3))
  5502. (add-text-properties (match-end 3) (match-end 0) ip)
  5503. (org-rear-nonsticky-at (match-end 0)))
  5504. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5505. (org-rear-nonsticky-at (match-beginning 1))
  5506. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5507. (org-rear-nonsticky-at (match-end 1))
  5508. (add-text-properties (match-end 1) (match-end 0) ip)
  5509. (org-rear-nonsticky-at (match-end 0)))
  5510. (when activate-func
  5511. (funcall activate-func link-start link-end path bracketp))
  5512. t)))
  5513. (defun org-activate-dates (limit)
  5514. "Add text properties for dates."
  5515. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5516. (not (equal (char-before (match-beginning 0)) 91)))
  5517. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5518. (add-text-properties (match-beginning 0) (match-end 0)
  5519. (list 'mouse-face 'highlight
  5520. 'keymap org-mouse-map))
  5521. (org-rear-nonsticky-at (match-end 0))
  5522. (when org-display-custom-times
  5523. (if (match-end 3)
  5524. (org-display-custom-time (match-beginning 3) (match-end 3))
  5525. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5526. t))
  5527. (defvar-local org-target-link-regexp nil
  5528. "Regular expression matching radio targets in plain text.")
  5529. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5530. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5531. border border border))
  5532. "Regular expression matching a link target.")
  5533. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5534. "Regular expression matching a radio target.")
  5535. (defconst org-any-target-regexp
  5536. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5537. "Regular expression matching any target.")
  5538. (defun org-activate-target-links (limit)
  5539. "Add text properties for target matches."
  5540. (when org-target-link-regexp
  5541. (let ((case-fold-search t))
  5542. (when (re-search-forward org-target-link-regexp limit t)
  5543. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5544. (add-text-properties (match-beginning 1) (match-end 1)
  5545. (list 'mouse-face 'highlight
  5546. 'keymap org-mouse-map
  5547. 'help-echo "Radio target link"
  5548. 'org-linked-text t))
  5549. (org-rear-nonsticky-at (match-end 1))
  5550. t))))
  5551. (defun org-update-radio-target-regexp ()
  5552. "Find all radio targets in this file and update the regular expression.
  5553. Also refresh fontification if needed."
  5554. (interactive)
  5555. (let ((old-regexp org-target-link-regexp)
  5556. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5557. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5558. (targets
  5559. (org-with-wide-buffer
  5560. (goto-char (point-min))
  5561. (let (rtn)
  5562. (while (re-search-forward org-radio-target-regexp nil t)
  5563. ;; Make sure point is really within the object.
  5564. (backward-char)
  5565. (let ((obj (org-element-context)))
  5566. (when (eq (org-element-type obj) 'radio-target)
  5567. (cl-pushnew (org-element-property :value obj) rtn
  5568. :test #'equal))))
  5569. rtn))))
  5570. (setq org-target-link-regexp
  5571. (and targets
  5572. (concat before-re
  5573. (mapconcat
  5574. (lambda (x)
  5575. (replace-regexp-in-string
  5576. " +" "\\s-+" (regexp-quote x) t t))
  5577. targets
  5578. "\\|")
  5579. after-re)))
  5580. (unless (equal old-regexp org-target-link-regexp)
  5581. ;; Clean-up cache.
  5582. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5583. ((not org-target-link-regexp) old-regexp)
  5584. (t
  5585. (concat before-re
  5586. (mapconcat
  5587. (lambda (re)
  5588. (substring re (length before-re)
  5589. (- (length after-re))))
  5590. (list old-regexp org-target-link-regexp)
  5591. "\\|")
  5592. after-re)))))
  5593. (org-with-wide-buffer
  5594. (goto-char (point-min))
  5595. (while (re-search-forward regexp nil t)
  5596. (org-element-cache-refresh (match-beginning 1)))))
  5597. ;; Re fontify buffer.
  5598. (when (memq 'radio org-highlight-links)
  5599. (org-restart-font-lock)))))
  5600. (defun org-hide-wide-columns (limit)
  5601. (let (s e)
  5602. (setq s (text-property-any (point) (or limit (point-max))
  5603. 'org-cwidth t))
  5604. (when s
  5605. (setq e (next-single-property-change s 'org-cwidth))
  5606. (add-text-properties s e '(invisible org-cwidth))
  5607. (goto-char e)
  5608. t)))
  5609. (defvar org-latex-and-related-regexp nil
  5610. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5611. (defun org-compute-latex-and-related-regexp ()
  5612. "Compute regular expression for LaTeX, entities and sub/superscript.
  5613. Result depends on variable `org-highlight-latex-and-related'."
  5614. (setq-local
  5615. org-latex-and-related-regexp
  5616. (let* ((re-sub
  5617. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5618. ((eq org-use-sub-superscripts '{})
  5619. (list org-match-substring-with-braces-regexp))
  5620. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5621. (re-latex
  5622. (when (memq 'latex org-highlight-latex-and-related)
  5623. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5624. (delq nil
  5625. (mapcar (lambda (x)
  5626. (and (member (car x) matchers) (nth 1 x)))
  5627. org-latex-regexps)))))
  5628. (re-entities
  5629. (when (memq 'entities org-highlight-latex-and-related)
  5630. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5631. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5632. (defun org-do-latex-and-related (limit)
  5633. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5634. LIMIT bounds the search for syntax to highlight. Stop at first
  5635. highlighted object, if any. Return t if some highlighting was
  5636. done, nil otherwise."
  5637. (when (org-string-nw-p org-latex-and-related-regexp)
  5638. (catch 'found
  5639. (while (re-search-forward org-latex-and-related-regexp limit t)
  5640. (unless
  5641. (cl-some
  5642. (lambda (f)
  5643. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5644. (save-excursion
  5645. (goto-char (1+ (match-beginning 0)))
  5646. (face-at-point nil t)))
  5647. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5648. '(?_ ?^))
  5649. 1
  5650. 0)))
  5651. (font-lock-prepend-text-property
  5652. (+ offset (match-beginning 0)) (match-end 0)
  5653. 'face 'org-latex-and-related)
  5654. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5655. '(font-lock-multiline t)))
  5656. (throw 'found t)))
  5657. nil)))
  5658. (defun org-restart-font-lock ()
  5659. "Restart `font-lock-mode', to force refontification."
  5660. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5661. (font-lock-mode -1)
  5662. (font-lock-mode 1)))
  5663. (defun org-activate-tags (limit)
  5664. (when (re-search-forward
  5665. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5666. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5667. (add-text-properties (match-beginning 1) (match-end 1)
  5668. (list 'mouse-face 'highlight
  5669. 'keymap org-mouse-map))
  5670. (org-rear-nonsticky-at (match-end 1))
  5671. t))
  5672. (defun org-outline-level ()
  5673. "Compute the outline level of the heading at point.
  5674. If this is called at a normal headline, the level is the number
  5675. of stars. Use `org-reduced-level' to remove the effect of
  5676. `org-odd-levels'. Unlike to `org-current-level', this function
  5677. takes into consideration inlinetasks."
  5678. (org-with-wide-buffer
  5679. (end-of-line)
  5680. (if (re-search-backward org-outline-regexp-bol nil t)
  5681. (1- (- (match-end 0) (match-beginning 0)))
  5682. 0)))
  5683. (defvar org-font-lock-keywords nil)
  5684. (defsubst org-re-property (property &optional literal allow-null value)
  5685. "Return a regexp matching a PROPERTY line.
  5686. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5687. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5688. non-nil, match properties even without a value.
  5689. Match group 3 is set to the value when it exists. If there is no
  5690. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5691. With optional argument VALUE, match only property lines with
  5692. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5693. unless LITERAL is non-nil."
  5694. (concat
  5695. "^\\(?4:[ \t]*\\)"
  5696. (format "\\(?1::\\(?2:%s\\):\\)"
  5697. (if literal property (regexp-quote property)))
  5698. (cond (value
  5699. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5700. (if literal value (regexp-quote value))))
  5701. (allow-null
  5702. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5703. (t
  5704. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5705. (defconst org-property-re
  5706. (org-re-property "\\S-+" 'literal t)
  5707. "Regular expression matching a property line.
  5708. There are four matching groups:
  5709. 1: :PROPKEY: including the leading and trailing colon,
  5710. 2: PROPKEY without the leading and trailing colon,
  5711. 3: PROPVAL without leading or trailing spaces,
  5712. 4: the indentation of the current line,
  5713. 5: trailing whitespace.")
  5714. (defvar org-font-lock-hook nil
  5715. "Functions to be called for special font lock stuff.")
  5716. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5717. (defvar org-font-lock-set-keywords-hook nil
  5718. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5719. This is called after `org-font-lock-extra-keywords' is defined, but before
  5720. it is installed to be used by font lock. This can be useful if something
  5721. needs to be inserted at a specific position in the font-lock sequence.")
  5722. (defun org-font-lock-hook (limit)
  5723. "Run `org-font-lock-hook' within LIMIT."
  5724. (run-hook-with-args 'org-font-lock-hook limit))
  5725. (defun org-set-font-lock-defaults ()
  5726. "Set font lock defaults for the current buffer."
  5727. (let* ((em org-fontify-emphasized-text)
  5728. (lk org-highlight-links)
  5729. (org-font-lock-extra-keywords
  5730. (list
  5731. ;; Call the hook
  5732. '(org-font-lock-hook)
  5733. ;; Headlines
  5734. `(,(if org-fontify-whole-heading-line
  5735. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5736. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5737. (1 (org-get-level-face 1))
  5738. (2 (org-get-level-face 2))
  5739. (3 (org-get-level-face 3)))
  5740. ;; Table lines
  5741. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5742. (1 'org-table t))
  5743. ;; Table internals
  5744. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5745. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5746. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5747. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5748. ;; Drawers
  5749. '(org-fontify-drawers)
  5750. ;; Properties
  5751. (list org-property-re
  5752. '(1 'org-special-keyword t)
  5753. '(3 'org-property-value t))
  5754. ;; Links
  5755. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5756. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5757. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5758. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5759. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5760. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5761. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5762. ;; Targets.
  5763. (list org-any-target-regexp '(0 'org-target t))
  5764. ;; Diary sexps.
  5765. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5766. ;; Macro
  5767. '(org-fontify-macros)
  5768. '(org-hide-wide-columns (0 nil append))
  5769. ;; TODO keyword
  5770. (list (format org-heading-keyword-regexp-format
  5771. org-todo-regexp)
  5772. '(2 (org-get-todo-face 2) t))
  5773. ;; DONE
  5774. (if org-fontify-done-headline
  5775. (list (format org-heading-keyword-regexp-format
  5776. (concat
  5777. "\\(?:"
  5778. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5779. "\\)"))
  5780. '(2 'org-headline-done t))
  5781. nil)
  5782. ;; Priorities
  5783. '(org-font-lock-add-priority-faces)
  5784. ;; Tags
  5785. '(org-font-lock-add-tag-faces)
  5786. ;; Tags groups
  5787. (when (and org-group-tags org-tag-groups-alist)
  5788. (list (concat org-outline-regexp-bol ".+\\(:"
  5789. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5790. ":\\).*$")
  5791. '(1 'org-tag-group prepend)))
  5792. ;; Special keywords
  5793. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5794. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5795. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5796. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5797. ;; Emphasis
  5798. (when em '(org-do-emphasis-faces))
  5799. ;; Checkboxes
  5800. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5801. 1 'org-checkbox prepend)
  5802. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5803. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5804. (0 (org-get-checkbox-statistics-face) t)))
  5805. ;; Description list items
  5806. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5807. 1 'org-list-dt prepend)
  5808. ;; ARCHIVEd headings
  5809. (list (concat
  5810. org-outline-regexp-bol
  5811. "\\(.*:" org-archive-tag ":.*\\)")
  5812. '(1 'org-archived prepend))
  5813. ;; Specials
  5814. '(org-do-latex-and-related)
  5815. '(org-fontify-entities)
  5816. '(org-raise-scripts)
  5817. ;; Code
  5818. '(org-activate-code (1 'org-code t))
  5819. ;; COMMENT
  5820. (list (format
  5821. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5822. org-todo-regexp
  5823. org-comment-string)
  5824. '(9 'org-special-keyword t))
  5825. ;; Blocks and meta lines
  5826. '(org-fontify-meta-lines-and-blocks))))
  5827. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5828. (run-hooks 'org-font-lock-set-keywords-hook)
  5829. ;; Now set the full font-lock-keywords
  5830. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5831. (setq-local font-lock-defaults
  5832. '(org-font-lock-keywords t nil nil backward-paragraph))
  5833. (kill-local-variable 'font-lock-keywords)
  5834. nil))
  5835. (defun org-toggle-pretty-entities ()
  5836. "Toggle the composition display of entities as UTF8 characters."
  5837. (interactive)
  5838. (setq-local org-pretty-entities (not org-pretty-entities))
  5839. (org-restart-font-lock)
  5840. (if org-pretty-entities
  5841. (message "Entities are now displayed as UTF8 characters")
  5842. (save-restriction
  5843. (widen)
  5844. (decompose-region (point-min) (point-max))
  5845. (message "Entities are now displayed as plain text"))))
  5846. (defvar-local org-custom-properties-overlays nil
  5847. "List of overlays used for custom properties.")
  5848. (defun org-toggle-custom-properties-visibility ()
  5849. "Display or hide properties in `org-custom-properties'."
  5850. (interactive)
  5851. (if org-custom-properties-overlays
  5852. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5853. (setq org-custom-properties-overlays nil))
  5854. (when org-custom-properties
  5855. (org-with-wide-buffer
  5856. (goto-char (point-min))
  5857. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5858. (while (re-search-forward regexp nil t)
  5859. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5860. (when (and end (< (point) end))
  5861. ;; Hide first custom property in current drawer.
  5862. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5863. (overlay-put o 'invisible t)
  5864. (overlay-put o 'org-custom-property t)
  5865. (push o org-custom-properties-overlays))
  5866. ;; Hide additional custom properties in the same drawer.
  5867. (while (re-search-forward regexp end t)
  5868. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5869. (overlay-put o 'invisible t)
  5870. (overlay-put o 'org-custom-property t)
  5871. (push o org-custom-properties-overlays)))))
  5872. ;; Each entry is limited to a single property drawer.
  5873. (outline-next-heading)))))))
  5874. (defun org-fontify-entities (limit)
  5875. "Find an entity to fontify."
  5876. (let (ee)
  5877. (when org-pretty-entities
  5878. (catch 'match
  5879. ;; "\_ "-family is left out on purpose. Only the first one,
  5880. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5881. ;; confusing when adding a second white space character.
  5882. (while (re-search-forward
  5883. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5884. limit t)
  5885. (when (and (not (org-at-comment-p))
  5886. (setq ee (org-entity-get (match-string 1)))
  5887. (= (length (nth 6 ee)) 1))
  5888. (let* ((end (if (equal (match-string 2) "{}")
  5889. (match-end 2)
  5890. (match-end 1))))
  5891. (add-text-properties
  5892. (match-beginning 0) end
  5893. (list 'font-lock-fontified t))
  5894. (compose-region (match-beginning 0) end
  5895. (nth 6 ee) nil)
  5896. (backward-char 1)
  5897. (throw 'match t))))
  5898. nil))))
  5899. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5900. "Fontify string S like in Org mode."
  5901. (with-temp-buffer
  5902. (insert s)
  5903. (let ((org-odd-levels-only odd-levels))
  5904. (org-mode)
  5905. (org-font-lock-ensure)
  5906. (buffer-string))))
  5907. (defvar org-m nil)
  5908. (defvar org-l nil)
  5909. (defvar org-f nil)
  5910. (defun org-get-level-face (n)
  5911. "Get the right face for match N in font-lock matching of headlines."
  5912. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5913. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5914. (if org-cycle-level-faces
  5915. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5916. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5917. (cond
  5918. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5919. ((eq n 2) org-f)
  5920. (t (unless org-level-color-stars-only org-f))))
  5921. (defun org-face-from-face-or-color (context inherit face-or-color)
  5922. "Create a face list that inherits INHERIT, but sets the foreground color.
  5923. When FACE-OR-COLOR is not a string, just return it."
  5924. (if (stringp face-or-color)
  5925. (list :inherit inherit
  5926. (cdr (assoc context org-faces-easy-properties))
  5927. face-or-color)
  5928. face-or-color))
  5929. (defun org-get-todo-face (kwd)
  5930. "Get the right face for a TODO keyword KWD.
  5931. If KWD is a number, get the corresponding match group."
  5932. (when (numberp kwd) (setq kwd (match-string kwd)))
  5933. (or (org-face-from-face-or-color
  5934. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5935. (and (member kwd org-done-keywords) 'org-done)
  5936. 'org-todo))
  5937. (defun org-get-priority-face (priority)
  5938. "Get the right face for PRIORITY.
  5939. PRIORITY is a character."
  5940. (or (org-face-from-face-or-color
  5941. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5942. 'org-priority))
  5943. (defun org-get-tag-face (tag)
  5944. "Get the right face for TAG.
  5945. If TAG is a number, get the corresponding match group."
  5946. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5947. (or (org-face-from-face-or-color
  5948. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5949. 'org-tag)))
  5950. (defun org-font-lock-add-priority-faces (limit)
  5951. "Add the special priority faces."
  5952. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5953. (add-text-properties
  5954. (match-beginning 1) (match-end 1)
  5955. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5956. 'font-lock-fontified t))))
  5957. (defun org-font-lock-add-tag-faces (limit)
  5958. "Add the special tag faces."
  5959. (when (and org-tag-faces org-tags-special-faces-re)
  5960. (while (re-search-forward org-tags-special-faces-re limit t)
  5961. (add-text-properties (match-beginning 1) (match-end 1)
  5962. (list 'face (org-get-tag-face 1)
  5963. 'font-lock-fontified t))
  5964. (backward-char 1))))
  5965. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5966. "Remove fontification and activation overlays from links."
  5967. (font-lock-default-unfontify-region beg end)
  5968. (let* ((buffer-undo-list t)
  5969. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5970. (inhibit-modification-hooks t)
  5971. deactivate-mark buffer-file-name buffer-file-truename)
  5972. (decompose-region beg end)
  5973. (remove-text-properties beg end
  5974. '(mouse-face t keymap t org-linked-text t
  5975. invisible t intangible t
  5976. org-emphasis t))
  5977. (org-remove-font-lock-display-properties beg end)))
  5978. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5979. ((raise 0.3) (height 0.7))
  5980. ((raise -0.5))
  5981. ((raise 0.5)))
  5982. "Display properties for showing superscripts and subscripts.")
  5983. (defun org-remove-font-lock-display-properties (beg end)
  5984. "Remove specific display properties that have been added by font lock.
  5985. The will remove the raise properties that are used to show superscripts
  5986. and subscripts."
  5987. (let (next prop)
  5988. (while (< beg end)
  5989. (setq next (next-single-property-change beg 'display nil end)
  5990. prop (get-text-property beg 'display))
  5991. (when (member prop org-script-display)
  5992. (put-text-property beg next 'display nil))
  5993. (setq beg next))))
  5994. (defun org-raise-scripts (limit)
  5995. "Add raise properties to sub/superscripts."
  5996. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5997. (re-search-forward
  5998. (if (eq org-use-sub-superscripts t)
  5999. org-match-substring-regexp
  6000. org-match-substring-with-braces-regexp)
  6001. limit t))
  6002. (let* ((pos (point)) table-p comment-p
  6003. (mpos (match-beginning 3))
  6004. (emph-p (get-text-property mpos 'org-emphasis))
  6005. (link-p (get-text-property mpos 'mouse-face))
  6006. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  6007. (goto-char (point-at-bol))
  6008. (setq table-p (looking-at-p org-table-dataline-regexp)
  6009. comment-p (looking-at-p "^[ \t]*#[ +]"))
  6010. (goto-char pos)
  6011. ;; Handle a_b^c
  6012. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  6013. (unless (or comment-p emph-p link-p keyw-p)
  6014. (put-text-property (match-beginning 3) (match-end 0)
  6015. 'display
  6016. (if (equal (char-after (match-beginning 2)) ?^)
  6017. (nth (if table-p 3 1) org-script-display)
  6018. (nth (if table-p 2 0) org-script-display)))
  6019. (add-text-properties (match-beginning 2) (match-end 2)
  6020. (list 'invisible t
  6021. 'org-dwidth t 'org-dwidth-n 1))
  6022. (if (and (eq (char-after (match-beginning 3)) ?{)
  6023. (eq (char-before (match-end 3)) ?}))
  6024. (progn
  6025. (add-text-properties
  6026. (match-beginning 3) (1+ (match-beginning 3))
  6027. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6028. (add-text-properties
  6029. (1- (match-end 3)) (match-end 3)
  6030. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6031. t)))
  6032. ;;;; Visibility cycling, including org-goto and indirect buffer
  6033. ;;; Cycling
  6034. (defvar-local org-cycle-global-status nil)
  6035. (put 'org-cycle-global-status 'org-state t)
  6036. (defvar-local org-cycle-subtree-status nil)
  6037. (put 'org-cycle-subtree-status 'org-state t)
  6038. (defvar org-inlinetask-min-level)
  6039. (defun org-unlogged-message (&rest args)
  6040. "Display a message, but avoid logging it in the *Messages* buffer."
  6041. (let ((message-log-max nil))
  6042. (apply 'message args)))
  6043. ;;;###autoload
  6044. (defun org-cycle (&optional arg)
  6045. "TAB-action and visibility cycling for Org mode.
  6046. This is the command invoked in Org mode by the `TAB' key. Its main
  6047. purpose is outline visibility cycling, but it also invokes other actions
  6048. in special contexts.
  6049. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6050. the entire
  6051. buffer through 3 states (global cycling)
  6052. 1. OVERVIEW: Show only top-level headlines.
  6053. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6054. 3. SHOW ALL: Show everything.
  6055. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6056. switch to the startup visibility,
  6057. determined by the variable `org-startup-folded', and by any VISIBILITY
  6058. properties in the buffer.
  6059. With a `\\[universal-argument] \\[universal-argument] \
  6060. \\[universal-argument]' prefix argument, show the entire buffer, including
  6061. any drawers.
  6062. When inside a table, re-align the table and move to the next field.
  6063. When point is at the beginning of a headline, rotate the subtree started
  6064. by this line through 3 different states (local cycling)
  6065. 1. FOLDED: Only the main headline is shown.
  6066. 2. CHILDREN: The main headline and the direct children are shown.
  6067. From this state, you can move to one of the children
  6068. and zoom in further.
  6069. 3. SUBTREE: Show the entire subtree, including body text.
  6070. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6071. When point is at the beginning of an empty headline and the variable
  6072. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6073. of the headline by demoting and promoting it to likely levels. This
  6074. speeds up creation document structure by pressing `TAB' once or several
  6075. times right after creating a new headline.
  6076. When there is a numeric prefix, go up to a heading with level ARG, do
  6077. a `show-subtree' and return to the previous cursor position. If ARG
  6078. is negative, go up that many levels.
  6079. When point is not at the beginning of a headline, execute the global
  6080. binding for `TAB', which is re-indenting the line. See the option
  6081. `org-cycle-emulate-tab' for details.
  6082. As a special case, if point is at the beginning of the buffer and there is
  6083. no headline in line 1, this function will act as if called with prefix arg
  6084. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6085. prefix arg, but only
  6086. if the variable `org-cycle-global-at-bob' is t."
  6087. (interactive "P")
  6088. (org-load-modules-maybe)
  6089. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6090. (and org-cycle-level-after-item/entry-creation
  6091. (or (org-cycle-level)
  6092. (org-cycle-item-indentation))))
  6093. (let* ((limit-level
  6094. (or org-cycle-max-level
  6095. (and (boundp 'org-inlinetask-min-level)
  6096. org-inlinetask-min-level
  6097. (1- org-inlinetask-min-level))))
  6098. (nstars (and limit-level
  6099. (if org-odd-levels-only
  6100. (and limit-level (1- (* limit-level 2)))
  6101. limit-level)))
  6102. (org-outline-regexp
  6103. (if (not (derived-mode-p 'org-mode))
  6104. outline-regexp
  6105. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6106. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6107. (not (looking-at org-outline-regexp))))
  6108. (org-cycle-hook
  6109. (if bob-special
  6110. (delq 'org-optimize-window-after-visibility-change
  6111. (copy-sequence org-cycle-hook))
  6112. org-cycle-hook))
  6113. (pos (point)))
  6114. (cond
  6115. ((equal arg '(16))
  6116. (setq last-command 'dummy)
  6117. (org-set-startup-visibility)
  6118. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6119. ((equal arg '(64))
  6120. (outline-show-all)
  6121. (org-unlogged-message "Entire buffer visible, including drawers"))
  6122. ((equal arg '(4)) (org-cycle-internal-global))
  6123. ;; Try hiding block at point.
  6124. ((org-hide-block-toggle-maybe))
  6125. ;; Try cdlatex TAB completion
  6126. ((org-try-cdlatex-tab))
  6127. ;; Table: enter it or move to the next field.
  6128. ((org-at-table-p 'any)
  6129. (if (org-at-table.el-p)
  6130. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6131. Use `\\[org-edit-special]' to edit table.el tables"))
  6132. (if arg (org-table-edit-field t)
  6133. (org-table-justify-field-maybe)
  6134. (call-interactively 'org-table-next-field))))
  6135. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6136. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6137. (bob-special (org-cycle-internal-global))
  6138. ;; Drawers: delegate to `org-flag-drawer'.
  6139. ((save-excursion
  6140. (beginning-of-line 1)
  6141. (looking-at org-drawer-regexp))
  6142. (org-flag-drawer ; toggle block visibility
  6143. (not (get-char-property (match-end 0) 'invisible))))
  6144. ;; Show-subtree, ARG levels up from here.
  6145. ((integerp arg)
  6146. (save-excursion
  6147. (org-back-to-heading)
  6148. (outline-up-heading (if (< arg 0) (- arg)
  6149. (- (funcall outline-level) arg)))
  6150. (org-show-subtree)))
  6151. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6152. ((and (featurep 'org-inlinetask)
  6153. (org-inlinetask-at-task-p)
  6154. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6155. (org-inlinetask-toggle-visibility))
  6156. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6157. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6158. (save-excursion (move-beginning-of-line 1)
  6159. (looking-at org-outline-regexp)))
  6160. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6161. (org-cycle-internal-local))
  6162. ;; From there: TAB emulation and template completion.
  6163. (buffer-read-only (org-back-to-heading))
  6164. ((run-hook-with-args-until-success
  6165. 'org-tab-after-check-for-cycling-hook))
  6166. ((org-try-structure-completion))
  6167. ((run-hook-with-args-until-success
  6168. 'org-tab-before-tab-emulation-hook))
  6169. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6170. (or (not (bolp))
  6171. (not (looking-at org-outline-regexp))))
  6172. (call-interactively (global-key-binding "\t")))
  6173. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6174. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6175. (or (and (eq org-cycle-emulate-tab 'white)
  6176. (= (match-end 0) (point-at-eol)))
  6177. (and (eq org-cycle-emulate-tab 'whitestart)
  6178. (>= (match-end 0) pos))))
  6179. t
  6180. (eq org-cycle-emulate-tab t))
  6181. (call-interactively (global-key-binding "\t")))
  6182. (t (save-excursion
  6183. (org-back-to-heading)
  6184. (org-cycle)))))))
  6185. (defun org-cycle-internal-global ()
  6186. "Do the global cycling action."
  6187. ;; Hack to avoid display of messages for .org attachments in Gnus
  6188. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6189. (cond
  6190. ((and (eq last-command this-command)
  6191. (eq org-cycle-global-status 'overview))
  6192. ;; We just created the overview - now do table of contents
  6193. ;; This can be slow in very large buffers, so indicate action
  6194. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6195. (unless ga (org-unlogged-message "CONTENTS..."))
  6196. (org-content)
  6197. (unless ga (org-unlogged-message "CONTENTS...done"))
  6198. (setq org-cycle-global-status 'contents)
  6199. (run-hook-with-args 'org-cycle-hook 'contents))
  6200. ((and (eq last-command this-command)
  6201. (eq org-cycle-global-status 'contents))
  6202. ;; We just showed the table of contents - now show everything
  6203. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6204. (outline-show-all)
  6205. (unless ga (org-unlogged-message "SHOW ALL"))
  6206. (setq org-cycle-global-status 'all)
  6207. (run-hook-with-args 'org-cycle-hook 'all))
  6208. (t
  6209. ;; Default action: go to overview
  6210. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6211. (org-overview)
  6212. (unless ga (org-unlogged-message "OVERVIEW"))
  6213. (setq org-cycle-global-status 'overview)
  6214. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6215. (defvar org-called-with-limited-levels nil
  6216. "Non-nil when `org-with-limited-levels' is currently active.")
  6217. (defun org-cycle-internal-local ()
  6218. "Do the local cycling action."
  6219. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6220. ;; First, determine end of headline (EOH), end of subtree or item
  6221. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6222. (save-excursion
  6223. (if (org-at-item-p)
  6224. (progn
  6225. (beginning-of-line)
  6226. (setq struct (org-list-struct))
  6227. (setq eoh (point-at-eol))
  6228. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6229. (setq has-children (org-list-has-child-p (point) struct)))
  6230. (org-back-to-heading)
  6231. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6232. (setq eos (save-excursion (org-end-of-subtree t t)
  6233. (when (bolp) (backward-char)) (point)))
  6234. (setq has-children
  6235. (or (save-excursion
  6236. (let ((level (funcall outline-level)))
  6237. (outline-next-heading)
  6238. (and (org-at-heading-p t)
  6239. (> (funcall outline-level) level))))
  6240. (save-excursion
  6241. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6242. ;; Determine end invisible part of buffer (EOL)
  6243. (beginning-of-line 2)
  6244. (while (and (not (eobp)) ;This is like `next-line'.
  6245. (get-char-property (1- (point)) 'invisible))
  6246. (goto-char (next-single-char-property-change (point) 'invisible))
  6247. (and (eolp) (beginning-of-line 2)))
  6248. (setq eol (point)))
  6249. ;; Find out what to do next and set `this-command'
  6250. (cond
  6251. ((= eos eoh)
  6252. ;; Nothing is hidden behind this heading
  6253. (unless (org-before-first-heading-p)
  6254. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6255. (org-unlogged-message "EMPTY ENTRY")
  6256. (setq org-cycle-subtree-status nil)
  6257. (save-excursion
  6258. (goto-char eos)
  6259. (outline-next-heading)
  6260. (when (outline-invisible-p) (org-flag-heading nil))))
  6261. ((and (or (>= eol eos)
  6262. (not (string-match "\\S-" (buffer-substring eol eos))))
  6263. (or has-children
  6264. (not (setq children-skipped
  6265. org-cycle-skip-children-state-if-no-children))))
  6266. ;; Entire subtree is hidden in one line: children view
  6267. (unless (org-before-first-heading-p)
  6268. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6269. (if (org-at-item-p)
  6270. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6271. (org-show-entry)
  6272. (org-with-limited-levels (org-show-children))
  6273. ;; FIXME: This slows down the func way too much.
  6274. ;; How keep drawers hidden in subtree anyway?
  6275. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6276. ;; (org-cycle-hide-drawers 'subtree))
  6277. ;; Fold every list in subtree to top-level items.
  6278. (when (eq org-cycle-include-plain-lists 'integrate)
  6279. (save-excursion
  6280. (org-back-to-heading)
  6281. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6282. (beginning-of-line 1)
  6283. (let* ((struct (org-list-struct))
  6284. (prevs (org-list-prevs-alist struct))
  6285. (end (org-list-get-bottom-point struct)))
  6286. (dolist (e (org-list-get-all-items (point) struct prevs))
  6287. (org-list-set-item-visibility e struct 'folded))
  6288. (goto-char (if (< end eos) end eos)))))))
  6289. (org-unlogged-message "CHILDREN")
  6290. (save-excursion
  6291. (goto-char eos)
  6292. (outline-next-heading)
  6293. (when (outline-invisible-p) (org-flag-heading nil)))
  6294. (setq org-cycle-subtree-status 'children)
  6295. (unless (org-before-first-heading-p)
  6296. (run-hook-with-args 'org-cycle-hook 'children)))
  6297. ((or children-skipped
  6298. (and (eq last-command this-command)
  6299. (eq org-cycle-subtree-status 'children)))
  6300. ;; We just showed the children, or no children are there,
  6301. ;; now show everything.
  6302. (unless (org-before-first-heading-p)
  6303. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6304. (outline-flag-region eoh eos nil)
  6305. (org-unlogged-message
  6306. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6307. (setq org-cycle-subtree-status 'subtree)
  6308. (unless (org-before-first-heading-p)
  6309. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6310. (t
  6311. ;; Default action: hide the subtree.
  6312. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6313. (outline-flag-region eoh eos t)
  6314. (org-unlogged-message "FOLDED")
  6315. (setq org-cycle-subtree-status 'folded)
  6316. (unless (org-before-first-heading-p)
  6317. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6318. ;;;###autoload
  6319. (defun org-global-cycle (&optional arg)
  6320. "Cycle the global visibility. For details see `org-cycle'.
  6321. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6322. With a numeric prefix, show all headlines up to that level."
  6323. (interactive "P")
  6324. (let ((org-cycle-include-plain-lists
  6325. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6326. (cond
  6327. ((integerp arg)
  6328. (outline-show-all)
  6329. (outline-hide-sublevels arg)
  6330. (setq org-cycle-global-status 'contents))
  6331. ((equal arg '(4))
  6332. (org-set-startup-visibility)
  6333. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6334. (t
  6335. (org-cycle '(4))))))
  6336. (defun org-set-startup-visibility ()
  6337. "Set the visibility required by startup options and properties."
  6338. (cond
  6339. ((eq org-startup-folded t)
  6340. (org-overview))
  6341. ((eq org-startup-folded 'content)
  6342. (org-content))
  6343. ((or (eq org-startup-folded 'showeverything)
  6344. (eq org-startup-folded nil))
  6345. (outline-show-all)))
  6346. (unless (eq org-startup-folded 'showeverything)
  6347. (when org-hide-block-startup (org-hide-block-all))
  6348. (org-set-visibility-according-to-property 'no-cleanup)
  6349. (org-cycle-hide-archived-subtrees 'all)
  6350. (org-cycle-hide-drawers 'all)
  6351. (org-cycle-show-empty-lines t)))
  6352. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6353. "Switch subtree visibilities according to :VISIBILITY: property."
  6354. (interactive)
  6355. (org-with-wide-buffer
  6356. (goto-char (point-min))
  6357. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6358. (if (not (org-at-property-p)) (outline-next-heading)
  6359. (let ((state (match-string 3)))
  6360. (save-excursion
  6361. (org-back-to-heading t)
  6362. (outline-hide-subtree)
  6363. (org-reveal)
  6364. (cond
  6365. ((equal state "folded")
  6366. (outline-hide-subtree))
  6367. ((equal state "children")
  6368. (org-show-hidden-entry)
  6369. (org-show-children))
  6370. ((equal state "content")
  6371. (save-excursion
  6372. (save-restriction
  6373. (org-narrow-to-subtree)
  6374. (org-content))))
  6375. ((member state '("all" "showall"))
  6376. (outline-show-subtree)))))))
  6377. (unless no-cleanup
  6378. (org-cycle-hide-archived-subtrees 'all)
  6379. (org-cycle-hide-drawers 'all)
  6380. (org-cycle-show-empty-lines 'all))))
  6381. ;; This function uses outline-regexp instead of the more fundamental
  6382. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6383. ;; buffers, where outline-regexp is needed.
  6384. (defun org-overview ()
  6385. "Switch to overview mode, showing only top-level headlines.
  6386. This shows all headlines with a level equal or greater than the level
  6387. of the first headline in the buffer. This is important, because if the
  6388. first headline is not level one, then (hide-sublevels 1) gives confusing
  6389. results."
  6390. (interactive)
  6391. (save-excursion
  6392. (let ((level
  6393. (save-excursion
  6394. (goto-char (point-min))
  6395. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6396. (goto-char (match-beginning 0))
  6397. (funcall outline-level)))))
  6398. (and level (outline-hide-sublevels level)))))
  6399. (defun org-content (&optional arg)
  6400. "Show all headlines in the buffer, like a table of contents.
  6401. With numerical argument N, show content up to level N."
  6402. (interactive "P")
  6403. (org-overview)
  6404. (save-excursion
  6405. ;; Visit all headings and show their offspring
  6406. (and (integerp arg) (org-overview))
  6407. (goto-char (point-max))
  6408. (catch 'exit
  6409. (while (and (progn (condition-case nil
  6410. (outline-previous-visible-heading 1)
  6411. (error (goto-char (point-min))))
  6412. t)
  6413. (looking-at org-outline-regexp))
  6414. (if (integerp arg)
  6415. (org-show-children (1- arg))
  6416. (outline-show-branches))
  6417. (when (bobp) (throw 'exit nil))))))
  6418. (defun org-optimize-window-after-visibility-change (state)
  6419. "Adjust the window after a change in outline visibility.
  6420. This function is the default value of the hook `org-cycle-hook'."
  6421. (when (get-buffer-window (current-buffer))
  6422. (cond
  6423. ((eq state 'content) nil)
  6424. ((eq state 'all) nil)
  6425. ((eq state 'folded) nil)
  6426. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6427. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6428. (defun org-remove-empty-overlays-at (pos)
  6429. "Remove outline overlays that do not contain non-white stuff."
  6430. (dolist (o (overlays-at pos))
  6431. (and (eq 'outline (overlay-get o 'invisible))
  6432. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6433. (overlay-end o))))
  6434. (delete-overlay o))))
  6435. (defun org-clean-visibility-after-subtree-move ()
  6436. "Fix visibility issues after moving a subtree."
  6437. ;; First, find a reasonable region to look at:
  6438. ;; Start two siblings above, end three below
  6439. (let* ((beg (save-excursion
  6440. (and (org-get-last-sibling)
  6441. (org-get-last-sibling))
  6442. (point)))
  6443. (end (save-excursion
  6444. (and (org-get-next-sibling)
  6445. (org-get-next-sibling)
  6446. (org-get-next-sibling))
  6447. (if (org-at-heading-p)
  6448. (point-at-eol)
  6449. (point))))
  6450. (level (looking-at "\\*+"))
  6451. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6452. (save-excursion
  6453. (save-restriction
  6454. (narrow-to-region beg end)
  6455. (when re
  6456. ;; Properly fold already folded siblings
  6457. (goto-char (point-min))
  6458. (while (re-search-forward re nil t)
  6459. (when (and (not (outline-invisible-p))
  6460. (save-excursion
  6461. (goto-char (point-at-eol)) (outline-invisible-p)))
  6462. (outline-hide-entry))))
  6463. (org-cycle-show-empty-lines 'overview)
  6464. (org-cycle-hide-drawers 'overview)))))
  6465. (defun org-cycle-show-empty-lines (state)
  6466. "Show empty lines above all visible headlines.
  6467. The region to be covered depends on STATE when called through
  6468. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6469. entire buffer covered. Note that an empty line is only shown if there
  6470. are at least `org-cycle-separator-lines' empty lines before the headline."
  6471. (when (/= org-cycle-separator-lines 0)
  6472. (save-excursion
  6473. (let* ((n (abs org-cycle-separator-lines))
  6474. (re (cond
  6475. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6476. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6477. (t (let ((ns (number-to-string (- n 2))))
  6478. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6479. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6480. beg end)
  6481. (cond
  6482. ((memq state '(overview contents t))
  6483. (setq beg (point-min) end (point-max)))
  6484. ((memq state '(children folded))
  6485. (setq beg (point)
  6486. end (progn (org-end-of-subtree t t)
  6487. (line-beginning-position 2)))))
  6488. (when beg
  6489. (goto-char beg)
  6490. (while (re-search-forward re end t)
  6491. (unless (get-char-property (match-end 1) 'invisible)
  6492. (let ((e (match-end 1))
  6493. (b (if (>= org-cycle-separator-lines 0)
  6494. (match-beginning 1)
  6495. (save-excursion
  6496. (goto-char (match-beginning 0))
  6497. (skip-chars-backward " \t\n")
  6498. (line-end-position)))))
  6499. (outline-flag-region b e nil))))))))
  6500. ;; Never hide empty lines at the end of the file.
  6501. (save-excursion
  6502. (goto-char (point-max))
  6503. (outline-previous-heading)
  6504. (outline-end-of-heading)
  6505. (when (and (looking-at "[ \t\n]+")
  6506. (= (match-end 0) (point-max)))
  6507. (outline-flag-region (point) (match-end 0) nil))))
  6508. (defun org-show-empty-lines-in-parent ()
  6509. "Move to the parent and re-show empty lines before visible headlines."
  6510. (save-excursion
  6511. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6512. (org-cycle-show-empty-lines context))))
  6513. (defun org-files-list ()
  6514. "Return `org-agenda-files' list, plus all open Org files.
  6515. This is useful for operations that need to scan all of a user's
  6516. open and agenda-wise Org files."
  6517. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6518. (dolist (buf (buffer-list))
  6519. (with-current-buffer buf
  6520. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6521. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6522. files))
  6523. (defsubst org-entry-beginning-position ()
  6524. "Return the beginning position of the current entry."
  6525. (save-excursion (org-back-to-heading t) (point)))
  6526. (defsubst org-entry-end-position ()
  6527. "Return the end position of the current entry."
  6528. (save-excursion (outline-next-heading) (point)))
  6529. (defun org-cycle-hide-drawers (state &optional exceptions)
  6530. "Re-hide all drawers after a visibility state change.
  6531. When non-nil, optional argument EXCEPTIONS is a list of strings
  6532. specifying which drawers should not be hidden."
  6533. (when (and (derived-mode-p 'org-mode)
  6534. (not (memq state '(overview folded contents))))
  6535. (save-excursion
  6536. (let* ((globalp (memq state '(contents all)))
  6537. (beg (if globalp (point-min) (point)))
  6538. (end (if globalp (point-max)
  6539. (if (eq state 'children)
  6540. (save-excursion (outline-next-heading) (point))
  6541. (org-end-of-subtree t)))))
  6542. (goto-char beg)
  6543. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6544. (unless (member-ignore-case (match-string 1) exceptions)
  6545. (let ((drawer (org-element-at-point)))
  6546. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6547. (org-flag-drawer t drawer)
  6548. ;; Make sure to skip drawer entirely or we might flag
  6549. ;; it another time when matching its ending line with
  6550. ;; `org-drawer-regexp'.
  6551. (goto-char (org-element-property :end drawer))))))))))
  6552. (defun org-flag-drawer (flag &optional element)
  6553. "When FLAG is non-nil, hide the drawer we are at.
  6554. Otherwise make it visible. When optional argument ELEMENT is
  6555. a parsed drawer, as returned by `org-element-at-point', hide or
  6556. show that drawer instead."
  6557. (let ((drawer (or element
  6558. (and (save-excursion
  6559. (beginning-of-line)
  6560. (looking-at-p org-drawer-regexp))
  6561. (org-element-at-point)))))
  6562. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6563. (let ((post (org-element-property :post-affiliated drawer)))
  6564. (save-excursion
  6565. (outline-flag-region
  6566. (progn (goto-char post) (line-end-position))
  6567. (progn (goto-char (org-element-property :end drawer))
  6568. (skip-chars-backward " \r\t\n")
  6569. (line-end-position))
  6570. flag))
  6571. ;; When the drawer is hidden away, make sure point lies in
  6572. ;; a visible part of the buffer.
  6573. (when (and flag (> (line-beginning-position) post))
  6574. (goto-char post))))))
  6575. (defun org-subtree-end-visible-p ()
  6576. "Is the end of the current subtree visible?"
  6577. (pos-visible-in-window-p
  6578. (save-excursion (org-end-of-subtree t) (point))))
  6579. (defun org-first-headline-recenter ()
  6580. "Move cursor to the first headline and recenter the headline."
  6581. (let ((window (get-buffer-window)))
  6582. (when window
  6583. (goto-char (point-min))
  6584. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6585. (set-window-start window (line-beginning-position))))))
  6586. ;;; Saving and restoring visibility
  6587. (defun org-outline-overlay-data (&optional use-markers)
  6588. "Return a list of the locations of all outline overlays.
  6589. These are overlays with the `invisible' property value `outline'.
  6590. The return value is a list of cons cells, with start and stop
  6591. positions for each overlay.
  6592. If USE-MARKERS is set, return the positions as markers."
  6593. (let (beg end)
  6594. (org-with-wide-buffer
  6595. (delq nil
  6596. (mapcar (lambda (o)
  6597. (when (eq (overlay-get o 'invisible) 'outline)
  6598. (setq beg (overlay-start o)
  6599. end (overlay-end o))
  6600. (and beg end (> end beg)
  6601. (if use-markers
  6602. (cons (copy-marker beg)
  6603. (copy-marker end t))
  6604. (cons beg end)))))
  6605. (overlays-in (point-min) (point-max)))))))
  6606. (defun org-set-outline-overlay-data (data)
  6607. "Create visibility overlays for all positions in DATA.
  6608. DATA should have been made by `org-outline-overlay-data'."
  6609. (org-with-wide-buffer
  6610. (outline-show-all)
  6611. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6612. ;;; Folding of blocks
  6613. (defvar-local org-hide-block-overlays nil
  6614. "Overlays hiding blocks.")
  6615. (defun org-block-map (function &optional start end)
  6616. "Call FUNCTION at the head of all source blocks in the current buffer.
  6617. Optional arguments START and END can be used to limit the range."
  6618. (let ((start (or start (point-min)))
  6619. (end (or end (point-max))))
  6620. (save-excursion
  6621. (goto-char start)
  6622. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6623. (save-excursion
  6624. (save-match-data
  6625. (goto-char (match-beginning 0))
  6626. (funcall function)))))))
  6627. (defun org-hide-block-toggle-all ()
  6628. "Toggle the visibility of all blocks in the current buffer."
  6629. (org-block-map 'org-hide-block-toggle))
  6630. (defun org-hide-block-all ()
  6631. "Fold all blocks in the current buffer."
  6632. (interactive)
  6633. (org-show-block-all)
  6634. (org-block-map 'org-hide-block-toggle-maybe))
  6635. (defun org-show-block-all ()
  6636. "Unfold all blocks in the current buffer."
  6637. (interactive)
  6638. (mapc #'delete-overlay org-hide-block-overlays)
  6639. (setq org-hide-block-overlays nil))
  6640. (defun org-hide-block-toggle-maybe ()
  6641. "Toggle visibility of block at point.
  6642. Unlike to `org-hide-block-toggle', this function does not throw
  6643. an error. Return a non-nil value when toggling is successful."
  6644. (interactive)
  6645. (ignore-errors (org-hide-block-toggle)))
  6646. (defun org-hide-block-toggle (&optional force)
  6647. "Toggle the visibility of the current block.
  6648. When optional argument FORCE is `off', make block visible. If it
  6649. is non-nil, hide it unconditionally. Throw an error when not at
  6650. a block. Return a non-nil value when toggling is successful."
  6651. (interactive)
  6652. (let ((element (org-element-at-point)))
  6653. (unless (memq (org-element-type element)
  6654. '(center-block comment-block dynamic-block example-block
  6655. export-block quote-block special-block
  6656. src-block verse-block))
  6657. (user-error "Not at a block"))
  6658. (let* ((start (save-excursion
  6659. (goto-char (org-element-property :post-affiliated element))
  6660. (line-end-position)))
  6661. (end (save-excursion
  6662. (goto-char (org-element-property :end element))
  6663. (skip-chars-backward " \r\t\n")
  6664. (line-end-position)))
  6665. (overlays (overlays-at start)))
  6666. (cond
  6667. ;; Do nothing when not before or at the block opening line or
  6668. ;; at the block closing line.
  6669. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6670. ((and (not (eq force 'off))
  6671. (not (memq t (mapcar
  6672. (lambda (o)
  6673. (eq (overlay-get o 'invisible) 'org-hide-block))
  6674. overlays))))
  6675. (let ((ov (make-overlay start end)))
  6676. (overlay-put ov 'invisible 'org-hide-block)
  6677. ;; Make the block accessible to `isearch'.
  6678. (overlay-put
  6679. ov 'isearch-open-invisible
  6680. (lambda (ov)
  6681. (when (memq ov org-hide-block-overlays)
  6682. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6683. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6684. (delete-overlay ov))))
  6685. (push ov org-hide-block-overlays)
  6686. ;; When the block is hidden away, make sure point is left in
  6687. ;; a visible part of the buffer.
  6688. (when (> (line-beginning-position) start)
  6689. (goto-char start)
  6690. (beginning-of-line))
  6691. ;; Signal successful toggling.
  6692. t))
  6693. ((or (not force) (eq force 'off))
  6694. (dolist (ov overlays t)
  6695. (when (memq ov org-hide-block-overlays)
  6696. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6697. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6698. (delete-overlay ov))))))))
  6699. ;; Remove overlays when changing major mode
  6700. (add-hook 'org-mode-hook
  6701. (lambda () (add-hook 'change-major-mode-hook
  6702. 'org-show-block-all 'append 'local)))
  6703. ;;; Org-goto
  6704. (defvar org-goto-window-configuration nil)
  6705. (defvar org-goto-marker nil)
  6706. (defvar org-goto-map)
  6707. (defun org-goto-map ()
  6708. "Set the keymap `org-goto'."
  6709. (setq org-goto-map
  6710. (let ((map (make-sparse-keymap)))
  6711. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6712. mouse-drag-region universal-argument org-occur)))
  6713. (dolist (cmd cmds)
  6714. (substitute-key-definition cmd cmd map global-map)))
  6715. (suppress-keymap map)
  6716. (org-defkey map "\C-m" 'org-goto-ret)
  6717. (org-defkey map [(return)] 'org-goto-ret)
  6718. (org-defkey map [(left)] 'org-goto-left)
  6719. (org-defkey map [(right)] 'org-goto-right)
  6720. (org-defkey map [(control ?g)] 'org-goto-quit)
  6721. (org-defkey map "\C-i" 'org-cycle)
  6722. (org-defkey map [(tab)] 'org-cycle)
  6723. (org-defkey map [(down)] 'outline-next-visible-heading)
  6724. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6725. (if org-goto-auto-isearch
  6726. (if (fboundp 'define-key-after)
  6727. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6728. nil)
  6729. (org-defkey map "q" 'org-goto-quit)
  6730. (org-defkey map "n" 'outline-next-visible-heading)
  6731. (org-defkey map "p" 'outline-previous-visible-heading)
  6732. (org-defkey map "f" 'outline-forward-same-level)
  6733. (org-defkey map "b" 'outline-backward-same-level)
  6734. (org-defkey map "u" 'outline-up-heading))
  6735. (org-defkey map "/" 'org-occur)
  6736. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6737. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6738. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6739. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6740. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6741. map)))
  6742. (defconst org-goto-help
  6743. "Browse buffer copy, to find location or copy text.%s
  6744. RET=jump to location C-g=quit and return to previous location
  6745. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6746. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6747. (defun org-goto (&optional alternative-interface)
  6748. "Look up a different location in the current file, keeping current visibility.
  6749. When you want look-up or go to a different location in a
  6750. document, the fastest way is often to fold the entire buffer and
  6751. then dive into the tree. This method has the disadvantage, that
  6752. the previous location will be folded, which may not be what you
  6753. want.
  6754. This command works around this by showing a copy of the current
  6755. buffer in an indirect buffer, in overview mode. You can dive
  6756. into the tree in that copy, use org-occur and incremental search
  6757. to find a location. When pressing RET or `Q', the command
  6758. returns to the original buffer in which the visibility is still
  6759. unchanged. After RET it will also jump to the location selected
  6760. in the indirect buffer and expose the headline hierarchy above.
  6761. With a prefix argument, use the alternative interface: e.g., if
  6762. `org-goto-interface' is `outline' use `outline-path-completion'."
  6763. (interactive "P")
  6764. (org-goto-map)
  6765. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6766. (org-refile-use-outline-path t)
  6767. (org-refile-target-verify-function nil)
  6768. (interface
  6769. (if (not alternative-interface)
  6770. org-goto-interface
  6771. (if (eq org-goto-interface 'outline)
  6772. 'outline-path-completion
  6773. 'outline)))
  6774. (org-goto-start-pos (point))
  6775. (selected-point
  6776. (if (eq interface 'outline)
  6777. (car (org-get-location (current-buffer) org-goto-help))
  6778. (let ((pa (org-refile-get-location "Goto")))
  6779. (org-refile-check-position pa)
  6780. (nth 3 pa)))))
  6781. (if selected-point
  6782. (progn
  6783. (org-mark-ring-push org-goto-start-pos)
  6784. (goto-char selected-point)
  6785. (when (or (outline-invisible-p) (org-invisible-p2))
  6786. (org-show-context 'org-goto)))
  6787. (message "Quit"))))
  6788. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6789. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6790. (defvar org-goto-local-auto-isearch-map) ; defined below
  6791. (defun org-get-location (_buf help)
  6792. "Let the user select a location in current buffer.
  6793. This function uses a recursive edit. It returns the selected position
  6794. or nil."
  6795. (org-no-popups
  6796. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6797. (isearch-hide-immediately nil)
  6798. (isearch-search-fun-function
  6799. (lambda () 'org-goto-local-search-headings))
  6800. (org-goto-selected-point org-goto-exit-command))
  6801. (save-excursion
  6802. (save-window-excursion
  6803. (delete-other-windows)
  6804. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6805. (pop-to-buffer-same-window
  6806. (condition-case nil
  6807. (make-indirect-buffer (current-buffer) "*org-goto*")
  6808. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6809. (with-output-to-temp-buffer "*Org Help*"
  6810. (princ (format help (if org-goto-auto-isearch
  6811. " Just type for auto-isearch."
  6812. " n/p/f/b/u to navigate, q to quit."))))
  6813. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6814. (setq buffer-read-only nil)
  6815. (let ((org-startup-truncated t)
  6816. (org-startup-folded nil)
  6817. (org-startup-align-all-tables nil))
  6818. (org-mode)
  6819. (org-overview))
  6820. (setq buffer-read-only t)
  6821. (if (and (boundp 'org-goto-start-pos)
  6822. (integer-or-marker-p org-goto-start-pos))
  6823. (progn (goto-char org-goto-start-pos)
  6824. (when (outline-invisible-p)
  6825. (org-show-set-visibility 'lineage)))
  6826. (goto-char (point-min)))
  6827. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6828. (message "Select location and press RET")
  6829. (use-local-map org-goto-map)
  6830. (recursive-edit)))
  6831. (kill-buffer "*org-goto*")
  6832. (cons org-goto-selected-point org-goto-exit-command))))
  6833. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6834. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6835. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6836. (if (fboundp 'isearch-other-control-char)
  6837. (progn
  6838. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6839. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6840. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6841. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6842. (define-key org-goto-local-auto-isearch-map [return] nil))
  6843. (defun org-goto-local-search-headings (string bound noerror)
  6844. "Search and make sure that any matches are in headlines."
  6845. (catch 'return
  6846. (while (if isearch-forward
  6847. (search-forward string bound noerror)
  6848. (search-backward string bound noerror))
  6849. (when (save-match-data
  6850. (and (save-excursion
  6851. (beginning-of-line)
  6852. (looking-at org-complex-heading-regexp))
  6853. (or (not (match-beginning 5))
  6854. (< (point) (match-beginning 5)))))
  6855. (throw 'return (point))))))
  6856. (defun org-goto-local-auto-isearch ()
  6857. "Start isearch."
  6858. (interactive)
  6859. (goto-char (point-min))
  6860. (let ((keys (this-command-keys)))
  6861. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6862. (isearch-mode t)
  6863. (isearch-process-search-char (string-to-char keys)))))
  6864. (defun org-goto-ret (&optional _arg)
  6865. "Finish `org-goto' by going to the new location."
  6866. (interactive "P")
  6867. (setq org-goto-selected-point (point))
  6868. (setq org-goto-exit-command 'return)
  6869. (throw 'exit nil))
  6870. (defun org-goto-left ()
  6871. "Finish `org-goto' by going to the new location."
  6872. (interactive)
  6873. (if (org-at-heading-p)
  6874. (progn
  6875. (beginning-of-line 1)
  6876. (setq org-goto-selected-point (point)
  6877. org-goto-exit-command 'left)
  6878. (throw 'exit nil))
  6879. (user-error "Not on a heading")))
  6880. (defun org-goto-right ()
  6881. "Finish `org-goto' by going to the new location."
  6882. (interactive)
  6883. (if (org-at-heading-p)
  6884. (progn
  6885. (setq org-goto-selected-point (point)
  6886. org-goto-exit-command 'right)
  6887. (throw 'exit nil))
  6888. (user-error "Not on a heading")))
  6889. (defun org-goto-quit ()
  6890. "Finish `org-goto' without cursor motion."
  6891. (interactive)
  6892. (setq org-goto-selected-point nil)
  6893. (setq org-goto-exit-command 'quit)
  6894. (throw 'exit nil))
  6895. ;;; Indirect buffer display of subtrees
  6896. (defvar org-indirect-dedicated-frame nil
  6897. "This is the frame being used for indirect tree display.")
  6898. (defvar org-last-indirect-buffer nil)
  6899. (defun org-tree-to-indirect-buffer (&optional arg)
  6900. "Create indirect buffer and narrow it to current subtree.
  6901. With a numerical prefix ARG, go up to this level and then take that tree.
  6902. If ARG is negative, go up that many levels.
  6903. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6904. indirect buffer previously made with this command, to avoid proliferation of
  6905. indirect buffers. However, when you call the command with a \
  6906. `\\[universal-argument]' prefix, or
  6907. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6908. so that you can work with several indirect buffers at the same time. If
  6909. `org-indirect-buffer-display' is `dedicated-frame', the \
  6910. `\\[universal-argument]' prefix also
  6911. requests that a new frame be made for the new buffer, so that the dedicated
  6912. frame is not changed."
  6913. (interactive "P")
  6914. (let ((cbuf (current-buffer))
  6915. (cwin (selected-window))
  6916. (pos (point))
  6917. beg end level heading ibuf)
  6918. (save-excursion
  6919. (org-back-to-heading t)
  6920. (when (numberp arg)
  6921. (setq level (org-outline-level))
  6922. (when (< arg 0) (setq arg (+ level arg)))
  6923. (while (> (setq level (org-outline-level)) arg)
  6924. (org-up-heading-safe)))
  6925. (setq beg (point)
  6926. heading (org-get-heading 'no-tags))
  6927. (org-end-of-subtree t t)
  6928. (when (org-at-heading-p) (backward-char 1))
  6929. (setq end (point)))
  6930. (when (and (buffer-live-p org-last-indirect-buffer)
  6931. (not (eq org-indirect-buffer-display 'new-frame))
  6932. (not arg))
  6933. (kill-buffer org-last-indirect-buffer))
  6934. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6935. org-last-indirect-buffer ibuf)
  6936. (cond
  6937. ((or (eq org-indirect-buffer-display 'new-frame)
  6938. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6939. (select-frame (make-frame))
  6940. (delete-other-windows)
  6941. (pop-to-buffer-same-window ibuf)
  6942. (org-set-frame-title heading))
  6943. ((eq org-indirect-buffer-display 'dedicated-frame)
  6944. (raise-frame
  6945. (select-frame (or (and org-indirect-dedicated-frame
  6946. (frame-live-p org-indirect-dedicated-frame)
  6947. org-indirect-dedicated-frame)
  6948. (setq org-indirect-dedicated-frame (make-frame)))))
  6949. (delete-other-windows)
  6950. (pop-to-buffer-same-window ibuf)
  6951. (org-set-frame-title (concat "Indirect: " heading)))
  6952. ((eq org-indirect-buffer-display 'current-window)
  6953. (pop-to-buffer-same-window ibuf))
  6954. ((eq org-indirect-buffer-display 'other-window)
  6955. (pop-to-buffer ibuf))
  6956. (t (error "Invalid value")))
  6957. (narrow-to-region beg end)
  6958. (outline-show-all)
  6959. (goto-char pos)
  6960. (run-hook-with-args 'org-cycle-hook 'all)
  6961. (and (window-live-p cwin) (select-window cwin))))
  6962. (defun org-get-indirect-buffer (&optional buffer heading)
  6963. (setq buffer (or buffer (current-buffer)))
  6964. (let ((n 1) (base (buffer-name buffer)) bname)
  6965. (while (buffer-live-p
  6966. (get-buffer
  6967. (setq bname
  6968. (concat base "-"
  6969. (if heading (concat heading "-" (number-to-string n))
  6970. (number-to-string n))))))
  6971. (setq n (1+ n)))
  6972. (condition-case nil
  6973. (make-indirect-buffer buffer bname 'clone)
  6974. (error (make-indirect-buffer buffer bname)))))
  6975. (defun org-set-frame-title (title)
  6976. "Set the title of the current frame to the string TITLE."
  6977. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6978. ;;;; Structure editing
  6979. ;;; Inserting headlines
  6980. (defun org--line-empty-p (n)
  6981. "Is the Nth next line empty?
  6982. Counts the current line as N = 1 and the previous line as N = 0;
  6983. see `beginning-of-line'."
  6984. (save-excursion
  6985. (and (not (bobp))
  6986. (or (beginning-of-line n) t)
  6987. (save-match-data
  6988. (looking-at "[ \t]*$")))))
  6989. (defun org-previous-line-empty-p ()
  6990. "Is the previous line a blank line?
  6991. When NEXT is non-nil, check the next line instead."
  6992. (org--line-empty-p 0))
  6993. (defun org-next-line-empty-p ()
  6994. "Is the previous line a blank line?
  6995. When NEXT is non-nil, check the next line instead."
  6996. (org--line-empty-p 2))
  6997. (defun org-insert-heading (&optional arg invisible-ok top)
  6998. "Insert a new heading or an item with the same depth at point.
  6999. If point is at the beginning of a heading or a list item, insert
  7000. a new heading or a new item above the current one. When at the
  7001. beginning of a regular line of text, turn it into a heading.
  7002. If point is in the middle of a line, split it and create a new
  7003. headline/item with the text in the current line after point (see
  7004. `org-M-RET-may-split-line' on how to modify this behavior). As
  7005. a special case, on a headline, splitting can only happen on the
  7006. title itself. E.g., this excludes breaking stars or tags.
  7007. With a `\\[universal-argument]' prefix, set \
  7008. `org-insert-heading-respect-content' to
  7009. a non-nil value for the duration of the command. This forces the
  7010. insertion of a heading after the current subtree, independently
  7011. on the location of point.
  7012. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  7013. insert the heading at the end of the tree
  7014. above the current heading. For example, if point is within a
  7015. 2nd-level heading, then it will insert a 2nd-level heading at
  7016. the end of the 1st-level parent subtree.
  7017. When INVISIBLE-OK is set, stop at invisible headlines when going
  7018. back. This is important for non-interactive uses of the
  7019. command.
  7020. When optional argument TOP is non-nil, insert a level 1 heading,
  7021. unconditionally."
  7022. (interactive "P")
  7023. (let ((itemp (and (not top) (org-in-item-p)))
  7024. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7025. (respect-content (or org-insert-heading-respect-content
  7026. (equal arg '(4))))
  7027. (initial-content ""))
  7028. (cond
  7029. ((or (= (buffer-size) 0)
  7030. (and (not (save-excursion
  7031. (and (ignore-errors (org-back-to-heading invisible-ok))
  7032. (org-at-heading-p))))
  7033. (or arg (not itemp))))
  7034. ;; At beginning of buffer or so high up that only a heading
  7035. ;; makes sense.
  7036. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7037. ((not respect-content)
  7038. (unless may-split (end-of-line))
  7039. (insert "\n* "))
  7040. ((re-search-forward org-outline-regexp-bol nil t)
  7041. (beginning-of-line)
  7042. (insert "* \n")
  7043. (backward-char))
  7044. (t (goto-char (point-max))
  7045. (insert "\n* ")))
  7046. (run-hooks 'org-insert-heading-hook))
  7047. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7048. (t
  7049. ;; Maybe move at the end of the subtree
  7050. (when (equal arg '(16))
  7051. (org-up-heading-safe)
  7052. (org-end-of-subtree t))
  7053. ;; Insert a heading
  7054. (save-restriction
  7055. (widen)
  7056. (let* ((level nil)
  7057. (on-heading (org-at-heading-p))
  7058. (empty-line-p (if on-heading
  7059. (org-previous-line-empty-p)
  7060. ;; We will decide later
  7061. nil))
  7062. ;; Get a level string to fall back on.
  7063. (fix-level
  7064. (if (org-before-first-heading-p) "*"
  7065. (save-excursion
  7066. (org-back-to-heading t)
  7067. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7068. (looking-at org-outline-regexp)
  7069. (make-string (1- (length (match-string 0))) ?*))))
  7070. (stars
  7071. (save-excursion
  7072. (condition-case nil
  7073. (if top "* "
  7074. (org-back-to-heading invisible-ok)
  7075. (when (and (not on-heading)
  7076. (featurep 'org-inlinetask)
  7077. (integerp org-inlinetask-min-level)
  7078. (>= (length (match-string 0))
  7079. org-inlinetask-min-level))
  7080. ;; Find a heading level before the inline
  7081. ;; task.
  7082. (while (and (setq level (org-up-heading-safe))
  7083. (>= level org-inlinetask-min-level)))
  7084. (if (org-at-heading-p)
  7085. (org-back-to-heading invisible-ok)
  7086. (error "This should not happen")))
  7087. (unless (and (save-excursion
  7088. (save-match-data
  7089. (org-backward-heading-same-level
  7090. 1 invisible-ok))
  7091. (= (point) (match-beginning 0)))
  7092. (not (org-next-line-empty-p)))
  7093. (setq empty-line-p (or empty-line-p
  7094. (org-previous-line-empty-p))))
  7095. (match-string 0))
  7096. (error (or fix-level "* ")))))
  7097. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7098. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7099. ;; If we insert after content, move there and clean up
  7100. ;; whitespace.
  7101. (when respect-content
  7102. (if (not (org-before-first-heading-p))
  7103. (org-end-of-subtree nil t)
  7104. (re-search-forward org-outline-regexp-bol)
  7105. (beginning-of-line 0))
  7106. (skip-chars-backward " \r\t\n")
  7107. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7108. (looking-at "[ \t]+") (replace-match ""))
  7109. (unless (eobp) (forward-char 1))
  7110. (when (looking-at "^\\*")
  7111. (unless (bobp) (backward-char 1))
  7112. (insert "\n")))
  7113. ;; If we are splitting, grab the text that should be moved
  7114. ;; to the new headline.
  7115. (when may-split
  7116. (if (org-at-heading-p)
  7117. ;; This is a heading: split intelligently (keeping
  7118. ;; tags).
  7119. (let ((pos (point)))
  7120. (beginning-of-line)
  7121. (let ((case-fold-search nil))
  7122. (unless (looking-at org-complex-heading-regexp)
  7123. (error "This should not happen")))
  7124. (when (and (match-beginning 4)
  7125. (> pos (match-beginning 4))
  7126. (< pos (match-end 4)))
  7127. (setq initial-content (buffer-substring pos (match-end 4)))
  7128. (goto-char pos)
  7129. (delete-region (point) (match-end 4))
  7130. (if (looking-at "[ \t]*$")
  7131. (replace-match "")
  7132. (insert (make-string (length initial-content) ?\s)))
  7133. (setq initial-content (org-trim initial-content)))
  7134. (goto-char pos))
  7135. ;; A normal line.
  7136. (setq initial-content
  7137. (org-trim
  7138. (delete-and-extract-region (point) (line-end-position))))))
  7139. ;; If we are at the beginning of the line, insert before it.
  7140. ;; Otherwise, after it.
  7141. (cond
  7142. ((and (bolp) (looking-at "[ \t]*$")))
  7143. ((bolp) (save-excursion (insert "\n")))
  7144. (t (end-of-line)
  7145. (insert "\n")))
  7146. ;; Insert the new heading
  7147. (insert stars)
  7148. (just-one-space)
  7149. (insert initial-content)
  7150. (unless (and blank (org-previous-line-empty-p))
  7151. (org-N-empty-lines-before-current (if blank 1 0)))
  7152. ;; Adjust visibility, which may be messed up if we removed
  7153. ;; blank lines while previous entry was hidden.
  7154. (let ((bol (line-beginning-position)))
  7155. (dolist (o (overlays-at (1- bol)))
  7156. (when (and (eq (overlay-get o 'invisible) 'outline)
  7157. (eq (overlay-end o) bol))
  7158. (move-overlay o (overlay-start o) (1- bol)))))
  7159. (run-hooks 'org-insert-heading-hook)))))))
  7160. (defun org-N-empty-lines-before-current (N)
  7161. "Make the number of empty lines before current exactly N.
  7162. So this will delete or add empty lines."
  7163. (save-excursion
  7164. (beginning-of-line)
  7165. (let ((p (point)))
  7166. (skip-chars-backward " \r\t\n")
  7167. (unless (bolp) (forward-line))
  7168. (delete-region (point) p))
  7169. (when (> N 0) (insert (make-string N ?\n)))))
  7170. (defun org-get-heading (&optional no-tags no-todo)
  7171. "Return the heading of the current entry, without the stars.
  7172. When NO-TAGS is non-nil, don't include tags.
  7173. When NO-TODO is non-nil, don't include TODO keywords."
  7174. (save-excursion
  7175. (org-back-to-heading t)
  7176. (let ((case-fold-search nil))
  7177. (cond
  7178. ((and no-tags no-todo)
  7179. (looking-at org-complex-heading-regexp)
  7180. ;; Return value has to be a string, but match group 4 is
  7181. ;; optional.
  7182. (or (match-string 4) ""))
  7183. (no-tags
  7184. (looking-at (concat org-outline-regexp
  7185. "\\(.*?\\)"
  7186. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7187. (match-string 1))
  7188. (no-todo
  7189. (looking-at org-todo-line-regexp)
  7190. (match-string 3))
  7191. (t (looking-at org-heading-regexp)
  7192. (match-string 2))))))
  7193. (defvar orgstruct-mode) ; defined below
  7194. (defun org-heading-components ()
  7195. "Return the components of the current heading.
  7196. This is a list with the following elements:
  7197. - the level as an integer
  7198. - the reduced level, different if `org-odd-levels-only' is set.
  7199. - the TODO keyword, or nil
  7200. - the priority character, like ?A, or nil if no priority is given
  7201. - the headline text itself, or the tags string if no headline text
  7202. - the tags string, or nil."
  7203. (save-excursion
  7204. (org-back-to-heading t)
  7205. (when (let (case-fold-search)
  7206. (looking-at
  7207. (if orgstruct-mode
  7208. org-heading-regexp
  7209. org-complex-heading-regexp)))
  7210. (if orgstruct-mode
  7211. (list (length (match-string 1))
  7212. (org-reduced-level (length (match-string 1)))
  7213. nil
  7214. nil
  7215. (match-string 2)
  7216. nil)
  7217. (list (length (match-string 1))
  7218. (org-reduced-level (length (match-string 1)))
  7219. (match-string-no-properties 2)
  7220. (and (match-end 3) (aref (match-string 3) 2))
  7221. (match-string-no-properties 4)
  7222. (match-string-no-properties 5))))))
  7223. (defun org-get-entry ()
  7224. "Get the entry text, after heading, entire subtree."
  7225. (save-excursion
  7226. (org-back-to-heading t)
  7227. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7228. (defun org-edit-headline (&optional heading)
  7229. "Edit the current headline.
  7230. Set it to HEADING when provided."
  7231. (interactive)
  7232. (org-with-wide-buffer
  7233. (org-back-to-heading t)
  7234. (let ((case-fold-search nil))
  7235. (when (looking-at org-complex-heading-regexp)
  7236. (let* ((old (match-string-no-properties 4))
  7237. (new (save-match-data
  7238. (org-trim (or heading (read-string "Edit: " old))))))
  7239. (unless (equal old new)
  7240. (if old (replace-match new t t nil 4)
  7241. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7242. (insert " " new))
  7243. (org-set-tags nil t)
  7244. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7245. (defun org-insert-heading-after-current ()
  7246. "Insert a new heading with same level as current, after current subtree."
  7247. (interactive)
  7248. (org-back-to-heading)
  7249. (org-insert-heading)
  7250. (org-move-subtree-down)
  7251. (end-of-line 1))
  7252. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7253. "Insert heading with `org-insert-heading-respect-content' set to t."
  7254. (interactive)
  7255. (org-insert-heading '(4) invisible-ok))
  7256. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7257. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7258. (interactive)
  7259. (org-insert-todo-heading force-state '(4)))
  7260. (defun org-insert-todo-heading (arg &optional force-heading)
  7261. "Insert a new heading with the same level and TODO state as current heading.
  7262. If the heading has no TODO state, or if the state is DONE, use
  7263. the first state (TODO by default). Also with one prefix arg,
  7264. force first state. With two prefix args, force inserting at the
  7265. end of the parent subtree.
  7266. When called at a plain list item, insert a new item with an
  7267. unchecked check box."
  7268. (interactive "P")
  7269. (when (or force-heading (not (org-insert-item 'checkbox)))
  7270. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7271. force-heading))
  7272. (save-excursion
  7273. (org-back-to-heading)
  7274. (outline-previous-heading)
  7275. (looking-at org-todo-line-regexp))
  7276. (let* ((new-mark-x
  7277. (if (or (equal arg '(4))
  7278. (not (match-beginning 2))
  7279. (member (match-string 2) org-done-keywords))
  7280. (car org-todo-keywords-1)
  7281. (match-string 2)))
  7282. (new-mark
  7283. (or
  7284. (run-hook-with-args-until-success
  7285. 'org-todo-get-default-hook new-mark-x nil)
  7286. new-mark-x)))
  7287. (beginning-of-line 1)
  7288. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7289. (if org-treat-insert-todo-heading-as-state-change
  7290. (org-todo new-mark)
  7291. (insert new-mark " "))))
  7292. (when org-provide-todo-statistics
  7293. (org-update-parent-todo-statistics))))
  7294. (defun org-insert-subheading (arg)
  7295. "Insert a new subheading and demote it.
  7296. Works for outline headings and for plain lists alike."
  7297. (interactive "P")
  7298. (org-insert-heading arg)
  7299. (cond
  7300. ((org-at-heading-p) (org-do-demote))
  7301. ((org-at-item-p) (org-indent-item))))
  7302. (defun org-insert-todo-subheading (arg)
  7303. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7304. Works for outline headings and for plain lists alike."
  7305. (interactive "P")
  7306. (org-insert-todo-heading arg)
  7307. (cond
  7308. ((org-at-heading-p) (org-do-demote))
  7309. ((org-at-item-p) (org-indent-item))))
  7310. ;;; Promotion and Demotion
  7311. (defvar org-after-demote-entry-hook nil
  7312. "Hook run after an entry has been demoted.
  7313. The cursor will be at the beginning of the entry.
  7314. When a subtree is being demoted, the hook will be called for each node.")
  7315. (defvar org-after-promote-entry-hook nil
  7316. "Hook run after an entry has been promoted.
  7317. The cursor will be at the beginning of the entry.
  7318. When a subtree is being promoted, the hook will be called for each node.")
  7319. (defun org-promote-subtree ()
  7320. "Promote the entire subtree.
  7321. See also `org-promote'."
  7322. (interactive)
  7323. (save-excursion
  7324. (org-with-limited-levels (org-map-tree 'org-promote)))
  7325. (org-fix-position-after-promote))
  7326. (defun org-demote-subtree ()
  7327. "Demote the entire subtree.
  7328. See `org-demote' and `org-promote'."
  7329. (interactive)
  7330. (save-excursion
  7331. (org-with-limited-levels (org-map-tree 'org-demote)))
  7332. (org-fix-position-after-promote))
  7333. (defun org-do-promote ()
  7334. "Promote the current heading higher up the tree.
  7335. If the region is active in `transient-mark-mode', promote all
  7336. headings in the region."
  7337. (interactive)
  7338. (save-excursion
  7339. (if (org-region-active-p)
  7340. (org-map-region 'org-promote (region-beginning) (region-end))
  7341. (org-promote)))
  7342. (org-fix-position-after-promote))
  7343. (defun org-do-demote ()
  7344. "Demote the current heading lower down the tree.
  7345. If the region is active in `transient-mark-mode', demote all
  7346. headings in the region."
  7347. (interactive)
  7348. (save-excursion
  7349. (if (org-region-active-p)
  7350. (org-map-region 'org-demote (region-beginning) (region-end))
  7351. (org-demote)))
  7352. (org-fix-position-after-promote))
  7353. (defun org-fix-position-after-promote ()
  7354. "Fix cursor position and indentation after demoting/promoting."
  7355. (let ((pos (point)))
  7356. (when (save-excursion
  7357. (beginning-of-line 1)
  7358. (looking-at org-todo-line-regexp)
  7359. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7360. (cond ((eobp) (insert " "))
  7361. ((eolp) (insert " "))
  7362. ((equal (char-after) ?\ ) (forward-char 1))))))
  7363. (defun org-current-level ()
  7364. "Return the level of the current entry, or nil if before the first headline.
  7365. The level is the number of stars at the beginning of the
  7366. headline. Use `org-reduced-level' to remove the effect of
  7367. `org-odd-levels'. Unlike to `org-outline-level', this function
  7368. ignores inlinetasks."
  7369. (let ((level (org-with-limited-levels (org-outline-level))))
  7370. (and (> level 0) level)))
  7371. (defun org-get-previous-line-level ()
  7372. "Return the outline depth of the last headline before the current line.
  7373. Returns 0 for the first headline in the buffer, and nil if before the
  7374. first headline."
  7375. (and (org-current-level)
  7376. (or (and (/= (line-beginning-position) (point-min))
  7377. (save-excursion (beginning-of-line 0) (org-current-level)))
  7378. 0)))
  7379. (defun org-reduced-level (l)
  7380. "Compute the effective level of a heading.
  7381. This takes into account the setting of `org-odd-levels-only'."
  7382. (cond
  7383. ((zerop l) 0)
  7384. (org-odd-levels-only (1+ (floor (/ l 2))))
  7385. (t l)))
  7386. (defun org-level-increment ()
  7387. "Return the number of stars that will be added or removed at a
  7388. time to headlines when structure editing, based on the value of
  7389. `org-odd-levels-only'."
  7390. (if org-odd-levels-only 2 1))
  7391. (defun org-get-valid-level (level &optional change)
  7392. "Rectify a level change under the influence of `org-odd-levels-only'
  7393. LEVEL is a current level, CHANGE is by how much the level should be
  7394. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7395. even level numbers will become the next higher odd number."
  7396. (if org-odd-levels-only
  7397. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7398. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7399. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7400. (max 1 (+ level (or change 0)))))
  7401. (defun org-promote ()
  7402. "Promote the current heading higher up the tree."
  7403. (org-with-wide-buffer
  7404. (org-back-to-heading t)
  7405. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7406. after-change-functions))
  7407. (level (save-match-data (funcall outline-level)))
  7408. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7409. (diff (abs (- level (length up-head) -1))))
  7410. (cond
  7411. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7412. (replace-match "# " nil t))
  7413. ((= level 1)
  7414. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7415. (t (replace-match up-head nil t)))
  7416. (unless (= level 1)
  7417. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7418. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7419. (run-hooks 'org-after-promote-entry-hook))))
  7420. (defun org-demote ()
  7421. "Demote the current heading lower down the tree."
  7422. (org-with-wide-buffer
  7423. (org-back-to-heading t)
  7424. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7425. after-change-functions))
  7426. (level (save-match-data (funcall outline-level)))
  7427. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7428. (diff (abs (- level (length down-head) -1))))
  7429. (replace-match down-head nil t)
  7430. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7431. (when org-adapt-indentation (org-fixup-indentation diff))
  7432. (run-hooks 'org-after-demote-entry-hook))))
  7433. (defun org-cycle-level ()
  7434. "Cycle the level of an empty headline through possible states.
  7435. This goes first to child, then to parent, level, then up the hierarchy.
  7436. After top level, it switches back to sibling level."
  7437. (interactive)
  7438. (let ((org-adapt-indentation nil))
  7439. (when (org-point-at-end-of-empty-headline)
  7440. (setq this-command 'org-cycle-level) ; Only needed for caching
  7441. (let ((cur-level (org-current-level))
  7442. (prev-level (org-get-previous-line-level)))
  7443. (cond
  7444. ;; If first headline in file, promote to top-level.
  7445. ((= prev-level 0)
  7446. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7447. do (org-do-promote)))
  7448. ;; If same level as prev, demote one.
  7449. ((= prev-level cur-level)
  7450. (org-do-demote))
  7451. ;; If parent is top-level, promote to top level if not already.
  7452. ((= prev-level 1)
  7453. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7454. do (org-do-promote)))
  7455. ;; If top-level, return to prev-level.
  7456. ((= cur-level 1)
  7457. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7458. do (org-do-demote)))
  7459. ;; If less than prev-level, promote one.
  7460. ((< cur-level prev-level)
  7461. (org-do-promote))
  7462. ;; If deeper than prev-level, promote until higher than
  7463. ;; prev-level.
  7464. ((> cur-level prev-level)
  7465. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7466. do (org-do-promote))))
  7467. t))))
  7468. (defun org-map-tree (fun)
  7469. "Call FUN for every heading underneath the current one."
  7470. (org-back-to-heading t)
  7471. (let ((level (funcall outline-level)))
  7472. (save-excursion
  7473. (funcall fun)
  7474. (while (and (progn
  7475. (outline-next-heading)
  7476. (> (funcall outline-level) level))
  7477. (not (eobp)))
  7478. (funcall fun)))))
  7479. (defun org-map-region (fun beg end)
  7480. "Call FUN for every heading between BEG and END."
  7481. (let ((org-ignore-region t))
  7482. (save-excursion
  7483. (setq end (copy-marker end))
  7484. (goto-char beg)
  7485. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7486. (< (point) end))
  7487. (funcall fun))
  7488. (while (and (progn
  7489. (outline-next-heading)
  7490. (< (point) end))
  7491. (not (eobp)))
  7492. (funcall fun)))))
  7493. (defun org-fixup-indentation (diff)
  7494. "Change the indentation in the current entry by DIFF.
  7495. DIFF is an integer. Indentation is done according to the
  7496. following rules:
  7497. - Planning information and property drawers are always indented
  7498. according to the new level of the headline;
  7499. - Footnote definitions and their contents are ignored;
  7500. - Inlinetasks' boundaries are not shifted;
  7501. - Empty lines are ignored;
  7502. - Other lines' indentation are shifted by DIFF columns, unless
  7503. it would introduce a structural change in the document, in
  7504. which case no shifting is done at all.
  7505. Assume point is at a heading or an inlinetask beginning."
  7506. (org-with-wide-buffer
  7507. (narrow-to-region (line-beginning-position)
  7508. (save-excursion
  7509. (if (org-with-limited-levels (org-at-heading-p))
  7510. (org-with-limited-levels (outline-next-heading))
  7511. (org-inlinetask-goto-end))
  7512. (point)))
  7513. (forward-line)
  7514. ;; Indent properly planning info and property drawer.
  7515. (when (looking-at-p org-planning-line-re)
  7516. (org-indent-line)
  7517. (forward-line))
  7518. (when (looking-at org-property-drawer-re)
  7519. (goto-char (match-end 0))
  7520. (forward-line)
  7521. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7522. (catch 'no-shift
  7523. (when (zerop diff) (throw 'no-shift nil))
  7524. ;; If DIFF is negative, first check if a shift is possible at all
  7525. ;; (e.g., it doesn't break structure). This can only happen if
  7526. ;; some contents are not properly indented.
  7527. (let ((case-fold-search t))
  7528. (when (< diff 0)
  7529. (let ((diff (- diff))
  7530. (forbidden-re (concat org-outline-regexp
  7531. "\\|"
  7532. (substring org-footnote-definition-re 1))))
  7533. (save-excursion
  7534. (while (not (eobp))
  7535. (cond
  7536. ((looking-at-p "[ \t]*$") (forward-line))
  7537. ((and (looking-at-p org-footnote-definition-re)
  7538. (let ((e (org-element-at-point)))
  7539. (and (eq (org-element-type e) 'footnote-definition)
  7540. (goto-char (org-element-property :end e))))))
  7541. ((looking-at-p org-outline-regexp) (forward-line))
  7542. ;; Give up if shifting would move before column 0 or
  7543. ;; if it would introduce a headline or a footnote
  7544. ;; definition.
  7545. (t
  7546. (skip-chars-forward " \t")
  7547. (let ((ind (current-column)))
  7548. (when (or (< ind diff)
  7549. (and (= ind diff) (looking-at-p forbidden-re)))
  7550. (throw 'no-shift nil)))
  7551. ;; Ignore contents of example blocks and source
  7552. ;; blocks if their indentation is meant to be
  7553. ;; preserved. Jump to block's closing line.
  7554. (beginning-of-line)
  7555. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7556. (let ((e (org-element-at-point)))
  7557. (and (memq (org-element-type e)
  7558. '(example-block src-block))
  7559. (or org-src-preserve-indentation
  7560. (org-element-property :preserve-indent e))
  7561. (goto-char (org-element-property :end e))
  7562. (progn (skip-chars-backward " \r\t\n")
  7563. (beginning-of-line)
  7564. t))))
  7565. (forward-line))))))))
  7566. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7567. ;; by DIFF. Also skip contents of source or example blocks
  7568. ;; when indentation is meant to be preserved.
  7569. (while (not (eobp))
  7570. (cond
  7571. ((and (looking-at-p org-footnote-definition-re)
  7572. (let ((e (org-element-at-point)))
  7573. (and (eq (org-element-type e) 'footnote-definition)
  7574. (goto-char (org-element-property :end e))))))
  7575. ((looking-at-p org-outline-regexp) (forward-line))
  7576. ((looking-at-p "[ \t]*$") (forward-line))
  7577. (t
  7578. (indent-line-to (+ (org-get-indentation) diff))
  7579. (beginning-of-line)
  7580. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7581. (let ((e (org-element-at-point)))
  7582. (and (memq (org-element-type e)
  7583. '(example-block src-block))
  7584. (or org-src-preserve-indentation
  7585. (org-element-property :preserve-indent e))
  7586. (goto-char (org-element-property :end e))
  7587. (progn (skip-chars-backward " \r\t\n")
  7588. (beginning-of-line)
  7589. t))))
  7590. (forward-line)))))))))
  7591. (defun org-convert-to-odd-levels ()
  7592. "Convert an Org file with all levels allowed to one with odd levels.
  7593. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7594. level 5 etc."
  7595. (interactive)
  7596. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7597. (let ((outline-level 'org-outline-level)
  7598. (org-odd-levels-only nil) n)
  7599. (save-excursion
  7600. (goto-char (point-min))
  7601. (while (re-search-forward "^\\*\\*+ " nil t)
  7602. (setq n (- (length (match-string 0)) 2))
  7603. (while (>= (setq n (1- n)) 0)
  7604. (org-demote))
  7605. (end-of-line 1))))))
  7606. (defun org-convert-to-oddeven-levels ()
  7607. "Convert an Org file with only odd levels to one with odd/even levels.
  7608. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7609. file contains a section with an even level, conversion would
  7610. destroy the structure of the file. An error is signaled in this
  7611. case."
  7612. (interactive)
  7613. (goto-char (point-min))
  7614. ;; First check if there are no even levels
  7615. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7616. (org-show-set-visibility 'canonical)
  7617. (error "Not all levels are odd in this file. Conversion not possible"))
  7618. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7619. (let ((outline-regexp org-outline-regexp)
  7620. (outline-level 'org-outline-level)
  7621. (org-odd-levels-only nil) n)
  7622. (save-excursion
  7623. (goto-char (point-min))
  7624. (while (re-search-forward "^\\*\\*+ " nil t)
  7625. (setq n (/ (1- (length (match-string 0))) 2))
  7626. (while (>= (setq n (1- n)) 0)
  7627. (org-promote))
  7628. (end-of-line 1))))))
  7629. (defun org-tr-level (n)
  7630. "Make N odd if required."
  7631. (if org-odd-levels-only (1+ (/ n 2)) n))
  7632. ;;; Vertical tree motion, cutting and pasting of subtrees
  7633. (defun org-move-subtree-up (&optional arg)
  7634. "Move the current subtree up past ARG headlines of the same level."
  7635. (interactive "p")
  7636. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7637. (defun org-move-subtree-down (&optional arg)
  7638. "Move the current subtree down past ARG headlines of the same level."
  7639. (interactive "p")
  7640. (setq arg (prefix-numeric-value arg))
  7641. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7642. 'org-get-last-sibling))
  7643. (ins-point (make-marker))
  7644. (cnt (abs arg))
  7645. (col (current-column))
  7646. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7647. ;; Select the tree
  7648. (org-back-to-heading)
  7649. (setq beg0 (point))
  7650. (save-excursion
  7651. (setq ne-beg (org-back-over-empty-lines))
  7652. (setq beg (point)))
  7653. (save-match-data
  7654. (save-excursion (outline-end-of-heading)
  7655. (setq folded (outline-invisible-p)))
  7656. (progn (org-end-of-subtree nil t)
  7657. (unless (eobp) (backward-char))))
  7658. (outline-next-heading)
  7659. (setq ne-end (org-back-over-empty-lines))
  7660. (setq end (point))
  7661. (goto-char beg0)
  7662. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7663. ;; include less whitespace
  7664. (save-excursion
  7665. (goto-char beg)
  7666. (forward-line (- ne-beg ne-end))
  7667. (setq beg (point))))
  7668. ;; Find insertion point, with error handling
  7669. (while (> cnt 0)
  7670. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7671. (progn (goto-char beg0)
  7672. (user-error "Cannot move past superior level or buffer limit")))
  7673. (setq cnt (1- cnt)))
  7674. (when (> arg 0)
  7675. ;; Moving forward - still need to move over subtree
  7676. (org-end-of-subtree t t)
  7677. (save-excursion
  7678. (org-back-over-empty-lines)
  7679. (or (bolp) (newline))))
  7680. (setq ne-ins (org-back-over-empty-lines))
  7681. (move-marker ins-point (point))
  7682. (setq txt (buffer-substring beg end))
  7683. (org-save-markers-in-region beg end)
  7684. (delete-region beg end)
  7685. (org-remove-empty-overlays-at beg)
  7686. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7687. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7688. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7689. (let ((bbb (point)))
  7690. (insert-before-markers txt)
  7691. (org-reinstall-markers-in-region bbb)
  7692. (move-marker ins-point bbb))
  7693. (or (bolp) (insert "\n"))
  7694. (setq ins-end (point))
  7695. (goto-char ins-point)
  7696. (org-skip-whitespace)
  7697. (when (and (< arg 0)
  7698. (org-first-sibling-p)
  7699. (> ne-ins ne-beg))
  7700. ;; Move whitespace back to beginning
  7701. (save-excursion
  7702. (goto-char ins-end)
  7703. (let ((kill-whole-line t))
  7704. (kill-line (- ne-ins ne-beg)) (point)))
  7705. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7706. (move-marker ins-point nil)
  7707. (if folded
  7708. (outline-hide-subtree)
  7709. (org-show-entry)
  7710. (org-show-children)
  7711. (org-cycle-hide-drawers 'children))
  7712. (org-clean-visibility-after-subtree-move)
  7713. ;; move back to the initial column we were at
  7714. (move-to-column col)))
  7715. (defvar org-subtree-clip ""
  7716. "Clipboard for cut and paste of subtrees.
  7717. This is actually only a copy of the kill, because we use the normal kill
  7718. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7719. (defvar org-subtree-clip-folded nil
  7720. "Was the last copied subtree folded?
  7721. This is used to fold the tree back after pasting.")
  7722. (defun org-cut-subtree (&optional n)
  7723. "Cut the current subtree into the clipboard.
  7724. With prefix arg N, cut this many sequential subtrees.
  7725. This is a short-hand for marking the subtree and then cutting it."
  7726. (interactive "p")
  7727. (org-copy-subtree n 'cut))
  7728. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7729. "Copy the current subtree it in the clipboard.
  7730. With prefix arg N, copy this many sequential subtrees.
  7731. This is a short-hand for marking the subtree and then copying it.
  7732. If CUT is non-nil, actually cut the subtree.
  7733. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7734. of some markers in the region, even if CUT is non-nil. This is
  7735. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7736. (interactive "p")
  7737. (let (beg end folded (beg0 (point)))
  7738. (if (called-interactively-p 'any)
  7739. (org-back-to-heading nil) ; take what looks like a subtree
  7740. (org-back-to-heading t)) ; take what is really there
  7741. (setq beg (point))
  7742. (skip-chars-forward " \t\r\n")
  7743. (save-match-data
  7744. (if nosubtrees
  7745. (outline-next-heading)
  7746. (save-excursion (outline-end-of-heading)
  7747. (setq folded (outline-invisible-p)))
  7748. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7749. (org-end-of-subtree t t)))
  7750. ;; Include the end of an inlinetask
  7751. (when (and (featurep 'org-inlinetask)
  7752. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7753. "END[ \t]*$")))
  7754. (end-of-line))
  7755. (setq end (point))
  7756. (goto-char beg0)
  7757. (when (> end beg)
  7758. (setq org-subtree-clip-folded folded)
  7759. (when (or cut force-store-markers)
  7760. (org-save-markers-in-region beg end))
  7761. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7762. (setq org-subtree-clip (current-kill 0))
  7763. (message "%s: Subtree(s) with %d characters"
  7764. (if cut "Cut" "Copied")
  7765. (length org-subtree-clip)))))
  7766. (defun org-paste-subtree (&optional level tree for-yank remove)
  7767. "Paste the clipboard as a subtree, with modification of headline level.
  7768. The entire subtree is promoted or demoted in order to match a new headline
  7769. level.
  7770. If the cursor is at the beginning of a headline, the same level as
  7771. that headline is used to paste the tree.
  7772. If not, the new level is derived from the *visible* headings
  7773. before and after the insertion point, and taken to be the inferior headline
  7774. level of the two. So if the previous visible heading is level 3 and the
  7775. next is level 4 (or vice versa), level 4 will be used for insertion.
  7776. This makes sure that the subtree remains an independent subtree and does
  7777. not swallow low level entries.
  7778. You can also force a different level, either by using a numeric prefix
  7779. argument, or by inserting the heading marker by hand. For example, if the
  7780. cursor is after \"*****\", then the tree will be shifted to level 5.
  7781. If optional TREE is given, use this text instead of the kill ring.
  7782. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7783. move back over whitespace before inserting, and move point to the end of
  7784. the inserted text when done.
  7785. When REMOVE is non-nil, remove the subtree from the clipboard."
  7786. (interactive "P")
  7787. (setq tree (or tree (and kill-ring (current-kill 0))))
  7788. (unless (org-kill-is-subtree-p tree)
  7789. (user-error "%s"
  7790. (substitute-command-keys
  7791. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7792. (org-with-limited-levels
  7793. (let* ((visp (not (outline-invisible-p)))
  7794. (txt tree)
  7795. (^re_ "\\(\\*+\\)[ \t]*")
  7796. (old-level (if (string-match org-outline-regexp-bol txt)
  7797. (- (match-end 0) (match-beginning 0) 1)
  7798. -1))
  7799. (force-level (cond (level (prefix-numeric-value level))
  7800. ((and (looking-at "[ \t]*$")
  7801. (string-match
  7802. "^\\*+$" (buffer-substring
  7803. (point-at-bol) (point))))
  7804. (- (match-end 0) (match-beginning 0)))
  7805. ((and (bolp)
  7806. (looking-at org-outline-regexp))
  7807. (- (match-end 0) (point) 1))))
  7808. (previous-level (save-excursion
  7809. (condition-case nil
  7810. (progn
  7811. (outline-previous-visible-heading 1)
  7812. (if (looking-at ^re_)
  7813. (- (match-end 0) (match-beginning 0) 1)
  7814. 1))
  7815. (error 1))))
  7816. (next-level (save-excursion
  7817. (condition-case nil
  7818. (progn
  7819. (or (looking-at org-outline-regexp)
  7820. (outline-next-visible-heading 1))
  7821. (if (looking-at ^re_)
  7822. (- (match-end 0) (match-beginning 0) 1)
  7823. 1))
  7824. (error 1))))
  7825. (new-level (or force-level (max previous-level next-level)))
  7826. (shift (if (or (= old-level -1)
  7827. (= new-level -1)
  7828. (= old-level new-level))
  7829. 0
  7830. (- new-level old-level)))
  7831. (delta (if (> shift 0) -1 1))
  7832. (func (if (> shift 0) 'org-demote 'org-promote))
  7833. (org-odd-levels-only nil)
  7834. beg end newend)
  7835. ;; Remove the forced level indicator
  7836. (when force-level
  7837. (delete-region (point-at-bol) (point)))
  7838. ;; Paste
  7839. (beginning-of-line (if (bolp) 1 2))
  7840. (setq beg (point))
  7841. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7842. (insert-before-markers txt)
  7843. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7844. (setq newend (point))
  7845. (org-reinstall-markers-in-region beg)
  7846. (setq end (point))
  7847. (goto-char beg)
  7848. (skip-chars-forward " \t\n\r")
  7849. (setq beg (point))
  7850. (when (and (outline-invisible-p) visp)
  7851. (save-excursion (outline-show-heading)))
  7852. ;; Shift if necessary
  7853. (unless (= shift 0)
  7854. (save-restriction
  7855. (narrow-to-region beg end)
  7856. (while (not (= shift 0))
  7857. (org-map-region func (point-min) (point-max))
  7858. (setq shift (+ delta shift)))
  7859. (goto-char (point-min))
  7860. (setq newend (point-max))))
  7861. (when (or (called-interactively-p 'interactive) for-yank)
  7862. (message "Clipboard pasted as level %d subtree" new-level))
  7863. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7864. kill-ring
  7865. (eq org-subtree-clip (current-kill 0))
  7866. org-subtree-clip-folded)
  7867. ;; The tree was folded before it was killed/copied
  7868. (outline-hide-subtree))
  7869. (and for-yank (goto-char newend))
  7870. (and remove (setq kill-ring (cdr kill-ring))))))
  7871. (defun org-kill-is-subtree-p (&optional txt)
  7872. "Check if the current kill is an outline subtree, or a set of trees.
  7873. Returns nil if kill does not start with a headline, or if the first
  7874. headline level is not the largest headline level in the tree.
  7875. So this will actually accept several entries of equal levels as well,
  7876. which is OK for `org-paste-subtree'.
  7877. If optional TXT is given, check this string instead of the current kill."
  7878. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7879. (re (org-get-limited-outline-regexp))
  7880. (^re (concat "^" re))
  7881. (start-level (and kill
  7882. (string-match
  7883. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7884. kill)
  7885. (- (match-end 2) (match-beginning 2) 1)))
  7886. (start (1+ (or (match-beginning 2) -1))))
  7887. (if (not start-level)
  7888. (progn
  7889. nil) ;; does not even start with a heading
  7890. (catch 'exit
  7891. (while (setq start (string-match ^re kill (1+ start)))
  7892. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7893. (throw 'exit nil)))
  7894. t))))
  7895. (defvar org-markers-to-move nil
  7896. "Markers that should be moved with a cut-and-paste operation.
  7897. Those markers are stored together with their positions relative to
  7898. the start of the region.")
  7899. (defun org-save-markers-in-region (beg end)
  7900. "Check markers in region.
  7901. If these markers are between BEG and END, record their position relative
  7902. to BEG, so that after moving the block of text, we can put the markers back
  7903. into place.
  7904. This function gets called just before an entry or tree gets cut from the
  7905. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7906. called immediately, to move the markers with the entries."
  7907. (setq org-markers-to-move nil)
  7908. (when (featurep 'org-clock)
  7909. (org-clock-save-markers-for-cut-and-paste beg end))
  7910. (when (featurep 'org-agenda)
  7911. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7912. (defun org-check-and-save-marker (marker beg end)
  7913. "Check if MARKER is between BEG and END.
  7914. If yes, remember the marker and the distance to BEG."
  7915. (when (and (marker-buffer marker)
  7916. (equal (marker-buffer marker) (current-buffer))
  7917. (>= marker beg) (< marker end))
  7918. (push (cons marker (- marker beg)) org-markers-to-move)))
  7919. (defun org-reinstall-markers-in-region (beg)
  7920. "Move all remembered markers to their position relative to BEG."
  7921. (dolist (x org-markers-to-move)
  7922. (move-marker (car x) (+ beg (cdr x))))
  7923. (setq org-markers-to-move nil))
  7924. (defun org-narrow-to-subtree ()
  7925. "Narrow buffer to the current subtree."
  7926. (interactive)
  7927. (save-excursion
  7928. (save-match-data
  7929. (org-with-limited-levels
  7930. (narrow-to-region
  7931. (progn (org-back-to-heading t) (point))
  7932. (progn (org-end-of-subtree t t)
  7933. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7934. (point)))))))
  7935. (defun org-narrow-to-block ()
  7936. "Narrow buffer to the current block."
  7937. (interactive)
  7938. (let* ((case-fold-search t)
  7939. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7940. "^[ \t]*#\\+end_.*")))
  7941. (if blockp
  7942. (narrow-to-region (car blockp) (cdr blockp))
  7943. (user-error "Not in a block"))))
  7944. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7945. "Clone the task (subtree) at point N times.
  7946. The clones will be inserted as siblings.
  7947. In interactive use, the user will be prompted for the number of
  7948. clones to be produced. If the entry has a timestamp, the user
  7949. will also be prompted for a time shift, which may be a repeater
  7950. as used in time stamps, for example `+3d'. To disable this,
  7951. you can call the function with a universal prefix argument.
  7952. When a valid repeater is given and the entry contains any time
  7953. stamps, the clones will become a sequence in time, with time
  7954. stamps in the subtree shifted for each clone produced. If SHIFT
  7955. is nil or the empty string, time stamps will be left alone. The
  7956. ID property of the original subtree is removed.
  7957. In each clone, all the CLOCK entries will be removed. This
  7958. prevents Org from considering that the clocked times overlap.
  7959. If the original subtree did contain time stamps with a repeater,
  7960. the following will happen:
  7961. - the repeater will be removed in each clone
  7962. - an additional clone will be produced, with the current, unshifted
  7963. date(s) in the entry.
  7964. - the original entry will be placed *after* all the clones, with
  7965. repeater intact.
  7966. - the start days in the repeater in the original entry will be shifted
  7967. to past the last clone.
  7968. In this way you can spell out a number of instances of a repeating task,
  7969. and still retain the repeater to cover future instances of the task.
  7970. As described above, N+1 clones are produced when the original
  7971. subtree has a repeater. Setting N to 0, then, can be used to
  7972. remove the repeater from a subtree and create a shifted clone
  7973. with the original repeater."
  7974. (interactive "nNumber of clones to produce: ")
  7975. (let ((shift
  7976. (or shift
  7977. (if (and (not (equal current-prefix-arg '(4)))
  7978. (save-excursion
  7979. (re-search-forward org-ts-regexp-both
  7980. (save-excursion
  7981. (org-end-of-subtree t)
  7982. (point)) t)))
  7983. (read-from-minibuffer
  7984. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7985. ""))) ;; No time shift
  7986. (n-no-remove -1)
  7987. (drawer-re org-drawer-regexp)
  7988. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7989. beg end template task idprop
  7990. shift-n shift-what doshift nmin nmax)
  7991. (unless (wholenump n)
  7992. (user-error "Invalid number of replications %s" n))
  7993. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7994. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7995. shift)))
  7996. (user-error "Invalid shift specification %s" shift))
  7997. (when doshift
  7998. (setq shift-n (string-to-number (match-string 1 shift))
  7999. shift-what (cdr (assoc (match-string 2 shift)
  8000. '(("d" . day) ("w" . week)
  8001. ("m" . month) ("y" . year))))))
  8002. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  8003. (setq nmin 1 nmax n)
  8004. (org-back-to-heading t)
  8005. (setq beg (point))
  8006. (setq idprop (org-entry-get nil "ID"))
  8007. (org-end-of-subtree t t)
  8008. (or (bolp) (insert "\n"))
  8009. (setq end (point))
  8010. (setq template (buffer-substring beg end))
  8011. (when (and doshift
  8012. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  8013. (delete-region beg end)
  8014. (setq end beg)
  8015. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  8016. (goto-char end)
  8017. (cl-loop for n from nmin to nmax do
  8018. ;; prepare clone
  8019. (with-temp-buffer
  8020. (insert template)
  8021. (org-mode)
  8022. (goto-char (point-min))
  8023. (org-show-subtree)
  8024. (and idprop (if org-clone-delete-id
  8025. (org-entry-delete nil "ID")
  8026. (org-id-get-create t)))
  8027. (unless (= n 0)
  8028. (while (re-search-forward org-clock-re nil t)
  8029. (kill-whole-line))
  8030. (goto-char (point-min))
  8031. (while (re-search-forward drawer-re nil t)
  8032. (org-remove-empty-drawer-at (point))))
  8033. (goto-char (point-min))
  8034. (when doshift
  8035. (while (re-search-forward org-ts-regexp-both nil t)
  8036. (org-timestamp-change (* n shift-n) shift-what))
  8037. (unless (= n n-no-remove)
  8038. (goto-char (point-min))
  8039. (while (re-search-forward org-ts-regexp nil t)
  8040. (save-excursion
  8041. (goto-char (match-beginning 0))
  8042. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8043. (delete-region (match-beginning 1) (match-end 1)))))))
  8044. (setq task (buffer-string)))
  8045. (insert task))
  8046. (goto-char beg)))
  8047. ;;; Outline Sorting
  8048. (defun org-sort (with-case)
  8049. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8050. Optional argument WITH-CASE means sort case-sensitively."
  8051. (interactive "P")
  8052. (cond
  8053. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8054. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8055. (t
  8056. (org-call-with-arg 'org-sort-entries with-case))))
  8057. (defun org-sort-remove-invisible (s)
  8058. "Remove invisible links from string S."
  8059. (remove-text-properties 0 (length s) org-rm-props s)
  8060. (while (string-match org-bracket-link-regexp s)
  8061. (setq s (replace-match (if (match-end 2)
  8062. (match-string 3 s)
  8063. (match-string 1 s))
  8064. t t s)))
  8065. (let ((st (format " %s " s)))
  8066. (while (string-match org-emph-re st)
  8067. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8068. (setq s (substring st 1 -1)))
  8069. s)
  8070. (defvar org-priority-regexp) ; defined later in the file
  8071. (defvar org-after-sorting-entries-or-items-hook nil
  8072. "Hook that is run after a bunch of entries or items have been sorted.
  8073. When children are sorted, the cursor is in the parent line when this
  8074. hook gets called. When a region or a plain list is sorted, the cursor
  8075. will be in the first entry of the sorted region/list.")
  8076. (defun org-sort-entries
  8077. (&optional with-case sorting-type getkey-func compare-func property)
  8078. "Sort entries on a certain level of an outline tree.
  8079. If there is an active region, the entries in the region are sorted.
  8080. Else, if the cursor is before the first entry, sort the top-level items.
  8081. Else, the children of the entry at point are sorted.
  8082. Sorting can be alphabetically, numerically, by date/time as given by
  8083. a time stamp, by a property, by priority order, or by a custom function.
  8084. The command prompts for the sorting type unless it has been given to the
  8085. function through the SORTING-TYPE argument, which needs to be a character,
  8086. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8087. the precise meaning of each character:
  8088. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8089. c By creation time, which is assumed to be the first inactive time stamp
  8090. at the beginning of a line.
  8091. d By deadline date/time.
  8092. k By clocking time.
  8093. n Numerically, by converting the beginning of the entry/item to a number.
  8094. o By order of TODO keywords.
  8095. p By priority according to the cookie.
  8096. r By the value of a property.
  8097. s By scheduled date/time.
  8098. t By date/time, either the first active time stamp in the entry, or, if
  8099. none exist, by the first inactive one.
  8100. Capital letters will reverse the sort order.
  8101. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8102. called with point at the beginning of the record. It must return either
  8103. a string or a number that should serve as the sorting key for that record.
  8104. Comparing entries ignores case by default. However, with an optional argument
  8105. WITH-CASE, the sorting considers case as well.
  8106. Sorting is done against the visible part of the headlines, it ignores hidden
  8107. links.
  8108. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8109. (interactive "P")
  8110. (let ((case-func (if with-case 'identity 'downcase))
  8111. (cmstr
  8112. ;; The clock marker is lost when using `sort-subr', let's
  8113. ;; store the clocking string.
  8114. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8115. (save-excursion
  8116. (goto-char org-clock-marker)
  8117. (buffer-substring-no-properties (line-beginning-position)
  8118. (point)))))
  8119. start beg end stars re re2
  8120. txt what tmp)
  8121. ;; Find beginning and end of region to sort
  8122. (cond
  8123. ((org-region-active-p)
  8124. ;; we will sort the region
  8125. (setq end (region-end)
  8126. what "region")
  8127. (goto-char (region-beginning))
  8128. (unless (org-at-heading-p) (outline-next-heading))
  8129. (setq start (point)))
  8130. ((or (org-at-heading-p)
  8131. (ignore-errors (progn (org-back-to-heading) t)))
  8132. ;; we will sort the children of the current headline
  8133. (org-back-to-heading)
  8134. (setq start (point)
  8135. end (progn (org-end-of-subtree t t)
  8136. (or (bolp) (insert "\n"))
  8137. (when (>= (org-back-over-empty-lines) 1)
  8138. (forward-line 1))
  8139. (point))
  8140. what "children")
  8141. (goto-char start)
  8142. (outline-show-subtree)
  8143. (outline-next-heading))
  8144. (t
  8145. ;; we will sort the top-level entries in this file
  8146. (goto-char (point-min))
  8147. (or (org-at-heading-p) (outline-next-heading))
  8148. (setq start (point))
  8149. (goto-char (point-max))
  8150. (beginning-of-line 1)
  8151. (when (looking-at ".*?\\S-")
  8152. ;; File ends in a non-white line
  8153. (end-of-line 1)
  8154. (insert "\n"))
  8155. (setq end (point-max))
  8156. (setq what "top-level")
  8157. (goto-char start)
  8158. (outline-show-all)))
  8159. (setq beg (point))
  8160. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8161. (looking-at "\\(\\*+\\)")
  8162. (setq stars (match-string 1)
  8163. re (concat "^" (regexp-quote stars) " +")
  8164. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8165. txt (buffer-substring beg end))
  8166. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8167. (when (and (not (equal stars "*")) (string-match re2 txt))
  8168. (user-error "Region to sort contains a level above the first entry"))
  8169. (unless sorting-type
  8170. (message
  8171. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8172. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8173. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8174. what)
  8175. (setq sorting-type (read-char-exclusive))
  8176. (unless getkey-func
  8177. (and (= (downcase sorting-type) ?f)
  8178. (setq getkey-func
  8179. (completing-read "Sort using function: "
  8180. obarray 'fboundp t nil nil))
  8181. (setq getkey-func (intern getkey-func))))
  8182. (and (= (downcase sorting-type) ?r)
  8183. (not property)
  8184. (setq property
  8185. (completing-read "Property: "
  8186. (mapcar #'list (org-buffer-property-keys t))
  8187. nil t))))
  8188. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8189. (message "Sorting entries...")
  8190. (save-restriction
  8191. (narrow-to-region start end)
  8192. (let ((dcst (downcase sorting-type))
  8193. (case-fold-search nil)
  8194. (now (current-time)))
  8195. (sort-subr
  8196. (/= dcst sorting-type)
  8197. ;; This function moves to the beginning character of the "record" to
  8198. ;; be sorted.
  8199. (lambda nil
  8200. (if (re-search-forward re nil t)
  8201. (goto-char (match-beginning 0))
  8202. (goto-char (point-max))))
  8203. ;; This function moves to the last character of the "record" being
  8204. ;; sorted.
  8205. (lambda nil
  8206. (save-match-data
  8207. (condition-case nil
  8208. (outline-forward-same-level 1)
  8209. (error
  8210. (goto-char (point-max))))))
  8211. ;; This function returns the value that gets sorted against.
  8212. (lambda nil
  8213. (cond
  8214. ((= dcst ?n)
  8215. (if (looking-at org-complex-heading-regexp)
  8216. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8217. nil))
  8218. ((= dcst ?a)
  8219. (if (looking-at org-complex-heading-regexp)
  8220. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8221. nil))
  8222. ((= dcst ?k)
  8223. (or (get-text-property (point) :org-clock-minutes) 0))
  8224. ((= dcst ?t)
  8225. (let ((end (save-excursion (outline-next-heading) (point))))
  8226. (if (or (re-search-forward org-ts-regexp end t)
  8227. (re-search-forward org-ts-regexp-both end t))
  8228. (org-time-string-to-seconds (match-string 0))
  8229. (float-time now))))
  8230. ((= dcst ?c)
  8231. (let ((end (save-excursion (outline-next-heading) (point))))
  8232. (if (re-search-forward
  8233. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8234. end t)
  8235. (org-time-string-to-seconds (match-string 0))
  8236. (float-time now))))
  8237. ((= dcst ?s)
  8238. (let ((end (save-excursion (outline-next-heading) (point))))
  8239. (if (re-search-forward org-scheduled-time-regexp end t)
  8240. (org-time-string-to-seconds (match-string 1))
  8241. (float-time now))))
  8242. ((= dcst ?d)
  8243. (let ((end (save-excursion (outline-next-heading) (point))))
  8244. (if (re-search-forward org-deadline-time-regexp end t)
  8245. (org-time-string-to-seconds (match-string 1))
  8246. (float-time now))))
  8247. ((= dcst ?p)
  8248. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8249. (string-to-char (match-string 2))
  8250. org-default-priority))
  8251. ((= dcst ?r)
  8252. (or (org-entry-get nil property) ""))
  8253. ((= dcst ?o)
  8254. (when (looking-at org-complex-heading-regexp)
  8255. (let* ((m (match-string 2))
  8256. (s (if (member m org-done-keywords) '- '+)))
  8257. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8258. ((= dcst ?f)
  8259. (if getkey-func
  8260. (progn
  8261. (setq tmp (funcall getkey-func))
  8262. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8263. tmp)
  8264. (error "Invalid key function `%s'" getkey-func)))
  8265. (t (error "Invalid sorting type `%c'" sorting-type))))
  8266. nil
  8267. (cond
  8268. ((= dcst ?a) 'string<)
  8269. ((= dcst ?f) compare-func)
  8270. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8271. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8272. ;; Reset the clock marker if needed
  8273. (when cmstr
  8274. (save-excursion
  8275. (goto-char start)
  8276. (search-forward cmstr nil t)
  8277. (move-marker org-clock-marker (point))))
  8278. (message "Sorting entries...done")))
  8279. ;;; The orgstruct minor mode
  8280. ;; Define a minor mode which can be used in other modes in order to
  8281. ;; integrate the Org mode structure editing commands.
  8282. ;; This is really a hack, because the Org mode structure commands use
  8283. ;; keys which normally belong to the major mode. Here is how it
  8284. ;; works: The minor mode defines all the keys necessary to operate the
  8285. ;; structure commands, but wraps the commands into a function which
  8286. ;; tests if the cursor is currently at a headline or a plain list
  8287. ;; item. If that is the case, the structure command is used,
  8288. ;; temporarily setting many Org mode variables like regular
  8289. ;; expressions for filling etc. However, when any of those keys is
  8290. ;; used at a different location, function uses `key-binding' to look
  8291. ;; up if the key has an associated command in another currently active
  8292. ;; keymap (minor modes, major mode, global), and executes that
  8293. ;; command. There might be problems if any of the keys is otherwise
  8294. ;; used as a prefix key.
  8295. (defcustom orgstruct-heading-prefix-regexp ""
  8296. "Regexp that matches the custom prefix of Org headlines in
  8297. orgstruct(++)-mode."
  8298. :group 'org
  8299. :version "24.4"
  8300. :package-version '(Org . "8.3")
  8301. :type 'regexp)
  8302. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8303. (defcustom orgstruct-setup-hook nil
  8304. "Hook run after orgstruct-mode-map is filled."
  8305. :group 'org
  8306. :version "24.4"
  8307. :package-version '(Org . "8.0")
  8308. :type 'hook)
  8309. (defvar orgstruct-initialized nil)
  8310. (defvar org-local-vars nil
  8311. "List of local variables, for use by `orgstruct-mode'.")
  8312. ;;;###autoload
  8313. (define-minor-mode orgstruct-mode
  8314. "Toggle the minor mode `orgstruct-mode'.
  8315. This mode is for using Org mode structure commands in other
  8316. modes. The following keys behave as if Org mode were active, if
  8317. the cursor is on a headline, or on a plain list item (both as
  8318. defined by Org mode)."
  8319. nil " OrgStruct" (make-sparse-keymap)
  8320. (funcall (if orgstruct-mode
  8321. 'add-to-invisibility-spec
  8322. 'remove-from-invisibility-spec)
  8323. '(outline . t))
  8324. (when orgstruct-mode
  8325. (org-load-modules-maybe)
  8326. (unless orgstruct-initialized
  8327. (orgstruct-setup)
  8328. (setq orgstruct-initialized t))))
  8329. ;;;###autoload
  8330. (defun turn-on-orgstruct ()
  8331. "Unconditionally turn on `orgstruct-mode'."
  8332. (orgstruct-mode 1))
  8333. (defvar-local orgstruct-is-++ nil
  8334. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8335. (defvar-local org-fb-vars nil)
  8336. (defun orgstruct++-mode (&optional arg)
  8337. "Toggle `orgstruct-mode', the enhanced version of it.
  8338. In addition to setting orgstruct-mode, this also exports all
  8339. indentation and autofilling variables from Org mode into the
  8340. buffer. It will also recognize item context in multiline items."
  8341. (interactive "P")
  8342. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8343. (if (< arg 1)
  8344. (progn (orgstruct-mode -1)
  8345. (dolist (v org-fb-vars)
  8346. (set (make-local-variable (car v))
  8347. (if (eq (car-safe (cadr v)) 'quote)
  8348. (cl-cadadr v)
  8349. (nth 1 v)))))
  8350. (orgstruct-mode 1)
  8351. (setq org-fb-vars nil)
  8352. (unless org-local-vars
  8353. (setq org-local-vars (org-get-local-variables)))
  8354. (let (var val)
  8355. (dolist (x org-local-vars)
  8356. (when (string-match
  8357. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8358. \\|fill-prefix\\|indent-\\)"
  8359. (symbol-name (car x)))
  8360. (setq var (car x) val (nth 1 x))
  8361. (push (list var `(quote ,(eval var))) org-fb-vars)
  8362. (set (make-local-variable var)
  8363. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8364. (setq-local orgstruct-is-++ t))))
  8365. ;;;###autoload
  8366. (defun turn-on-orgstruct++ ()
  8367. "Unconditionally turn on `orgstruct++-mode'."
  8368. (orgstruct++-mode 1))
  8369. (defun orgstruct-error ()
  8370. "Error when there is no default binding for a structure key."
  8371. (interactive)
  8372. (funcall (if (fboundp 'user-error)
  8373. 'user-error
  8374. 'error)
  8375. "This key has no function outside structure elements"))
  8376. (defun orgstruct-setup ()
  8377. "Setup orgstruct keymap."
  8378. (dolist (cell '((org-demote . t)
  8379. (org-metaleft . t)
  8380. (org-metaright . t)
  8381. (org-promote . t)
  8382. (org-shiftmetaleft . t)
  8383. (org-shiftmetaright . t)
  8384. org-backward-element
  8385. org-backward-heading-same-level
  8386. org-ctrl-c-ret
  8387. org-ctrl-c-minus
  8388. org-ctrl-c-star
  8389. org-cycle
  8390. org-force-cycle-archived
  8391. org-forward-heading-same-level
  8392. org-insert-heading
  8393. org-insert-heading-respect-content
  8394. org-kill-note-or-show-branches
  8395. org-mark-subtree
  8396. org-meta-return
  8397. org-metadown
  8398. org-metaup
  8399. org-narrow-to-subtree
  8400. org-promote-subtree
  8401. org-reveal
  8402. org-shiftdown
  8403. org-shiftleft
  8404. org-shiftmetadown
  8405. org-shiftmetaup
  8406. org-shiftright
  8407. org-shifttab
  8408. org-shifttab
  8409. org-shiftup
  8410. org-show-children
  8411. org-show-subtree
  8412. org-sort
  8413. org-up-element
  8414. outline-demote
  8415. outline-next-visible-heading
  8416. outline-previous-visible-heading
  8417. outline-promote
  8418. outline-up-heading))
  8419. (let ((f (or (car-safe cell) cell))
  8420. (disable-when-heading-prefix (cdr-safe cell)))
  8421. (when (fboundp f)
  8422. (let ((new-bindings))
  8423. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8424. (where-is-internal f outline-mode-map)))
  8425. (push binding new-bindings)
  8426. ;; TODO use local-function-key-map
  8427. (dolist (rep '(("<tab>" . "TAB")
  8428. ("<return>" . "RET")
  8429. ("<escape>" . "ESC")
  8430. ("<delete>" . "DEL")))
  8431. (setq binding (read-kbd-macro
  8432. (let ((case-fold-search))
  8433. (replace-regexp-in-string
  8434. (regexp-quote (cdr rep))
  8435. (car rep)
  8436. (key-description binding)))))
  8437. (cl-pushnew binding new-bindings :test 'equal)))
  8438. (dolist (binding new-bindings)
  8439. (let ((key (lookup-key orgstruct-mode-map binding)))
  8440. (when (or (not key) (numberp key))
  8441. (ignore-errors
  8442. (org-defkey orgstruct-mode-map
  8443. binding
  8444. (orgstruct-make-binding
  8445. f binding disable-when-heading-prefix))))))))))
  8446. (run-hooks 'orgstruct-setup-hook))
  8447. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8448. "Create a function for binding in the structure minor mode.
  8449. FUN is the command to call inside a table. KEY is the key that
  8450. should be checked in for a command to execute outside of tables.
  8451. Non-nil `disable-when-heading-prefix' means to disable the command
  8452. if `orgstruct-heading-prefix-regexp' is not empty."
  8453. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8454. (let ((nname name)
  8455. (i 0))
  8456. (while (fboundp (intern nname))
  8457. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8458. (setq name (intern nname)))
  8459. (eval
  8460. (let ((bindings '((org-heading-regexp
  8461. (concat "^"
  8462. orgstruct-heading-prefix-regexp
  8463. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8464. (org-outline-regexp
  8465. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8466. (org-outline-regexp-bol
  8467. (concat "^" org-outline-regexp))
  8468. (outline-regexp org-outline-regexp)
  8469. (outline-heading-end-regexp "\n")
  8470. (outline-level 'org-outline-level)
  8471. (outline-heading-alist))))
  8472. `(defun ,name (arg)
  8473. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8474. "Outside of structure, run the binding of `"
  8475. (key-description key) "'."
  8476. (when disable-when-heading-prefix
  8477. (concat
  8478. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8479. "back to the default binding due to limitations of Org's implementation of\n"
  8480. "`" (symbol-name fun) "'.")))
  8481. (interactive "p")
  8482. (let* ((disable
  8483. ,(and disable-when-heading-prefix
  8484. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8485. (fallback
  8486. (or disable
  8487. (not
  8488. (let* ,bindings
  8489. (org-context-p 'headline 'item
  8490. ,(when (memq fun
  8491. '(org-insert-heading
  8492. org-insert-heading-respect-content
  8493. org-meta-return))
  8494. '(when orgstruct-is-++
  8495. 'item-body))))))))
  8496. (if fallback
  8497. (let* ((orgstruct-mode)
  8498. (binding
  8499. (let ((key ,key))
  8500. (catch 'exit
  8501. (dolist
  8502. (rep
  8503. '(nil
  8504. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8505. ("<\\([^>]*\\)return>" . "\\1RET")
  8506. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8507. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8508. nil)
  8509. (when rep
  8510. (setq key (read-kbd-macro
  8511. (let ((case-fold-search))
  8512. (replace-regexp-in-string
  8513. (car rep)
  8514. (cdr rep)
  8515. (key-description key))))))
  8516. (when (key-binding key)
  8517. (throw 'exit (key-binding key))))))))
  8518. (if (keymapp binding)
  8519. (org-set-transient-map binding)
  8520. (let ((func (or binding
  8521. (unless disable
  8522. 'orgstruct-error))))
  8523. (when func
  8524. (call-interactively func)))))
  8525. (org-run-like-in-org-mode
  8526. (lambda ()
  8527. (interactive)
  8528. (let* ,bindings
  8529. (call-interactively ',fun)))))))))
  8530. name))
  8531. (defun org-contextualize-keys (alist contexts)
  8532. "Return valid elements in ALIST depending on CONTEXTS.
  8533. `org-agenda-custom-commands' or `org-capture-templates' are the
  8534. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8535. or `org-capture-templates-contexts' are the associated contexts
  8536. definitions."
  8537. (let ((contexts
  8538. ;; normalize contexts
  8539. (mapcar
  8540. (lambda(c) (cond ((listp (cadr c))
  8541. (list (car c) (car c) (nth 1 c)))
  8542. ((string= "" (cadr c))
  8543. (list (car c) (car c) (nth 2 c)))
  8544. (t c)))
  8545. contexts))
  8546. (a alist) r s)
  8547. ;; loop over all commands or templates
  8548. (dolist (c a)
  8549. (let (vrules repl)
  8550. (cond
  8551. ((not (assoc (car c) contexts))
  8552. (push c r))
  8553. ((and (assoc (car c) contexts)
  8554. (setq vrules (org-contextualize-validate-key
  8555. (car c) contexts)))
  8556. (mapc (lambda (vr)
  8557. (unless (equal (car vr) (cadr vr))
  8558. (setq repl vr)))
  8559. vrules)
  8560. (if (not repl) (push c r)
  8561. (push (cadr repl) s)
  8562. (push
  8563. (cons (car c)
  8564. (cdr (or (assoc (cadr repl) alist)
  8565. (error "Undefined key `%s' as contextual replacement for `%s'"
  8566. (cadr repl) (car c)))))
  8567. r))))))
  8568. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8569. (delq
  8570. nil
  8571. (delete-dups
  8572. (mapcar (lambda (x)
  8573. (let ((tpl (car x)))
  8574. (unless (delq
  8575. nil
  8576. (mapcar (lambda (y)
  8577. (equal y tpl))
  8578. s))
  8579. x)))
  8580. (reverse r))))))
  8581. (defun org-contextualize-validate-key (key contexts)
  8582. "Check CONTEXTS for agenda or capture KEY."
  8583. (let (res)
  8584. (dolist (r contexts)
  8585. (dolist (rr (car (last r)))
  8586. (when
  8587. (and (equal key (car r))
  8588. (if (functionp rr) (funcall rr)
  8589. (or (and (eq (car rr) 'in-file)
  8590. (buffer-file-name)
  8591. (string-match (cdr rr) (buffer-file-name)))
  8592. (and (eq (car rr) 'in-mode)
  8593. (string-match (cdr rr) (symbol-name major-mode)))
  8594. (and (eq (car rr) 'in-buffer)
  8595. (string-match (cdr rr) (buffer-name)))
  8596. (when (and (eq (car rr) 'not-in-file)
  8597. (buffer-file-name))
  8598. (not (string-match (cdr rr) (buffer-file-name))))
  8599. (when (eq (car rr) 'not-in-mode)
  8600. (not (string-match (cdr rr) (symbol-name major-mode))))
  8601. (when (eq (car rr) 'not-in-buffer)
  8602. (not (string-match (cdr rr) (buffer-name)))))))
  8603. (push r res))))
  8604. (delete-dups (delq nil res))))
  8605. (defun org-context-p (&rest contexts)
  8606. "Check if local context is any of CONTEXTS.
  8607. Possible values in the list of contexts are `table', `headline', and `item'."
  8608. (let ((pos (point)))
  8609. (goto-char (point-at-bol))
  8610. (prog1 (or (and (memq 'table contexts)
  8611. (looking-at "[ \t]*|"))
  8612. (and (memq 'headline contexts)
  8613. (looking-at org-outline-regexp))
  8614. (and (memq 'item contexts)
  8615. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8616. (and (memq 'item-body contexts)
  8617. (org-in-item-p)))
  8618. (goto-char pos))))
  8619. (defconst org-unique-local-variables
  8620. '(org-element--cache
  8621. org-element--cache-objects
  8622. org-element--cache-sync-keys
  8623. org-element--cache-sync-requests
  8624. org-element--cache-sync-timer)
  8625. "List of local variables that cannot be transferred to another buffer.")
  8626. (defun org-get-local-variables ()
  8627. "Return a list of all local variables in an Org mode buffer."
  8628. (delq nil
  8629. (mapcar
  8630. (lambda (x)
  8631. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8632. (name (car binding)))
  8633. (and (not (get name 'org-state))
  8634. (not (memq name org-unique-local-variables))
  8635. (string-match-p
  8636. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8637. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8638. (symbol-name name))
  8639. binding)))
  8640. (with-temp-buffer
  8641. (org-mode)
  8642. (buffer-local-variables)))))
  8643. (defun org-clone-local-variables (from-buffer &optional regexp)
  8644. "Clone local variables from FROM-BUFFER.
  8645. Optional argument REGEXP selects variables to clone."
  8646. (dolist (pair (buffer-local-variables from-buffer))
  8647. (let ((name (car pair)))
  8648. (when (and (symbolp name)
  8649. (not (memq name org-unique-local-variables))
  8650. (or (null regexp) (string-match regexp (symbol-name name))))
  8651. (set (make-local-variable name) (cdr pair))))))
  8652. ;;;###autoload
  8653. (defun org-run-like-in-org-mode (cmd)
  8654. "Run a command, pretending that the current buffer is in Org mode.
  8655. This will temporarily bind local variables that are typically bound in
  8656. Org mode to the values they have in Org mode, and then interactively
  8657. call CMD."
  8658. (org-load-modules-maybe)
  8659. (unless org-local-vars
  8660. (setq org-local-vars (org-get-local-variables)))
  8661. (let (binds)
  8662. (dolist (var org-local-vars)
  8663. (when (or (not (boundp (car var)))
  8664. (eq (symbol-value (car var))
  8665. (default-value (car var))))
  8666. (push (list (car var) `(quote ,(cadr var))) binds)))
  8667. (eval `(let ,binds
  8668. (call-interactively (quote ,cmd))))))
  8669. (defun org-get-category (&optional pos force-refresh)
  8670. "Get the category applying to position POS."
  8671. (save-match-data
  8672. (when force-refresh (org-refresh-category-properties))
  8673. (let ((pos (or pos (point))))
  8674. (or (get-text-property pos 'org-category)
  8675. (progn (org-refresh-category-properties)
  8676. (get-text-property pos 'org-category))))))
  8677. ;;; Refresh properties
  8678. (defun org-refresh-properties (dprop tprop)
  8679. "Refresh buffer text properties.
  8680. DPROP is the drawer property and TPROP is either the
  8681. corresponding text property to set, or an alist with each element
  8682. being a text property (as a symbol) and a function to apply to
  8683. the value of the drawer property."
  8684. (let ((case-fold-search t)
  8685. (inhibit-read-only t))
  8686. (org-with-silent-modifications
  8687. (org-with-wide-buffer
  8688. (goto-char (point-min))
  8689. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8690. (org-refresh-property tprop (match-string-no-properties 1)))))))
  8691. (defun org-refresh-property (tprop p)
  8692. "Refresh the buffer text property TPROP from the drawer property P.
  8693. The refresh happens only for the current tree (not subtree)."
  8694. (unless (org-before-first-heading-p)
  8695. (save-excursion
  8696. (org-back-to-heading t)
  8697. (if (symbolp tprop)
  8698. ;; TPROP is a text property symbol
  8699. (put-text-property
  8700. (point) (or (outline-next-heading) (point-max)) tprop p)
  8701. ;; TPROP is an alist with (properties . function) elements
  8702. (dolist (al tprop)
  8703. (save-excursion
  8704. (put-text-property
  8705. (line-beginning-position) (or (outline-next-heading) (point-max))
  8706. (car al)
  8707. (funcall (cdr al) p))))))))
  8708. (defun org-refresh-category-properties ()
  8709. "Refresh category text properties in the buffer."
  8710. (let ((case-fold-search t)
  8711. (inhibit-read-only t)
  8712. (default-category
  8713. (cond ((null org-category)
  8714. (if buffer-file-name
  8715. (file-name-sans-extension
  8716. (file-name-nondirectory buffer-file-name))
  8717. "???"))
  8718. ((symbolp org-category) (symbol-name org-category))
  8719. (t org-category))))
  8720. (org-with-silent-modifications
  8721. (org-with-wide-buffer
  8722. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8723. ;; This is the default category for the buffer. If none is
  8724. ;; found, fall-back to `org-category' or buffer file name.
  8725. (put-text-property
  8726. (point-min) (point-max)
  8727. 'org-category
  8728. (catch 'buffer-category
  8729. (goto-char (point-max))
  8730. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8731. (let ((element (org-element-at-point)))
  8732. (when (eq (org-element-type element) 'keyword)
  8733. (throw 'buffer-category
  8734. (org-element-property :value element)))))
  8735. default-category))
  8736. ;; Set sub-tree specific categories.
  8737. (goto-char (point-min))
  8738. (let ((regexp (org-re-property "CATEGORY")))
  8739. (while (re-search-forward regexp nil t)
  8740. (let ((value (match-string-no-properties 3)))
  8741. (when (org-at-property-p)
  8742. (put-text-property
  8743. (save-excursion (org-back-to-heading t) (point))
  8744. (save-excursion (org-end-of-subtree t t) (point))
  8745. 'org-category
  8746. value)))))))))
  8747. (defun org-refresh-stats-properties ()
  8748. "Refresh stats text properties in the buffer."
  8749. (let (stats)
  8750. (org-with-silent-modifications
  8751. (org-with-wide-buffer
  8752. (goto-char (point-min))
  8753. (while (re-search-forward
  8754. (concat org-outline-regexp-bol ".*"
  8755. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8756. nil t)
  8757. (setq stats (cond ((equal (match-string 3) "0") 0)
  8758. ((match-string 2)
  8759. (/ (* (string-to-number (match-string 2)) 100)
  8760. (string-to-number (match-string 3))))
  8761. (t (string-to-number (match-string 1)))))
  8762. (org-back-to-heading t)
  8763. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8764. 'org-stats stats))))))
  8765. (defun org-refresh-effort-properties ()
  8766. "Refresh effort properties"
  8767. (org-refresh-properties
  8768. org-effort-property
  8769. '((effort . identity)
  8770. (effort-minutes . org-duration-string-to-minutes))))
  8771. ;;;; Link Stuff
  8772. ;;; Link abbreviations
  8773. (defun org-link-expand-abbrev (link)
  8774. "Apply replacements as defined in `org-link-abbrev-alist'."
  8775. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8776. (let* ((key (match-string 1 link))
  8777. (as (or (assoc key org-link-abbrev-alist-local)
  8778. (assoc key org-link-abbrev-alist)))
  8779. (tag (and (match-end 2) (match-string 3 link)))
  8780. rpl)
  8781. (if (not as)
  8782. link
  8783. (setq rpl (cdr as))
  8784. (cond
  8785. ((symbolp rpl) (funcall rpl tag))
  8786. ((string-match "%(\\([^)]+\\))" rpl)
  8787. (replace-match
  8788. (save-match-data
  8789. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8790. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8791. ((string-match "%h" rpl)
  8792. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8793. (t (concat rpl tag)))))
  8794. link))
  8795. ;;; Storing and inserting links
  8796. (defvar org-insert-link-history nil
  8797. "Minibuffer history for links inserted with `org-insert-link'.")
  8798. (defvar org-stored-links nil
  8799. "Contains the links stored with `org-store-link'.")
  8800. (defvar org-store-link-plist nil
  8801. "Plist with info about the most recently link created with `org-store-link'.")
  8802. (defun org-store-link-functions ()
  8803. "Return a list of functions that are called to create and store a link.
  8804. The functions defined in the :store property of
  8805. `org-link-parameters'.
  8806. Each function will be called in turn until one returns a non-nil
  8807. value. Each function should check if it is responsible for
  8808. creating this link (for example by looking at the major mode).
  8809. If not, it must exit and return nil. If yes, it should return
  8810. a non-nil value after calling `org-store-link-props' with a list
  8811. of properties and values. Special properties are:
  8812. :type The link prefix, like \"http\". This must be given.
  8813. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8814. This is obligatory as well.
  8815. :description Optional default description for the second pair
  8816. of brackets in an Org mode link. The user can still change
  8817. this when inserting this link into an Org mode buffer.
  8818. In addition to these, any additional properties can be specified
  8819. and then used in capture templates."
  8820. (cl-loop for link in org-link-parameters
  8821. with store-func
  8822. do (setq store-func (org-link-get-parameter (car link) :store))
  8823. if store-func
  8824. collect store-func))
  8825. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8826. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8827. ;;;###autoload
  8828. (defun org-store-link (arg)
  8829. "Store an org-link to the current location.
  8830. \\<org-mode-map>
  8831. This link is added to `org-stored-links' and can later be inserted
  8832. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8833. For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
  8834. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8835. For file links, ARG negates `org-context-in-file-links'.
  8836. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8837. skipping storing functions that are not
  8838. part of Org core.
  8839. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8840. prefix ARG forces storing a link for each line in the
  8841. active region."
  8842. (interactive "P")
  8843. (org-load-modules-maybe)
  8844. (if (and (equal arg '(64)) (org-region-active-p))
  8845. (save-excursion
  8846. (let ((end (region-end)))
  8847. (goto-char (region-beginning))
  8848. (set-mark (point))
  8849. (while (< (point-at-eol) end)
  8850. (move-end-of-line 1) (activate-mark)
  8851. (let (current-prefix-arg)
  8852. (call-interactively 'org-store-link))
  8853. (move-beginning-of-line 2)
  8854. (set-mark (point)))))
  8855. (setq org-store-link-plist nil)
  8856. (let (link cpltxt desc description search
  8857. txt custom-id agenda-link sfuns sfunsn)
  8858. (cond
  8859. ;; Store a link using an external link type
  8860. ((and (not (equal arg '(16)))
  8861. (setq sfuns
  8862. (delq
  8863. nil (mapcar (lambda (f)
  8864. (let (fs) (if (funcall f) (push f fs))))
  8865. (org-store-link-functions)))
  8866. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8867. (or (and (cdr sfuns)
  8868. (funcall (intern
  8869. (completing-read
  8870. "Which function for creating the link? "
  8871. sfunsn nil t (car sfunsn)))))
  8872. (funcall (caar sfuns)))
  8873. (setq link (plist-get org-store-link-plist :link)
  8874. desc (or (plist-get org-store-link-plist
  8875. :description)
  8876. link))))
  8877. ;; Store a link from a source code buffer.
  8878. ((org-src-edit-buffer-p)
  8879. (let ((coderef-format (org-src-coderef-format)))
  8880. (cond ((save-excursion
  8881. (beginning-of-line)
  8882. (looking-at (org-src-coderef-regexp coderef-format)))
  8883. (setq link (format "(%s)" (match-string-no-properties 3))))
  8884. ((called-interactively-p 'any)
  8885. (let ((label (read-string "Code line label: ")))
  8886. (end-of-line)
  8887. (setq link (format coderef-format label))
  8888. (let ((gc (- 79 (length link))))
  8889. (if (< (current-column) gc)
  8890. (org-move-to-column gc t)
  8891. (insert " ")))
  8892. (insert link)
  8893. (setq link (concat "(" label ")"))
  8894. (setq desc nil)))
  8895. (t (setq link nil)))))
  8896. ;; We are in the agenda, link to referenced location
  8897. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8898. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8899. (get-text-property (point) 'org-marker))))
  8900. (when m
  8901. (org-with-point-at m
  8902. (setq agenda-link
  8903. (if (called-interactively-p 'any)
  8904. (call-interactively 'org-store-link)
  8905. (org-store-link nil)))))))
  8906. ((eq major-mode 'calendar-mode)
  8907. (let ((cd (calendar-cursor-to-date)))
  8908. (setq link
  8909. (format-time-string
  8910. (car org-time-stamp-formats)
  8911. (apply 'encode-time
  8912. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8913. nil nil nil))))
  8914. (org-store-link-props :type "calendar" :date cd)))
  8915. ((eq major-mode 'help-mode)
  8916. (setq link (concat "help:" (save-excursion
  8917. (goto-char (point-min))
  8918. (looking-at "^[^ ]+")
  8919. (match-string 0))))
  8920. (org-store-link-props :type "help"))
  8921. ((eq major-mode 'w3-mode)
  8922. (setq cpltxt (if (and (buffer-name)
  8923. (not (string-match "Untitled" (buffer-name))))
  8924. (buffer-name)
  8925. (url-view-url t))
  8926. link (url-view-url t))
  8927. (org-store-link-props :type "w3" :url (url-view-url t)))
  8928. ((eq major-mode 'image-mode)
  8929. (setq cpltxt (concat "file:"
  8930. (abbreviate-file-name buffer-file-name))
  8931. link cpltxt)
  8932. (org-store-link-props :type "image" :file buffer-file-name))
  8933. ;; In dired, store a link to the file of the current line
  8934. ((derived-mode-p 'dired-mode)
  8935. (let ((file (dired-get-filename nil t)))
  8936. (setq file (if file
  8937. (abbreviate-file-name
  8938. (expand-file-name (dired-get-filename nil t)))
  8939. ;; otherwise, no file so use current directory.
  8940. default-directory))
  8941. (setq cpltxt (concat "file:" file)
  8942. link cpltxt)))
  8943. ((setq search (run-hook-with-args-until-success
  8944. 'org-create-file-search-functions))
  8945. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8946. "::" search))
  8947. (setq cpltxt (or description link)))
  8948. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8949. (org-with-limited-levels
  8950. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8951. (cond
  8952. ;; Store a link using the target at point
  8953. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8954. (setq cpltxt
  8955. (concat "file:"
  8956. (abbreviate-file-name
  8957. (buffer-file-name (buffer-base-buffer)))
  8958. "::" (match-string 1))
  8959. link cpltxt))
  8960. ((and (featurep 'org-id)
  8961. (or (eq org-id-link-to-org-use-id t)
  8962. (and (called-interactively-p 'any)
  8963. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8964. (and (eq org-id-link-to-org-use-id
  8965. 'create-if-interactive-and-no-custom-id)
  8966. (not custom-id))))
  8967. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8968. ;; Store a link using the ID at point
  8969. (setq link (condition-case nil
  8970. (prog1 (org-id-store-link)
  8971. (setq desc (or (plist-get org-store-link-plist
  8972. :description)
  8973. "")))
  8974. (error
  8975. ;; Probably before first headline, link only to file
  8976. (concat "file:"
  8977. (abbreviate-file-name
  8978. (buffer-file-name (buffer-base-buffer))))))))
  8979. (t
  8980. ;; Just link to current headline
  8981. (setq cpltxt (concat "file:"
  8982. (abbreviate-file-name
  8983. (buffer-file-name (buffer-base-buffer)))))
  8984. ;; Add a context search string
  8985. (when (org-xor org-context-in-file-links arg)
  8986. (let* ((element (org-element-at-point))
  8987. (name (org-element-property :name element)))
  8988. (setq txt (cond
  8989. ((org-at-heading-p) nil)
  8990. (name)
  8991. ((org-region-active-p)
  8992. (buffer-substring (region-beginning) (region-end)))))
  8993. (when (or (null txt) (string-match "\\S-" txt))
  8994. (setq cpltxt
  8995. (concat cpltxt "::"
  8996. (condition-case nil
  8997. (org-make-org-heading-search-string txt)
  8998. (error "")))
  8999. desc (or name
  9000. (nth 4 (ignore-errors (org-heading-components)))
  9001. "NONE")))))
  9002. (when (string-match "::\\'" cpltxt)
  9003. (setq cpltxt (substring cpltxt 0 -2)))
  9004. (setq link cpltxt)))))
  9005. ((buffer-file-name (buffer-base-buffer))
  9006. ;; Just link to this file here.
  9007. (setq cpltxt (concat "file:"
  9008. (abbreviate-file-name
  9009. (buffer-file-name (buffer-base-buffer)))))
  9010. ;; Add a context string.
  9011. (when (org-xor org-context-in-file-links arg)
  9012. (setq txt (if (org-region-active-p)
  9013. (buffer-substring (region-beginning) (region-end))
  9014. (buffer-substring (point-at-bol) (point-at-eol))))
  9015. ;; Only use search option if there is some text.
  9016. (when (string-match "\\S-" txt)
  9017. (setq cpltxt
  9018. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  9019. desc "NONE")))
  9020. (setq link cpltxt))
  9021. ((called-interactively-p 'interactive)
  9022. (user-error "No method for storing a link from this buffer"))
  9023. (t (setq link nil)))
  9024. ;; We're done setting link and desc, clean up
  9025. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9026. (setq link (or link cpltxt)
  9027. desc (or desc cpltxt))
  9028. (cond ((not desc))
  9029. ((equal desc "NONE") (setq desc nil))
  9030. (t (setq desc
  9031. (replace-regexp-in-string
  9032. org-bracket-link-analytic-regexp
  9033. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9034. desc))))
  9035. ;; Return the link
  9036. (if (not (and (or (called-interactively-p 'any)
  9037. executing-kbd-macro)
  9038. link))
  9039. (or agenda-link (and link (org-make-link-string link desc)))
  9040. (push (list link desc) org-stored-links)
  9041. (message "Stored: %s" (or desc link))
  9042. (when custom-id
  9043. (setq link (concat "file:" (abbreviate-file-name
  9044. (buffer-file-name)) "::#" custom-id))
  9045. (push (list link desc) org-stored-links))
  9046. (car org-stored-links)))))
  9047. (defun org-store-link-props (&rest plist)
  9048. "Store link properties, extract names, addresses and dates."
  9049. (let ((x (plist-get plist :from)))
  9050. (when x
  9051. (let ((adr (mail-extract-address-components x)))
  9052. (setq plist (plist-put plist :fromname (car adr)))
  9053. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9054. (let ((x (plist-get plist :to)))
  9055. (when x
  9056. (let ((adr (mail-extract-address-components x)))
  9057. (setq plist (plist-put plist :toname (car adr)))
  9058. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9059. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9060. (when x
  9061. (setq plist (plist-put plist :date-timestamp
  9062. (format-time-string
  9063. (org-time-stamp-format t) x)))
  9064. (setq plist (plist-put plist :date-timestamp-inactive
  9065. (format-time-string
  9066. (org-time-stamp-format t t) x)))))
  9067. (let ((from (plist-get plist :from))
  9068. (to (plist-get plist :to)))
  9069. (when (and from to org-from-is-user-regexp)
  9070. (setq plist
  9071. (plist-put plist :fromto
  9072. (if (string-match org-from-is-user-regexp from)
  9073. (concat "to %t")
  9074. (concat "from %f"))))))
  9075. (setq org-store-link-plist plist))
  9076. (defun org-add-link-props (&rest plist)
  9077. "Add these properties to the link property list."
  9078. (let (key value)
  9079. (while plist
  9080. (setq key (pop plist) value (pop plist))
  9081. (setq org-store-link-plist
  9082. (plist-put org-store-link-plist key value)))))
  9083. (defun org-email-link-description (&optional fmt)
  9084. "Return the description part of an email link.
  9085. This takes information from `org-store-link-plist' and formats it
  9086. according to FMT (default from `org-email-link-description-format')."
  9087. (setq fmt (or fmt org-email-link-description-format))
  9088. (let* ((p org-store-link-plist)
  9089. (to (plist-get p :toaddress))
  9090. (from (plist-get p :fromaddress))
  9091. (table
  9092. (list
  9093. (cons "%c" (plist-get p :fromto))
  9094. (cons "%F" (plist-get p :from))
  9095. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9096. (cons "%T" (plist-get p :to))
  9097. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9098. (cons "%s" (plist-get p :subject))
  9099. (cons "%d" (plist-get p :date))
  9100. (cons "%m" (plist-get p :message-id)))))
  9101. (when (string-match "%c" fmt)
  9102. ;; Check if the user wrote this message
  9103. (if (and org-from-is-user-regexp from to
  9104. (save-match-data (string-match org-from-is-user-regexp from)))
  9105. (setq fmt (replace-match "to %t" t t fmt))
  9106. (setq fmt (replace-match "from %f" t t fmt))))
  9107. (org-replace-escapes fmt table)))
  9108. (defun org-make-org-heading-search-string (&optional string)
  9109. "Make search string for the current headline or STRING."
  9110. (let ((s (or string
  9111. (and (derived-mode-p 'org-mode)
  9112. (save-excursion
  9113. (org-back-to-heading t)
  9114. (org-element-property :raw-value (org-element-at-point))))))
  9115. (lines org-context-in-file-links))
  9116. (or string (setq s (concat "*" s))) ; Add * for headlines
  9117. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9118. (when (and string (integerp lines) (> lines 0))
  9119. (let ((slines (org-split-string s "\n")))
  9120. (when (< lines (length slines))
  9121. (setq s (mapconcat
  9122. 'identity
  9123. (reverse (nthcdr (- (length slines) lines)
  9124. (reverse slines))) "\n")))))
  9125. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9126. (defun org-make-link-string (link &optional description)
  9127. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9128. (unless (org-string-nw-p link) (error "Empty link"))
  9129. (let ((uri (cond ((string-match org-link-types-re link)
  9130. (concat (match-string 1 link)
  9131. (org-link-escape (substring link (match-end 1)))))
  9132. ;; For readability, url-encode internal links only
  9133. ;; when absolutely needed (i.e, when they contain
  9134. ;; square brackets). File links however, are
  9135. ;; encoded since, e.g., spaces are significant.
  9136. ((or (file-name-absolute-p link)
  9137. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9138. (org-link-escape link))
  9139. (t link)))
  9140. (description
  9141. (and (org-string-nw-p description)
  9142. ;; Remove brackets from description, as they are fatal.
  9143. (replace-regexp-in-string
  9144. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9145. (org-trim description)))))
  9146. (format "[[%s]%s]"
  9147. uri
  9148. (if description (format "[%s]" description) ""))))
  9149. (defconst org-link-escape-chars
  9150. ;;%20 %5B %5D %25
  9151. '(?\s ?\[ ?\] ?%)
  9152. "List of characters that should be escaped in a link when stored to Org.
  9153. This is the list that is used for internal purposes.")
  9154. (defun org-link-escape (text &optional table merge)
  9155. "Return percent escaped representation of TEXT.
  9156. TEXT is a string with the text to escape.
  9157. Optional argument TABLE is a list with characters that should be
  9158. escaped. When nil, `org-link-escape-chars' is used.
  9159. If optional argument MERGE is set, merge TABLE into
  9160. `org-link-escape-chars'."
  9161. (let ((characters-to-encode
  9162. (cond ((null table) org-link-escape-chars)
  9163. (merge (append org-link-escape-chars table))
  9164. (t table))))
  9165. (mapconcat
  9166. (lambda (c)
  9167. (if (or (memq c characters-to-encode)
  9168. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9169. (mapconcat (lambda (e) (format "%%%.2X" e))
  9170. (or (encode-coding-char c 'utf-8)
  9171. (error "Unable to percent escape character: %c" c))
  9172. "")
  9173. (char-to-string c)))
  9174. text "")))
  9175. (defun org-link-unescape (str)
  9176. "Unhex hexified Unicode parts in string STR.
  9177. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9178. reciprocal of `org-link-escape', which see."
  9179. (if (org-string-nw-p str)
  9180. (replace-regexp-in-string
  9181. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9182. str))
  9183. (defun org-link-unescape-compound (hex)
  9184. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9185. Note: this function also decodes single byte encodings like
  9186. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9187. (save-match-data
  9188. (let* ((bytes (cdr (split-string hex "%")))
  9189. (ret "")
  9190. (eat 0)
  9191. (sum 0))
  9192. (while bytes
  9193. (let* ((val (string-to-number (pop bytes) 16))
  9194. (shift-xor
  9195. (if (= 0 eat)
  9196. (cond
  9197. ((>= val 252) (cons 6 252))
  9198. ((>= val 248) (cons 5 248))
  9199. ((>= val 240) (cons 4 240))
  9200. ((>= val 224) (cons 3 224))
  9201. ((>= val 192) (cons 2 192))
  9202. (t (cons 0 0)))
  9203. (cons 6 128))))
  9204. (when (>= val 192) (setq eat (car shift-xor)))
  9205. (setq val (logxor val (cdr shift-xor)))
  9206. (setq sum (+ (lsh sum (car shift-xor)) val))
  9207. (when (> eat 0) (setq eat (- eat 1)))
  9208. (cond
  9209. ((= 0 eat) ;multi byte
  9210. (setq ret (concat ret (char-to-string sum)))
  9211. (setq sum 0))
  9212. ((not bytes) ; single byte(s)
  9213. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9214. ret)))
  9215. (defun org-link-unescape-single-byte-sequence (hex)
  9216. "Unhexify hex-encoded single byte character sequences."
  9217. (mapconcat (lambda (byte)
  9218. (char-to-string (string-to-number byte 16)))
  9219. (cdr (split-string hex "%")) ""))
  9220. (defun org-xor (a b)
  9221. "Exclusive or."
  9222. (if a (not b) b))
  9223. (defun org-fixup-message-id-for-http (s)
  9224. "Replace special characters in a message id, so it can be used in an http query."
  9225. (when (string-match "%" s)
  9226. (setq s (mapconcat (lambda (c)
  9227. (if (eq c ?%)
  9228. "%25"
  9229. (char-to-string c)))
  9230. s "")))
  9231. (while (string-match "<" s)
  9232. (setq s (replace-match "%3C" t t s)))
  9233. (while (string-match ">" s)
  9234. (setq s (replace-match "%3E" t t s)))
  9235. (while (string-match "@" s)
  9236. (setq s (replace-match "%40" t t s)))
  9237. s)
  9238. (defun org-link-prettify (link)
  9239. "Return a human-readable representation of LINK.
  9240. The car of LINK must be a raw link.
  9241. The cdr of LINK must be either a link description or nil."
  9242. (let ((desc (or (cadr link) "<no description>")))
  9243. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9244. "<" (car link) ">")))
  9245. ;;;###autoload
  9246. (defun org-insert-link-global ()
  9247. "Insert a link like Org mode does.
  9248. This command can be called in any mode to insert a link in Org syntax."
  9249. (interactive)
  9250. (org-load-modules-maybe)
  9251. (org-run-like-in-org-mode 'org-insert-link))
  9252. (defun org-insert-all-links (arg &optional pre post)
  9253. "Insert all links in `org-stored-links'.
  9254. When a universal prefix, do not delete the links from `org-stored-links'.
  9255. When `ARG' is a number, insert the last N link(s).
  9256. `PRE' and `POST' are optional arguments to define a string to
  9257. prepend or to append."
  9258. (interactive "P")
  9259. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9260. (links (copy-sequence org-stored-links))
  9261. (pr (or pre "- "))
  9262. (po (or post "\n"))
  9263. (cnt 1) l)
  9264. (if (null org-stored-links)
  9265. (message "No link to insert")
  9266. (while (and (or (listp arg) (>= arg cnt))
  9267. (setq l (if (listp arg)
  9268. (pop links)
  9269. (pop org-stored-links))))
  9270. (setq cnt (1+ cnt))
  9271. (insert pr)
  9272. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9273. (insert po)))))
  9274. (defun org-insert-last-stored-link (arg)
  9275. "Insert the last link stored in `org-stored-links'."
  9276. (interactive "p")
  9277. (org-insert-all-links arg "" "\n"))
  9278. (defun org-link-fontify-links-to-this-file ()
  9279. "Fontify links to the current file in `org-stored-links'."
  9280. (let ((f (buffer-file-name)) a b)
  9281. (setq a (mapcar (lambda(l)
  9282. (let ((ll (car l)))
  9283. (when (and (string-match "^file:\\(.+\\)::" ll)
  9284. (equal f (expand-file-name (match-string 1 ll))))
  9285. ll)))
  9286. org-stored-links))
  9287. (when (featurep 'org-id)
  9288. (setq b (mapcar (lambda(l)
  9289. (let ((ll (car l)))
  9290. (when (and (string-match "^id:\\(.+\\)$" ll)
  9291. (equal f (expand-file-name
  9292. (or (org-id-find-id-file
  9293. (match-string 1 ll)) ""))))
  9294. ll)))
  9295. org-stored-links)))
  9296. (mapcar (lambda(l)
  9297. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9298. (delq nil (append a b)))))
  9299. (defvar org--links-history nil)
  9300. (defun org-insert-link (&optional complete-file link-location default-description)
  9301. "Insert a link. At the prompt, enter the link.
  9302. Completion can be used to insert any of the link protocol prefixes in use.
  9303. The history can be used to select a link previously stored with
  9304. `org-store-link'. When the empty string is entered (i.e. if you just
  9305. press `RET' at the prompt), the link defaults to the most recently
  9306. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9307. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9308. You will also be prompted for a description, and if one is given, it will
  9309. be displayed in the buffer instead of the link.
  9310. If there is already a link at point, this command will allow you to edit
  9311. link and description parts.
  9312. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9313. file name can be
  9314. selected using completion. The path to the file will be relative to the
  9315. current directory if the file is in the current directory or a subdirectory.
  9316. Otherwise, the link will be the absolute path as completed in the minibuffer
  9317. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9318. option `org-link-file-path-type'.
  9319. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9320. absolute path even if the file is in
  9321. the current directory or below.
  9322. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9323. prefix negates `org-keep-stored-link-after-insertion'.
  9324. If `org-make-link-description-function' is non-nil, this function will be
  9325. called with the link target, and the result will be the default
  9326. link description.
  9327. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9328. the link location instead of reading one interactively.
  9329. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9330. as the default description."
  9331. (interactive "P")
  9332. (let* ((wcf (current-window-configuration))
  9333. (origbuf (current-buffer))
  9334. (region (when (org-region-active-p)
  9335. (buffer-substring (region-beginning) (region-end))))
  9336. (remove (and region (list (region-beginning) (region-end))))
  9337. (desc region)
  9338. (link link-location)
  9339. (abbrevs org-link-abbrev-alist-local)
  9340. entry all-prefixes auto-desc)
  9341. (cond
  9342. (link-location) ; specified by arg, just use it.
  9343. ((org-in-regexp org-bracket-link-regexp 1)
  9344. ;; We do have a link at point, and we are going to edit it.
  9345. (setq remove (list (match-beginning 0) (match-end 0)))
  9346. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9347. (setq link (read-string "Link: "
  9348. (org-link-unescape
  9349. (match-string-no-properties 1)))))
  9350. ((or (org-in-regexp org-angle-link-re)
  9351. (org-in-regexp org-plain-link-re))
  9352. ;; Convert to bracket link
  9353. (setq remove (list (match-beginning 0) (match-end 0))
  9354. link (read-string "Link: "
  9355. (org-unbracket-string "<" ">" (match-string 0)))))
  9356. ((member complete-file '((4) (16)))
  9357. ;; Completing read for file names.
  9358. (setq link (org-file-complete-link complete-file)))
  9359. (t
  9360. ;; Read link, with completion for stored links.
  9361. (org-link-fontify-links-to-this-file)
  9362. (org-switch-to-buffer-other-window "*Org Links*")
  9363. (with-current-buffer "*Org Links*"
  9364. (erase-buffer)
  9365. (insert "Insert a link.
  9366. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9367. (when org-stored-links
  9368. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9369. (insert (mapconcat 'org-link-prettify
  9370. (reverse org-stored-links) "\n")))
  9371. (goto-char (point-min)))
  9372. (let ((cw (selected-window)))
  9373. (select-window (get-buffer-window "*Org Links*" 'visible))
  9374. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9375. (unless (pos-visible-in-window-p (point-max))
  9376. (org-fit-window-to-buffer))
  9377. (and (window-live-p cw) (select-window cw)))
  9378. (setq all-prefixes (append (mapcar 'car abbrevs)
  9379. (mapcar 'car org-link-abbrev-alist)
  9380. (org-link-types)))
  9381. (unwind-protect
  9382. ;; Fake a link history, containing the stored links.
  9383. (let ((org--links-history
  9384. (append (mapcar #'car org-stored-links)
  9385. org-insert-link-history)))
  9386. (setq link
  9387. (org-completing-read
  9388. "Link: "
  9389. (append
  9390. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9391. (mapcar #'car org-stored-links))
  9392. nil nil nil
  9393. 'org--links-history
  9394. (caar org-stored-links)))
  9395. (unless (org-string-nw-p link) (user-error "No link selected"))
  9396. (dolist (l org-stored-links)
  9397. (when (equal link (cadr l))
  9398. (setq link (car l))
  9399. (setq auto-desc t)))
  9400. (when (or (member link all-prefixes)
  9401. (and (equal ":" (substring link -1))
  9402. (member (substring link 0 -1) all-prefixes)
  9403. (setq link (substring link 0 -1))))
  9404. (setq link (with-current-buffer origbuf
  9405. (org-link-try-special-completion link)))))
  9406. (set-window-configuration wcf)
  9407. (kill-buffer "*Org Links*"))
  9408. (setq entry (assoc link org-stored-links))
  9409. (or entry (push link org-insert-link-history))
  9410. (setq desc (or desc (nth 1 entry)))))
  9411. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9412. (not org-keep-stored-link-after-insertion))
  9413. (setq org-stored-links (delq (assoc link org-stored-links)
  9414. org-stored-links)))
  9415. (when (and (string-match org-plain-link-re link)
  9416. (not (string-match org-ts-regexp link)))
  9417. ;; URL-like link, normalize the use of angular brackets.
  9418. (setq link (org-unbracket-string "<" ">" link)))
  9419. ;; Check if we are linking to the current file with a search
  9420. ;; option If yes, simplify the link by using only the search
  9421. ;; option.
  9422. (when (and buffer-file-name
  9423. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9424. (let* ((path (match-string 1 link))
  9425. (case-fold-search nil)
  9426. (search (match-string 2 link)))
  9427. (save-match-data
  9428. (when (equal (file-truename buffer-file-name) (file-truename path))
  9429. ;; We are linking to this same file, with a search option
  9430. (setq link search)))))
  9431. ;; Check if we can/should use a relative path. If yes, simplify the link
  9432. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9433. (let* ((type (match-string 1 link))
  9434. (path (match-string 2 link))
  9435. (origpath path)
  9436. (case-fold-search nil))
  9437. (cond
  9438. ((or (eq org-link-file-path-type 'absolute)
  9439. (equal complete-file '(16)))
  9440. (setq path (abbreviate-file-name (expand-file-name path))))
  9441. ((eq org-link-file-path-type 'noabbrev)
  9442. (setq path (expand-file-name path)))
  9443. ((eq org-link-file-path-type 'relative)
  9444. (setq path (file-relative-name path)))
  9445. (t
  9446. (save-match-data
  9447. (if (string-match (concat "^" (regexp-quote
  9448. (expand-file-name
  9449. (file-name-as-directory
  9450. default-directory))))
  9451. (expand-file-name path))
  9452. ;; We are linking a file with relative path name.
  9453. (setq path (substring (expand-file-name path)
  9454. (match-end 0)))
  9455. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9456. (setq link (concat type path))
  9457. (when (equal desc origpath)
  9458. (setq desc path))))
  9459. (if org-make-link-description-function
  9460. (setq desc
  9461. (or (condition-case nil
  9462. (funcall org-make-link-description-function link desc)
  9463. (error (progn (message "Can't get link description from `%s'"
  9464. (symbol-name org-make-link-description-function))
  9465. (sit-for 2) nil)))
  9466. (read-string "Description: " default-description)))
  9467. (if default-description (setq desc default-description)
  9468. (setq desc (or (and auto-desc desc)
  9469. (read-string "Description: " desc)))))
  9470. (unless (string-match "\\S-" desc) (setq desc nil))
  9471. (when remove (apply 'delete-region remove))
  9472. (insert (org-make-link-string link desc))
  9473. ;; Redisplay so as the new link has proper invisible characters.
  9474. (sit-for 0)))
  9475. (defun org-link-try-special-completion (type)
  9476. "If there is completion support for link type TYPE, offer it."
  9477. (let ((fun (org-link-get-parameter type :complete)))
  9478. (if (functionp fun)
  9479. (funcall fun)
  9480. (read-string "Link (no completion support): " (concat type ":")))))
  9481. (defun org-file-complete-link (&optional arg)
  9482. "Create a file link using completion."
  9483. (let ((file (read-file-name "File: "))
  9484. (pwd (file-name-as-directory (expand-file-name ".")))
  9485. (pwd1 (file-name-as-directory (abbreviate-file-name
  9486. (expand-file-name ".")))))
  9487. (cond ((equal arg '(16))
  9488. (concat "file:"
  9489. (abbreviate-file-name (expand-file-name file))))
  9490. ((string-match
  9491. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9492. (concat "file:" (match-string 1 file)))
  9493. ((string-match
  9494. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9495. (expand-file-name file))
  9496. (concat "file:"
  9497. (match-string 1 (expand-file-name file))))
  9498. (t (concat "file:" file)))))
  9499. (defun org-completing-read (&rest args)
  9500. "Completing-read with SPACE being a normal character."
  9501. (let ((enable-recursive-minibuffers t)
  9502. (minibuffer-local-completion-map
  9503. (copy-keymap minibuffer-local-completion-map)))
  9504. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9505. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9506. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9507. 'org-time-stamp-inactive)
  9508. (apply #'completing-read args)))
  9509. ;;; Opening/following a link
  9510. (defvar org-link-search-failed nil)
  9511. (defvar org-open-link-functions nil
  9512. "Hook for functions finding a plain text link.
  9513. These functions must take a single argument, the link content.
  9514. They will be called for links that look like [[link text][description]]
  9515. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9516. like a filename (e.g. \"./blue.png\").
  9517. These functions will be called *before* Org attempts to resolve the
  9518. link by doing text searches in the current buffer - so if you want a
  9519. link \"[[target]]\" to still find \"<<target>>\", your function should
  9520. handle this as a special case.
  9521. When the function does handle the link, it must return a non-nil value.
  9522. If it decides that it is not responsible for this link, it must return
  9523. nil to indicate that that Org can continue with other options like
  9524. exact and fuzzy text search.")
  9525. (defun org-next-link (&optional search-backward)
  9526. "Move forward to the next link.
  9527. If the link is in hidden text, expose it."
  9528. (interactive "P")
  9529. (when (and org-link-search-failed (eq this-command last-command))
  9530. (goto-char (point-min))
  9531. (message "Link search wrapped back to beginning of buffer"))
  9532. (setq org-link-search-failed nil)
  9533. (let* ((pos (point))
  9534. (ct (org-context))
  9535. (a (assq :link ct))
  9536. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9537. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9538. ((looking-at org-any-link-re)
  9539. ;; Don't stay stuck at link without an org-link face
  9540. (forward-char (if search-backward -1 1))))
  9541. (if (funcall srch-fun org-any-link-re nil t)
  9542. (progn
  9543. (goto-char (match-beginning 0))
  9544. (when (outline-invisible-p) (org-show-context)))
  9545. (goto-char pos)
  9546. (setq org-link-search-failed t)
  9547. (message "No further link found"))))
  9548. (defun org-previous-link ()
  9549. "Move backward to the previous link.
  9550. If the link is in hidden text, expose it."
  9551. (interactive)
  9552. (funcall 'org-next-link t))
  9553. (defun org-translate-link (s)
  9554. "Translate a link string if a translation function has been defined."
  9555. (with-temp-buffer
  9556. (insert (org-trim s))
  9557. (org-trim (org-element-interpret-data (org-element-context)))))
  9558. (defun org-translate-link-from-planner (type path)
  9559. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9560. This is still an experimental function, your mileage may vary."
  9561. (cond
  9562. ((member type '("http" "https" "news" "ftp"))
  9563. ;; standard Internet links are the same.
  9564. nil)
  9565. ((and (equal type "irc") (string-match "^//" path))
  9566. ;; Planner has two / at the beginning of an irc link, we have 1.
  9567. ;; We should have zero, actually....
  9568. (setq path (substring path 1)))
  9569. ((and (equal type "lisp") (string-match "^/" path))
  9570. ;; Planner has a slash, we do not.
  9571. (setq type "elisp" path (substring path 1)))
  9572. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9573. ;; A typical message link. Planner has the id after the final slash,
  9574. ;; we separate it with a hash mark
  9575. (setq path (concat (match-string 1 path) "#"
  9576. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9577. (cons type path))
  9578. (defun org-find-file-at-mouse (ev)
  9579. "Open file link or URL at mouse."
  9580. (interactive "e")
  9581. (mouse-set-point ev)
  9582. (org-open-at-point 'in-emacs))
  9583. (defun org-open-at-mouse (ev)
  9584. "Open file link or URL at mouse.
  9585. See the docstring of `org-open-file' for details."
  9586. (interactive "e")
  9587. (mouse-set-point ev)
  9588. (when (eq major-mode 'org-agenda-mode)
  9589. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9590. (org-open-at-point))
  9591. (defvar org-window-config-before-follow-link nil
  9592. "The window configuration before following a link.
  9593. This is saved in case the need arises to restore it.")
  9594. ;;;###autoload
  9595. (defun org-open-at-point-global ()
  9596. "Follow a link or time-stamp like Org mode does.
  9597. This command can be called in any mode to follow an external link
  9598. or a time-stamp that has Org mode syntax. Its behavior is
  9599. undefined when called on internal links (e.g., fuzzy links).
  9600. Raise an error when there is nothing to follow. "
  9601. (interactive)
  9602. (cond ((org-in-regexp org-any-link-re)
  9603. (org-open-link-from-string (match-string-no-properties 0)))
  9604. ((or (org-in-regexp org-ts-regexp-both nil t)
  9605. (org-in-regexp org-tsr-regexp-both nil t))
  9606. (org-follow-timestamp-link))
  9607. (t (user-error "No link found"))))
  9608. ;;;###autoload
  9609. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9610. "Open a link in the string S, as if it was in Org mode."
  9611. (interactive "sLink: \nP")
  9612. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9613. (with-temp-buffer
  9614. (let ((org-inhibit-startup (not reference-buffer)))
  9615. (org-mode)
  9616. (insert s)
  9617. (goto-char (point-min))
  9618. (when reference-buffer
  9619. (setq org-link-abbrev-alist-local
  9620. (with-current-buffer reference-buffer
  9621. org-link-abbrev-alist-local)))
  9622. (org-open-at-point arg reference-buffer)))))
  9623. (defvar org-open-at-point-functions nil
  9624. "Hook that is run when following a link at point.
  9625. Functions in this hook must return t if they identify and follow
  9626. a link at point. If they don't find anything interesting at point,
  9627. they must return nil.")
  9628. (defvar org-link-search-inhibit-query nil)
  9629. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9630. (defun org--open-doi-link (path)
  9631. "Open a \"doi\" type link.
  9632. PATH is a the path to search for, as a string."
  9633. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9634. (defun org--open-elisp-link (path)
  9635. "Open a \"elisp\" type link.
  9636. PATH is the sexp to evaluate, as a string."
  9637. (let ((cmd path))
  9638. (if (or (and (org-string-nw-p
  9639. org-confirm-elisp-link-not-regexp)
  9640. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9641. (not org-confirm-elisp-link-function)
  9642. (funcall org-confirm-elisp-link-function
  9643. (format "Execute \"%s\" as elisp? "
  9644. (org-add-props cmd nil 'face 'org-warning))))
  9645. (message "%s => %s" cmd
  9646. (if (eq (string-to-char cmd) ?\()
  9647. (eval (read cmd))
  9648. (call-interactively (read cmd))))
  9649. (user-error "Abort"))))
  9650. (defun org--open-help-link (path)
  9651. "Open a \"help\" type link.
  9652. PATH is a symbol name, as a string."
  9653. (pcase (intern path)
  9654. ((and (pred fboundp) variable) (describe-function variable))
  9655. ((and (pred boundp) function) (describe-variable function))
  9656. (name (user-error "Unknown function or variable: %s" name))))
  9657. (defun org--open-shell-link (path)
  9658. "Open a \"shell\" type link.
  9659. PATH is the command to execute, as a string."
  9660. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9661. (cmd path))
  9662. (if (or (and (org-string-nw-p
  9663. org-confirm-shell-link-not-regexp)
  9664. (string-match
  9665. org-confirm-shell-link-not-regexp cmd))
  9666. (not org-confirm-shell-link-function)
  9667. (funcall org-confirm-shell-link-function
  9668. (format "Execute \"%s\" in shell? "
  9669. (org-add-props cmd nil
  9670. 'face 'org-warning))))
  9671. (progn
  9672. (message "Executing %s" cmd)
  9673. (shell-command cmd buf)
  9674. (when (featurep 'midnight)
  9675. (setq clean-buffer-list-kill-buffer-names
  9676. (cons (buffer-name buf)
  9677. clean-buffer-list-kill-buffer-names))))
  9678. (user-error "Abort"))))
  9679. (defun org-open-at-point (&optional arg reference-buffer)
  9680. "Open link, timestamp, footnote or tags at point.
  9681. When point is on a link, follow it. Normally, files will be
  9682. opened by an appropriate application. If the optional prefix
  9683. argument ARG is non-nil, Emacs will visit the file. With
  9684. a double prefix argument, try to open outside of Emacs, in the
  9685. application the system uses for this file type.
  9686. When point is on a timestamp, open the agenda at the day
  9687. specified.
  9688. When point is a footnote definition, move to the first reference
  9689. found. If it is on a reference, move to the associated
  9690. definition.
  9691. When point is on a headline, display a list of every link in the
  9692. entry, so it is possible to pick one, or all, of them. If point
  9693. is on a tag, call `org-tags-view' instead.
  9694. When optional argument REFERENCE-BUFFER is non-nil, it should
  9695. specify a buffer from where the link search should happen. This
  9696. is used internally by `org-open-link-from-string'.
  9697. On top of syntactically correct links, this function will open
  9698. the link at point in comments or comment blocks and the first
  9699. link in a property drawer line."
  9700. (interactive "P")
  9701. ;; On a code block, open block's results.
  9702. (unless (call-interactively 'org-babel-open-src-block-result)
  9703. (org-load-modules-maybe)
  9704. (setq org-window-config-before-follow-link (current-window-configuration))
  9705. (org-remove-occur-highlights nil nil t)
  9706. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9707. (let* ((context
  9708. ;; Only consider supported types, even if they are not
  9709. ;; the closest one.
  9710. (org-element-lineage
  9711. (org-element-context)
  9712. '(clock comment comment-block footnote-definition
  9713. footnote-reference headline inlinetask keyword link
  9714. node-property timestamp)
  9715. t))
  9716. (type (org-element-type context))
  9717. (value (org-element-property :value context)))
  9718. (cond
  9719. ((not context) (user-error "No link found"))
  9720. ;; Exception: open timestamps and links in properties
  9721. ;; drawers, keywords and comments.
  9722. ((memq type '(comment comment-block keyword node-property))
  9723. (call-interactively #'org-open-at-point-global))
  9724. ;; On a headline or an inlinetask, but not on a timestamp,
  9725. ;; a link, a footnote reference or on tags.
  9726. ((and (memq type '(headline inlinetask))
  9727. ;; Not on tags.
  9728. (let ((case-fold-search nil))
  9729. (save-excursion
  9730. (beginning-of-line)
  9731. (looking-at org-complex-heading-regexp))
  9732. (or (not (match-beginning 5))
  9733. (< (point) (match-beginning 5)))))
  9734. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9735. (links (car data))
  9736. (links-end (cdr data)))
  9737. (if links
  9738. (dolist (link (if (stringp links) (list links) links))
  9739. (search-forward link nil links-end)
  9740. (goto-char (match-beginning 0))
  9741. (org-open-at-point))
  9742. (require 'org-attach)
  9743. (org-attach-reveal 'if-exists))))
  9744. ;; On a clock line, make sure point is on the timestamp
  9745. ;; before opening it.
  9746. ((and (eq type 'clock)
  9747. value
  9748. (>= (point) (org-element-property :begin value))
  9749. (<= (point) (org-element-property :end value)))
  9750. (org-follow-timestamp-link))
  9751. ;; Do nothing on white spaces after an object.
  9752. ((>= (point)
  9753. (save-excursion
  9754. (goto-char (org-element-property :end context))
  9755. (skip-chars-backward " \t")
  9756. (point)))
  9757. (user-error "No link found"))
  9758. ((eq type 'timestamp) (org-follow-timestamp-link))
  9759. ;; On tags within a headline or an inlinetask.
  9760. ((and (memq type '(headline inlinetask))
  9761. (let ((case-fold-search nil))
  9762. (save-excursion (beginning-of-line)
  9763. (looking-at org-complex-heading-regexp))
  9764. (and (match-beginning 5)
  9765. (>= (point) (match-beginning 5)))))
  9766. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9767. ((eq type 'link)
  9768. ;; When link is located within the description of another
  9769. ;; link (e.g., an inline image), always open the parent
  9770. ;; link.
  9771. (let* ((link (let ((up (org-element-property :parent context)))
  9772. (if (eq (org-element-type up) 'link) up context)))
  9773. (type (org-element-property :type link))
  9774. (path (org-link-unescape (org-element-property :path link))))
  9775. ;; Switch back to REFERENCE-BUFFER needed when called in
  9776. ;; a temporary buffer through `org-open-link-from-string'.
  9777. (with-current-buffer (or reference-buffer (current-buffer))
  9778. (cond
  9779. ((equal type "file")
  9780. (if (string-match "[*?{]" (file-name-nondirectory path))
  9781. (dired path)
  9782. ;; Look into `org-link-parameters' in order to find
  9783. ;; a DEDICATED-FUNCTION to open file. The function
  9784. ;; will be applied on raw link instead of parsed
  9785. ;; link due to the limitation in `org-add-link-type'
  9786. ;; ("open" function called with a single argument).
  9787. ;; If no such function is found, fallback to
  9788. ;; `org-open-file'.
  9789. (let* ((option (org-element-property :search-option link))
  9790. (app (org-element-property :application link))
  9791. (dedicated-function
  9792. (org-link-get-parameter
  9793. (if app (concat type "+" app) type)
  9794. :follow)))
  9795. (if dedicated-function
  9796. (funcall dedicated-function
  9797. (concat path
  9798. (and option (concat "::" option))))
  9799. (apply #'org-open-file
  9800. path
  9801. (cond (arg)
  9802. ((equal app "emacs") 'emacs)
  9803. ((equal app "sys") 'system))
  9804. (cond ((not option) nil)
  9805. ((string-match-p "\\`[0-9]+\\'" option)
  9806. (list (string-to-number option)))
  9807. (t (list nil
  9808. (org-link-unescape option)))))))))
  9809. ((functionp (org-link-get-parameter type :follow))
  9810. (funcall (org-link-get-parameter type :follow) path))
  9811. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9812. (unless (run-hook-with-args-until-success
  9813. 'org-open-link-functions path)
  9814. (if (not arg) (org-mark-ring-push)
  9815. (switch-to-buffer-other-window
  9816. (org-get-buffer-for-internal-link (current-buffer))))
  9817. (let ((destination
  9818. (org-with-wide-buffer
  9819. (if (equal type "radio")
  9820. (org-search-radio-target
  9821. (org-element-property :path link))
  9822. (org-link-search
  9823. (if (member type '("custom-id" "coderef"))
  9824. (org-element-property :raw-link link)
  9825. path)
  9826. ;; Prevent fuzzy links from matching
  9827. ;; themselves.
  9828. (and (equal type "fuzzy")
  9829. (+ 2 (org-element-property :begin link)))))
  9830. (point))))
  9831. (unless (and (<= (point-min) destination)
  9832. (>= (point-max) destination))
  9833. (widen))
  9834. (goto-char destination))))
  9835. (t (browse-url-at-point))))))
  9836. ;; On a footnote reference or at a footnote definition's label.
  9837. ((or (eq type 'footnote-reference)
  9838. (and (eq type 'footnote-definition)
  9839. (save-excursion
  9840. ;; Do not validate action when point is on the
  9841. ;; spaces right after the footnote label, in
  9842. ;; order to be on par with behaviour on links.
  9843. (skip-chars-forward " \t")
  9844. (let ((begin
  9845. (org-element-property :contents-begin context)))
  9846. (if begin (< (point) begin)
  9847. (= (org-element-property :post-affiliated context)
  9848. (line-beginning-position)))))))
  9849. (org-footnote-action))
  9850. (t (user-error "No link found")))))
  9851. (run-hook-with-args 'org-follow-link-hook)))
  9852. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9853. "Offer links in the current entry and return the selected link.
  9854. If there is only one link, return it.
  9855. If NTH is an integer, return the NTH link found.
  9856. If ZERO is a string, check also this string for a link, and if
  9857. there is one, return it."
  9858. (with-current-buffer buffer
  9859. (org-with-wide-buffer
  9860. (goto-char marker)
  9861. (let ((cnt ?0)
  9862. have-zero end links link c)
  9863. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9864. (push (match-string 0 zero) links)
  9865. (setq cnt (1- cnt) have-zero t))
  9866. (save-excursion
  9867. (org-back-to-heading t)
  9868. (setq end (save-excursion (outline-next-heading) (point)))
  9869. (while (re-search-forward org-any-link-re end t)
  9870. (push (match-string 0) links))
  9871. (setq links (org-uniquify (reverse links))))
  9872. (cond
  9873. ((null links)
  9874. (message "No links"))
  9875. ((equal (length links) 1)
  9876. (setq link (car links)))
  9877. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9878. (setq link (nth (if have-zero nth (1- nth)) links)))
  9879. (t ; we have to select a link
  9880. (save-excursion
  9881. (save-window-excursion
  9882. (delete-other-windows)
  9883. (with-output-to-temp-buffer "*Select Link*"
  9884. (dolist (l links)
  9885. (cond
  9886. ((not (string-match org-bracket-link-regexp l))
  9887. (princ (format "[%c] %s\n" (cl-incf cnt)
  9888. (org-unbracket-string "<" ">" l))))
  9889. ((match-end 3)
  9890. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9891. (match-string 3 l) (match-string 1 l))))
  9892. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9893. (match-string 1 l)))))))
  9894. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9895. (message "Select link to open, RET to open all:")
  9896. (setq c (read-char-exclusive))
  9897. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9898. (when (equal c ?q) (user-error "Abort"))
  9899. (if (equal c ?\C-m)
  9900. (setq link links)
  9901. (setq nth (- c ?0))
  9902. (when have-zero (setq nth (1+ nth)))
  9903. (unless (and (integerp nth) (>= (length links) nth))
  9904. (user-error "Invalid link selection"))
  9905. (setq link (nth (1- nth) links)))))
  9906. (cons link end)))))
  9907. ;; TODO: These functions are deprecated since `org-open-at-point'
  9908. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9909. (defun org-open-file-with-system (path)
  9910. "Open file at PATH using the system way of opening it."
  9911. (org-open-file path 'system))
  9912. (defun org-open-file-with-emacs (path)
  9913. "Open file at PATH in Emacs."
  9914. (org-open-file path 'emacs))
  9915. ;;; File search
  9916. (defvar org-create-file-search-functions nil
  9917. "List of functions to construct the right search string for a file link.
  9918. These functions are called in turn with point at the location to
  9919. which the link should point.
  9920. A function in the hook should first test if it would like to
  9921. handle this file type, for example by checking the `major-mode'
  9922. or the file extension. If it decides not to handle this file, it
  9923. should just return nil to give other functions a chance. If it
  9924. does handle the file, it must return the search string to be used
  9925. when following the link. The search string will be part of the
  9926. file link, given after a double colon, and `org-open-at-point'
  9927. will automatically search for it. If special measures must be
  9928. taken to make the search successful, another function should be
  9929. added to the companion hook `org-execute-file-search-functions',
  9930. which see.
  9931. A function in this hook may also use `setq' to set the variable
  9932. `description' to provide a suggestion for the descriptive text to
  9933. be used for this link when it gets inserted into an Org buffer
  9934. with \\[org-insert-link].")
  9935. (defvar org-execute-file-search-functions nil
  9936. "List of functions to execute a file search triggered by a link.
  9937. Functions added to this hook must accept a single argument, the
  9938. search string that was part of the file link, the part after the
  9939. double colon. The function must first check if it would like to
  9940. handle this search, for example by checking the `major-mode' or
  9941. the file extension. If it decides not to handle this search, it
  9942. should just return nil to give other functions a chance. If it
  9943. does handle the search, it must return a non-nil value to keep
  9944. other functions from trying.
  9945. Each function can access the current prefix argument through the
  9946. variable `current-prefix-arg'. Note that a single prefix is used
  9947. to force opening a link in Emacs, so it may be good to only use a
  9948. numeric or double prefix to guide the search function.
  9949. In case this is needed, a function in this hook can also restore
  9950. the window configuration before `org-open-at-point' was called using:
  9951. (set-window-configuration org-window-config-before-follow-link)")
  9952. (defun org-search-radio-target (target)
  9953. "Search a radio target matching TARGET in current buffer.
  9954. White spaces are not significant."
  9955. (let ((re (format "<<<%s>>>"
  9956. (mapconcat #'regexp-quote
  9957. (org-split-string target "[ \t\n]+")
  9958. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9959. (origin (point)))
  9960. (goto-char (point-min))
  9961. (catch :radio-match
  9962. (while (re-search-forward re nil t)
  9963. (backward-char)
  9964. (let ((object (org-element-context)))
  9965. (when (eq (org-element-type object) 'radio-target)
  9966. (goto-char (org-element-property :begin object))
  9967. (org-show-context 'link-search)
  9968. (throw :radio-match nil))))
  9969. (goto-char origin)
  9970. (user-error "No match for radio target: %s" target))))
  9971. (defun org-link-search (s &optional avoid-pos stealth)
  9972. "Search for a search string S.
  9973. If S starts with \"#\", it triggers a custom ID search.
  9974. If S is enclosed within parenthesis, it initiates a coderef
  9975. search.
  9976. If S is surrounded by forward slashes, it is interpreted as
  9977. a regular expression. In Org mode files, this will create an
  9978. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9979. to list matches. If the current buffer is in `dired-mode', grep
  9980. will be used to search in all files.
  9981. When AVOID-POS is given, ignore matches near that position.
  9982. When optional argument STEALTH is non-nil, do not modify
  9983. visibility around point, thus ignoring `org-show-context-detail'
  9984. variable.
  9985. Search is case-insensitive and ignores white spaces. Return type
  9986. of matched result, which is either `dedicated' or `fuzzy'."
  9987. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9988. (let* ((case-fold-search t)
  9989. (origin (point))
  9990. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9991. (words (org-split-string s "[ \t\n]+"))
  9992. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9993. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9994. type)
  9995. (cond
  9996. ;; Check if there are any special search functions.
  9997. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9998. ((eq (string-to-char s) ?#)
  9999. ;; Look for a custom ID S if S starts with "#".
  10000. (let* ((id (substring normalized 1))
  10001. (match (org-find-property "CUSTOM_ID" id)))
  10002. (if match (progn (goto-char match) (setf type 'dedicated))
  10003. (error "No match for custom ID: %s" id))))
  10004. ((string-match "\\`(\\(.*\\))\\'" normalized)
  10005. ;; Look for coderef targets if S is enclosed within parenthesis.
  10006. (let ((coderef (match-string-no-properties 1 normalized))
  10007. (re (substring s-single-re 1 -1)))
  10008. (goto-char (point-min))
  10009. (catch :coderef-match
  10010. (while (re-search-forward re nil t)
  10011. (let ((element (org-element-at-point)))
  10012. (when (and (memq (org-element-type element)
  10013. '(example-block src-block))
  10014. ;; Build proper regexp according to current
  10015. ;; block's label format.
  10016. (let ((label-fmt
  10017. (regexp-quote
  10018. (or (org-element-property :label-fmt element)
  10019. org-coderef-label-format))))
  10020. (save-excursion
  10021. (beginning-of-line)
  10022. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  10023. (format label-fmt coderef))))))
  10024. (setq type 'dedicated)
  10025. (goto-char (match-beginning 1))
  10026. (throw :coderef-match nil))))
  10027. (goto-char origin)
  10028. (error "No match for coderef: %s" coderef))))
  10029. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10030. ;; Look for a regular expression.
  10031. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10032. (match-string 1 s)))
  10033. ;; Fuzzy links.
  10034. (t
  10035. (let ((starred (eq (string-to-char normalized) ?*)))
  10036. (cond
  10037. ;; Look for targets, only if not in a headline search.
  10038. ((and (not starred)
  10039. (let ((target (format "<<%s>>" s-multi-re)))
  10040. (catch :target-match
  10041. (goto-char (point-min))
  10042. (while (re-search-forward target nil t)
  10043. (backward-char)
  10044. (let ((context (org-element-context)))
  10045. (when (eq (org-element-type context) 'target)
  10046. (setq type 'dedicated)
  10047. (goto-char (org-element-property :begin context))
  10048. (throw :target-match t))))
  10049. nil))))
  10050. ;; Look for elements named after S, only if not in a headline
  10051. ;; search.
  10052. ((and (not starred)
  10053. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10054. (catch :name-match
  10055. (goto-char (point-min))
  10056. (while (re-search-forward name nil t)
  10057. (let ((element (org-element-at-point)))
  10058. (when (equal (org-split-string
  10059. (org-element-property :name element)
  10060. "[ \t]+")
  10061. words)
  10062. (setq type 'dedicated)
  10063. (beginning-of-line)
  10064. (throw :name-match t))))
  10065. nil))))
  10066. ;; Regular text search. Prefer headlines in Org mode
  10067. ;; buffers.
  10068. ((and (derived-mode-p 'org-mode)
  10069. (let* ((wspace "[ \t]")
  10070. (wspaceopt (concat wspace "*"))
  10071. (cookie (concat "\\(?:"
  10072. wspaceopt
  10073. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  10074. wspaceopt
  10075. "\\)"))
  10076. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10077. (re (concat
  10078. org-outline-regexp-bol
  10079. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  10080. "\\(?:\\[#.\\][ \t]+\\)?"
  10081. "\\(?:" org-comment-string "[ \t]+\\)?"
  10082. sep "?"
  10083. (let ((title (mapconcat #'regexp-quote
  10084. words
  10085. sep)))
  10086. (if starred (substring title 1) title))
  10087. sep "?"
  10088. "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
  10089. "[ \t]*$")))
  10090. (goto-char (point-min))
  10091. (re-search-forward re nil t)))
  10092. (goto-char (match-beginning 0))
  10093. (setq type 'dedicated))
  10094. ;; Offer to create non-existent headline depending on
  10095. ;; `org-link-search-must-match-exact-headline'.
  10096. ((and (derived-mode-p 'org-mode)
  10097. (not org-link-search-inhibit-query)
  10098. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10099. (yes-or-no-p "No match - create this as a new heading? "))
  10100. (goto-char (point-max))
  10101. (unless (bolp) (newline))
  10102. (org-insert-heading nil t t)
  10103. (insert s "\n")
  10104. (beginning-of-line 0))
  10105. ;; Only headlines are looked after. No need to process
  10106. ;; further: throw an error.
  10107. ((and (derived-mode-p 'org-mode)
  10108. (or starred org-link-search-must-match-exact-headline))
  10109. (goto-char origin)
  10110. (error "No match for fuzzy expression: %s" normalized))
  10111. ;; Regular text search.
  10112. ((catch :fuzzy-match
  10113. (goto-char (point-min))
  10114. (while (re-search-forward s-multi-re nil t)
  10115. ;; Skip match if it contains AVOID-POS or it is included
  10116. ;; in a link with a description but outside the
  10117. ;; description.
  10118. (unless (or (and avoid-pos
  10119. (<= (match-beginning 0) avoid-pos)
  10120. (> (match-end 0) avoid-pos))
  10121. (and (save-match-data
  10122. (org-in-regexp org-bracket-link-regexp))
  10123. (match-beginning 3)
  10124. (or (> (match-beginning 3) (point))
  10125. (<= (match-end 3) (point)))
  10126. (org-element-lineage
  10127. (save-match-data (org-element-context))
  10128. '(link) t)))
  10129. (goto-char (match-beginning 0))
  10130. (setq type 'fuzzy)
  10131. (throw :fuzzy-match t)))
  10132. nil))
  10133. ;; All failed. Throw an error.
  10134. (t (goto-char origin)
  10135. (error "No match for fuzzy expression: %s" normalized))))))
  10136. ;; Disclose surroundings of match, if appropriate.
  10137. (when (and (derived-mode-p 'org-mode) (not stealth))
  10138. (org-show-context 'link-search))
  10139. type))
  10140. (defun org-get-buffer-for-internal-link (buffer)
  10141. "Return a buffer to be used for displaying the link target of internal links."
  10142. (cond
  10143. ((not org-display-internal-link-with-indirect-buffer)
  10144. buffer)
  10145. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10146. (message "Buffer is already a clone, not making another one")
  10147. ;; we also do not modify visibility in this case
  10148. buffer)
  10149. (t ; make a new indirect buffer for displaying the link
  10150. (let* ((bn (buffer-name buffer))
  10151. (ibn (concat bn "(Clone)"))
  10152. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10153. (with-current-buffer ib (org-overview))
  10154. ib))))
  10155. (defun org-do-occur (regexp &optional cleanup)
  10156. "Call the Emacs command `occur'.
  10157. If CLEANUP is non-nil, remove the printout of the regular expression
  10158. in the *Occur* buffer. This is useful if the regex is long and not useful
  10159. to read."
  10160. (occur regexp)
  10161. (when cleanup
  10162. (let ((cwin (selected-window)) win beg end)
  10163. (when (setq win (get-buffer-window "*Occur*"))
  10164. (select-window win))
  10165. (goto-char (point-min))
  10166. (when (re-search-forward "match[a-z]+" nil t)
  10167. (setq beg (match-end 0))
  10168. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10169. (setq end (1- (match-beginning 0)))))
  10170. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10171. (goto-char (point-min))
  10172. (select-window cwin))))
  10173. ;;; The mark ring for links jumps
  10174. (defvar org-mark-ring nil
  10175. "Mark ring for positions before jumps in Org mode.")
  10176. (defvar org-mark-ring-last-goto nil
  10177. "Last position in the mark ring used to go back.")
  10178. ;; Fill and close the ring
  10179. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10180. (dotimes (_ org-mark-ring-length)
  10181. (push (make-marker) org-mark-ring))
  10182. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10183. org-mark-ring)
  10184. (defun org-mark-ring-push (&optional pos buffer)
  10185. "Put the current position or POS into the mark ring and rotate it."
  10186. (interactive)
  10187. (setq pos (or pos (point)))
  10188. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10189. (move-marker (car org-mark-ring)
  10190. (or pos (point))
  10191. (or buffer (current-buffer)))
  10192. (message "%s"
  10193. (substitute-command-keys
  10194. "Position saved to mark ring, go back with \
  10195. `\\[org-mark-ring-goto]'.")))
  10196. (defun org-mark-ring-goto (&optional n)
  10197. "Jump to the previous position in the mark ring.
  10198. With prefix arg N, jump back that many stored positions. When
  10199. called several times in succession, walk through the entire ring.
  10200. Org mode commands jumping to a different position in the current file,
  10201. or to another Org file, automatically push the old position onto the ring."
  10202. (interactive "p")
  10203. (let (p m)
  10204. (if (eq last-command this-command)
  10205. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10206. (setq p org-mark-ring))
  10207. (setq org-mark-ring-last-goto p)
  10208. (setq m (car p))
  10209. (pop-to-buffer-same-window (marker-buffer m))
  10210. (goto-char m)
  10211. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10212. (defun org-add-angle-brackets (s)
  10213. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10214. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10215. s)
  10216. ;;; Following specific links
  10217. (defvar org-agenda-buffer-tmp-name)
  10218. (defvar org-agenda-start-on-weekday)
  10219. (defun org-follow-timestamp-link ()
  10220. "Open an agenda view for the time-stamp date/range at point."
  10221. (cond
  10222. ((org-at-date-range-p t)
  10223. (let ((org-agenda-start-on-weekday)
  10224. (t1 (match-string 1))
  10225. (t2 (match-string 2)) tt1 tt2)
  10226. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10227. tt2 (time-to-days (org-time-string-to-time t2)))
  10228. (let ((org-agenda-buffer-tmp-name
  10229. (format "*Org Agenda(a:%s)"
  10230. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10231. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10232. ((org-at-timestamp-p t)
  10233. (let ((org-agenda-buffer-tmp-name
  10234. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10235. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10236. (substring (match-string 1) 0 10)))
  10237. 1)))
  10238. (t (error "This should not happen"))))
  10239. ;;; Following file links
  10240. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10241. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10242. (declare-function mailcap-mime-info
  10243. "mailcap" (string &optional request no-decode))
  10244. (defvar org-wait nil)
  10245. (defun org-open-file (path &optional in-emacs line search)
  10246. "Open the file at PATH.
  10247. First, this expands any special file name abbreviations. Then the
  10248. configuration variable `org-file-apps' is checked if it contains an
  10249. entry for this file type, and if yes, the corresponding command is launched.
  10250. If no application is found, Emacs simply visits the file.
  10251. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10252. With a double \\[universal-argument] \\[universal-argument] \
  10253. prefix arg, Org tries to avoid opening in Emacs
  10254. and to use an external application to visit the file.
  10255. Optional LINE specifies a line to go to, optional SEARCH a string
  10256. to search for. If LINE or SEARCH is given, the file will be
  10257. opened in Emacs, unless an entry from org-file-apps that makes
  10258. use of groups in a regexp matches.
  10259. If you want to change the way frames are used when following a
  10260. link, please customize `org-link-frame-setup'.
  10261. If the file does not exist, an error is thrown."
  10262. (let* ((file (if (equal path "")
  10263. buffer-file-name
  10264. (substitute-in-file-name (expand-file-name path))))
  10265. (file-apps (append org-file-apps (org-default-apps)))
  10266. (apps (cl-remove-if
  10267. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10268. (apps-dlink (cl-remove-if-not
  10269. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10270. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10271. (dirp (unless remp (file-directory-p file)))
  10272. (file (if (and dirp org-open-directory-means-index-dot-org)
  10273. (concat (file-name-as-directory file) "index.org")
  10274. file))
  10275. (a-m-a-p (assq 'auto-mode apps))
  10276. (dfile (downcase file))
  10277. ;; Reconstruct the original link from the PATH, LINE and
  10278. ;; SEARCH args.
  10279. (link (cond (line (concat file "::" (number-to-string line)))
  10280. (search (concat file "::" search))
  10281. (t file)))
  10282. (dlink (downcase link))
  10283. (old-buffer (current-buffer))
  10284. (old-pos (point))
  10285. (old-mode major-mode)
  10286. (ext
  10287. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10288. (match-string 1 dfile)))
  10289. cmd link-match-data)
  10290. (cond
  10291. ((member in-emacs '((16) system))
  10292. (setq cmd (cdr (assq 'system apps))))
  10293. (in-emacs (setq cmd 'emacs))
  10294. (t
  10295. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10296. (and dirp (cdr (assq 'directory apps)))
  10297. ;; First, try matching against apps-dlink if we
  10298. ;; get a match here, store the match data for
  10299. ;; later.
  10300. (let ((match (assoc-default dlink apps-dlink
  10301. 'string-match)))
  10302. (if match
  10303. (progn (setq link-match-data (match-data))
  10304. match)
  10305. (progn (setq in-emacs (or in-emacs line search))
  10306. nil))) ; if we have no match in apps-dlink,
  10307. ; always open the file in emacs if line or search
  10308. ; is given (for backwards compatibility)
  10309. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10310. 'string-match)
  10311. (cdr (assoc ext apps))
  10312. (cdr (assq t apps))))))
  10313. (when (eq cmd 'system)
  10314. (setq cmd (cdr (assq 'system apps))))
  10315. (when (eq cmd 'default)
  10316. (setq cmd (cdr (assoc t apps))))
  10317. (when (eq cmd 'mailcap)
  10318. (require 'mailcap)
  10319. (mailcap-parse-mailcaps)
  10320. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10321. (command (mailcap-mime-info mime-type)))
  10322. (if (stringp command)
  10323. (setq cmd command)
  10324. (setq cmd 'emacs))))
  10325. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10326. (not (file-exists-p file))
  10327. (not org-open-non-existing-files))
  10328. (user-error "No such file: %s" file))
  10329. (cond
  10330. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10331. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10332. (while (string-match "['\"]%s['\"]" cmd)
  10333. (setq cmd (replace-match "%s" t t cmd)))
  10334. (setq cmd (replace-regexp-in-string
  10335. "%s"
  10336. (shell-quote-argument (convert-standard-filename file))
  10337. cmd
  10338. nil t))
  10339. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10340. (save-match-data
  10341. (let ((match-index 1)
  10342. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10343. (set-match-data link-match-data)
  10344. (while (<= match-index number-of-groups)
  10345. (let ((regex (concat "%" (number-to-string match-index)))
  10346. (replace-with (match-string match-index dlink)))
  10347. (while (string-match regex cmd)
  10348. (setq cmd (replace-match replace-with t t cmd))))
  10349. (setq match-index (+ match-index 1)))))
  10350. (save-window-excursion
  10351. (message "Running %s...done" cmd)
  10352. (start-process-shell-command cmd nil cmd)
  10353. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10354. ((or (stringp cmd)
  10355. (eq cmd 'emacs))
  10356. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10357. (widen)
  10358. (cond (line (org-goto-line line)
  10359. (when (derived-mode-p 'org-mode) (org-reveal)))
  10360. (search (org-link-search search))))
  10361. ((functionp cmd)
  10362. (save-match-data
  10363. (set-match-data link-match-data)
  10364. (condition-case nil
  10365. (funcall cmd file link)
  10366. ;; FIXME: Remove this check when most default installations
  10367. ;; of Emacs have at least Org 9.0.
  10368. ((debug wrong-number-of-arguments wrong-type-argument
  10369. invalid-function)
  10370. (user-error "Please see Org News for version 9.0 about \
  10371. `org-file-apps'--Lisp error: %S" cmd)))))
  10372. ((consp cmd)
  10373. ;; FIXME: Remove this check when most default installations of
  10374. ;; Emacs have at least Org 9.0.
  10375. ;; Heads-up instead of silently fall back to
  10376. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10377. ;; with sexp instead of a function for `cmd'.
  10378. (user-error "Please see Org News for version 9.0 about \
  10379. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10380. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10381. (and (derived-mode-p 'org-mode)
  10382. (eq old-mode 'org-mode)
  10383. (or (not (eq old-buffer (current-buffer)))
  10384. (not (eq old-pos (point))))
  10385. (org-mark-ring-push old-pos old-buffer))))
  10386. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10387. "This function returns non-nil if `entry' uses a regular
  10388. expression which should be matched against the whole link by
  10389. org-open-file.
  10390. It assumes that is the case when the entry uses a regular
  10391. expression which has at least one grouping construct and the
  10392. action is either a lisp form or a command string containing
  10393. `%1', i.e. using at least one subexpression match as a
  10394. parameter."
  10395. (let ((selector (car entry))
  10396. (action (cdr entry)))
  10397. (if (stringp selector)
  10398. (and (> (regexp-opt-depth selector) 0)
  10399. (or (and (stringp action)
  10400. (string-match "%[0-9]" action))
  10401. (consp action)))
  10402. nil)))
  10403. (defun org-default-apps ()
  10404. "Return the default applications for this operating system."
  10405. (cond
  10406. ((eq system-type 'darwin)
  10407. org-file-apps-defaults-macosx)
  10408. ((eq system-type 'windows-nt)
  10409. org-file-apps-defaults-windowsnt)
  10410. (t org-file-apps-defaults-gnu)))
  10411. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10412. "Convert extensions to regular expressions in the cars of LIST.
  10413. Also, weed out any non-string entries, because the return value is used
  10414. only for regexp matching.
  10415. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10416. point to the symbol `emacs', indicating that the file should
  10417. be opened in Emacs."
  10418. (append
  10419. (delq nil
  10420. (mapcar (lambda (x)
  10421. (unless (not (stringp (car x)))
  10422. (if (string-match "\\W" (car x))
  10423. x
  10424. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10425. list))
  10426. (when add-auto-mode
  10427. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10428. (defvar ange-ftp-name-format)
  10429. (defun org-file-remote-p (file)
  10430. "Test whether FILE specifies a location on a remote system.
  10431. Return non-nil if the location is indeed remote.
  10432. For example, the filename \"/user@host:/foo\" specifies a location
  10433. on the system \"/user@host:\"."
  10434. (cond ((fboundp 'file-remote-p)
  10435. (file-remote-p file))
  10436. ((fboundp 'tramp-handle-file-remote-p)
  10437. (tramp-handle-file-remote-p file))
  10438. ((and (boundp 'ange-ftp-name-format)
  10439. (string-match (car ange-ftp-name-format) file))
  10440. t)))
  10441. ;;;; Refiling
  10442. (defun org-get-org-file ()
  10443. "Read a filename, with default directory `org-directory'."
  10444. (let ((default (or org-default-notes-file remember-data-file)))
  10445. (read-file-name (format "File name [%s]: " default)
  10446. (file-name-as-directory org-directory)
  10447. default)))
  10448. (defun org-notes-order-reversed-p ()
  10449. "Check if the current file should receive notes in reversed order."
  10450. (cond
  10451. ((not org-reverse-note-order) nil)
  10452. ((eq t org-reverse-note-order) t)
  10453. ((not (listp org-reverse-note-order)) nil)
  10454. (t (catch 'exit
  10455. (dolist (entry org-reverse-note-order)
  10456. (when (string-match (car entry) buffer-file-name)
  10457. (throw 'exit (cdr entry))))))))
  10458. (defvar org-refile-target-table nil
  10459. "The list of refile targets, created by `org-refile'.")
  10460. (defvar org-agenda-new-buffers nil
  10461. "Buffers created to visit agenda files.")
  10462. (defvar org-refile-cache nil
  10463. "Cache for refile targets.")
  10464. (defvar org-refile-markers nil
  10465. "All the markers used for caching refile locations.")
  10466. (defun org-refile-marker (pos)
  10467. "Get a new refile marker, but only if caching is in use."
  10468. (if (not org-refile-use-cache)
  10469. pos
  10470. (let ((m (make-marker)))
  10471. (move-marker m pos)
  10472. (push m org-refile-markers)
  10473. m)))
  10474. (defun org-refile-cache-clear ()
  10475. "Clear the refile cache and disable all the markers."
  10476. (dolist (m org-refile-markers) (move-marker m nil))
  10477. (setq org-refile-markers nil)
  10478. (setq org-refile-cache nil)
  10479. (message "Refile cache has been cleared"))
  10480. (defun org-refile-cache-check-set (set)
  10481. "Check if all the markers in the cache still have live buffers."
  10482. (let (marker)
  10483. (catch 'exit
  10484. (while (and set (setq marker (nth 3 (pop set))))
  10485. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10486. (when (and marker (null (marker-buffer marker)))
  10487. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10488. (sit-for 3)
  10489. (throw 'exit nil)))
  10490. t)))
  10491. (defun org-refile-cache-put (set &rest identifiers)
  10492. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10493. (let* ((key (sha1 (prin1-to-string identifiers)))
  10494. (entry (assoc key org-refile-cache)))
  10495. (if entry
  10496. (setcdr entry set)
  10497. (push (cons key set) org-refile-cache))))
  10498. (defun org-refile-cache-get (&rest identifiers)
  10499. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10500. (cond
  10501. ((not org-refile-cache) nil)
  10502. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10503. (t
  10504. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10505. org-refile-cache))))
  10506. (and set (org-refile-cache-check-set set) set)))))
  10507. (defvar org-outline-path-cache nil
  10508. "Alist between buffer positions and outline paths.
  10509. It value is an alist (POSITION . PATH) where POSITION is the
  10510. buffer position at the beginning of an entry and PATH is a list
  10511. of strings describing the outline path for that entry, in reverse
  10512. order.")
  10513. (defun org-refile-get-targets (&optional default-buffer)
  10514. "Produce a table with refile targets."
  10515. (let ((case-fold-search nil)
  10516. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10517. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10518. targets tgs files desc descre)
  10519. (message "Getting targets...")
  10520. (with-current-buffer (or default-buffer (current-buffer))
  10521. (dolist (entry entries)
  10522. (setq files (car entry) desc (cdr entry))
  10523. (cond
  10524. ((null files) (setq files (list (current-buffer))))
  10525. ((eq files 'org-agenda-files)
  10526. (setq files (org-agenda-files 'unrestricted)))
  10527. ((and (symbolp files) (fboundp files))
  10528. (setq files (funcall files)))
  10529. ((and (symbolp files) (boundp files))
  10530. (setq files (symbol-value files))))
  10531. (when (stringp files) (setq files (list files)))
  10532. (cond
  10533. ((eq (car desc) :tag)
  10534. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10535. ((eq (car desc) :todo)
  10536. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10537. ((eq (car desc) :regexp)
  10538. (setq descre (cdr desc)))
  10539. ((eq (car desc) :level)
  10540. (setq descre (concat "^\\*\\{" (number-to-string
  10541. (if org-odd-levels-only
  10542. (1- (* 2 (cdr desc)))
  10543. (cdr desc)))
  10544. "\\}[ \t]")))
  10545. ((eq (car desc) :maxlevel)
  10546. (setq descre (concat "^\\*\\{1," (number-to-string
  10547. (if org-odd-levels-only
  10548. (1- (* 2 (cdr desc)))
  10549. (cdr desc)))
  10550. "\\}[ \t]")))
  10551. (t (error "Bad refiling target description %s" desc)))
  10552. (dolist (f files)
  10553. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10554. (or
  10555. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10556. (progn
  10557. (when (bufferp f)
  10558. (setq f (buffer-file-name (buffer-base-buffer f))))
  10559. (setq f (and f (expand-file-name f)))
  10560. (when (eq org-refile-use-outline-path 'file)
  10561. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10562. (org-with-wide-buffer
  10563. (goto-char (point-min))
  10564. (setq org-outline-path-cache nil)
  10565. (while (re-search-forward descre nil t)
  10566. (beginning-of-line)
  10567. (let ((case-fold-search nil))
  10568. (looking-at org-complex-heading-regexp))
  10569. (let ((begin (point))
  10570. (heading (match-string-no-properties 4)))
  10571. (unless (or (and
  10572. org-refile-target-verify-function
  10573. (not
  10574. (funcall org-refile-target-verify-function)))
  10575. (not heading))
  10576. (let ((re (format org-complex-heading-regexp-format
  10577. (regexp-quote heading)))
  10578. (target
  10579. (if (not org-refile-use-outline-path) heading
  10580. (mapconcat
  10581. #'org-protect-slash
  10582. (append
  10583. (pcase org-refile-use-outline-path
  10584. (`file (list (file-name-nondirectory
  10585. (buffer-file-name
  10586. (buffer-base-buffer)))))
  10587. (`full-file-path
  10588. (list (buffer-file-name
  10589. (buffer-base-buffer))))
  10590. (_ nil))
  10591. (org-get-outline-path t t))
  10592. "/"))))
  10593. (push (list target f re (org-refile-marker (point)))
  10594. tgs)))
  10595. (when (= (point) begin)
  10596. ;; Verification function has not moved point.
  10597. (end-of-line)))))))
  10598. (when org-refile-use-cache
  10599. (org-refile-cache-put tgs (buffer-file-name) descre))
  10600. (setq targets (append tgs targets))))))
  10601. (message "Getting targets...done")
  10602. (nreverse targets)))
  10603. (defun org-protect-slash (s)
  10604. (replace-regexp-in-string "/" "\\/" s nil t))
  10605. (defun org--get-outline-path-1 (&optional use-cache)
  10606. "Return outline path to current headline.
  10607. Outline path is a list of strings, in reverse order. When
  10608. optional argument USE-CACHE is non-nil, make use of a cache. See
  10609. `org-get-outline-path' for details.
  10610. Assume buffer is widened and point is on a headline."
  10611. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10612. (let ((p (point))
  10613. (heading (let ((case-fold-search nil))
  10614. (looking-at org-complex-heading-regexp)
  10615. (if (not (match-end 4)) ""
  10616. ;; Remove statistics cookies.
  10617. (org-trim
  10618. (org-link-display-format
  10619. (replace-regexp-in-string
  10620. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10621. (match-string-no-properties 4))))))))
  10622. (if (org-up-heading-safe)
  10623. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10624. (when use-cache
  10625. (push (cons p path) org-outline-path-cache))
  10626. path)
  10627. ;; This is a new root node. Since we assume we are moving
  10628. ;; forward, we can drop previous cache so as to limit number
  10629. ;; of associations there.
  10630. (let ((path (list heading)))
  10631. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10632. path)))))
  10633. (defun org-get-outline-path (&optional with-self use-cache)
  10634. "Return the outline path to the current entry.
  10635. An outline path is a list of ancestors for current headline, as
  10636. a list of strings. Statistics cookies are removed and links are
  10637. replaced with their description, if any, or their path otherwise.
  10638. When optional argument WITH-SELF is non-nil, the path also
  10639. includes the current headline.
  10640. When optional argument USE-CACHE is non-nil, cache outline paths
  10641. between calls to this function so as to avoid backtracking. This
  10642. argument is useful when planning to find more than one outline
  10643. path in the same document. In that case, there are two
  10644. conditions to satisfy:
  10645. - `org-outline-path-cache' is set to nil before starting the
  10646. process;
  10647. - outline paths are computed by increasing buffer positions."
  10648. (org-with-wide-buffer
  10649. (and (or (and with-self (org-back-to-heading t))
  10650. (org-up-heading-safe))
  10651. (reverse (org--get-outline-path-1 use-cache)))))
  10652. (defun org-format-outline-path (path &optional width prefix separator)
  10653. "Format the outline path PATH for display.
  10654. WIDTH is the maximum number of characters that is available.
  10655. PREFIX is a prefix to be included in the returned string,
  10656. such as the file name.
  10657. SEPARATOR is inserted between the different parts of the path,
  10658. the default is \"/\"."
  10659. (setq width (or width 79))
  10660. (setq path (delq nil path))
  10661. (unless (> width 0)
  10662. (user-error "Argument `width' must be positive"))
  10663. (setq separator (or separator "/"))
  10664. (let* ((org-odd-levels-only nil)
  10665. (fpath (concat
  10666. prefix (and prefix path separator)
  10667. (mapconcat
  10668. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10669. (cl-loop for head in path
  10670. for n from 0
  10671. collect (org-add-props
  10672. head nil 'face
  10673. (nth (% n org-n-level-faces) org-level-faces)))
  10674. separator))))
  10675. (when (> (length fpath) width)
  10676. (if (< width 7)
  10677. ;; It's unlikely that `width' will be this small, but don't
  10678. ;; waste characters by adding ".." if it is.
  10679. (setq fpath (substring fpath 0 width))
  10680. (setf (substring fpath (- width 2)) "..")))
  10681. fpath))
  10682. (defun org-display-outline-path (&optional file current separator just-return-string)
  10683. "Display the current outline path in the echo area.
  10684. If FILE is non-nil, prepend the output with the file name.
  10685. If CURRENT is non-nil, append the current heading to the output.
  10686. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10687. the different parts of the path and defaults to \"/\".
  10688. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10689. (interactive "P")
  10690. (let* (case-fold-search
  10691. (bfn (buffer-file-name (buffer-base-buffer)))
  10692. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10693. res)
  10694. (when current (setq path (append path
  10695. (save-excursion
  10696. (org-back-to-heading t)
  10697. (when (looking-at org-complex-heading-regexp)
  10698. (list (match-string 4)))))))
  10699. (setq res
  10700. (org-format-outline-path
  10701. path
  10702. (1- (frame-width))
  10703. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10704. separator))
  10705. (if just-return-string
  10706. (org-no-properties res)
  10707. (org-unlogged-message "%s" res))))
  10708. (defvar org-refile-history nil
  10709. "History for refiling operations.")
  10710. (defvar org-after-refile-insert-hook nil
  10711. "Hook run after `org-refile' has inserted its stuff at the new location.
  10712. Note that this is still *before* the stuff will be removed from
  10713. the *old* location.")
  10714. (defvar org-capture-last-stored-marker)
  10715. (defvar org-refile-keep nil
  10716. "Non-nil means `org-refile' will copy instead of refile.")
  10717. (defun org-copy ()
  10718. "Like `org-refile', but copy."
  10719. (interactive)
  10720. (let ((org-refile-keep t))
  10721. (funcall 'org-refile nil nil nil "Copy")))
  10722. (defun org-refile (&optional arg default-buffer rfloc msg)
  10723. "Move the entry or entries at point to another heading.
  10724. The list of target headings is compiled using the information in
  10725. `org-refile-targets', which see.
  10726. At the target location, the entry is filed as a subitem of the
  10727. target heading. Depending on `org-reverse-note-order', the new
  10728. subitem will either be the first or the last subitem.
  10729. If there is an active region, all entries in that region will be
  10730. refiled. However, the region must fulfill the requirement that
  10731. the first heading sets the top-level of the moved text.
  10732. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10733. location
  10734. and not actually move anything.
  10735. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10736. location where the last
  10737. refiling operation has put the subtree.
  10738. With a numeric prefix argument of `2', refile to the running clock.
  10739. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10740. being set to t and copy to the target location, don't move it.
  10741. Beware that keeping refiled entries may result in duplicated ID
  10742. properties.
  10743. RFLOC can be a refile location obtained in a different way.
  10744. MSG is a string to replace \"Refile\" in the default prompt with
  10745. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10746. See also `org-refile-use-outline-path'.
  10747. If you are using target caching (see `org-refile-use-cache'), you
  10748. have to clear the target cache in order to find new targets.
  10749. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10750. prefix argument (`C-u C-u C-u C-c C-w')."
  10751. (interactive "P")
  10752. (if (member arg '(0 (64)))
  10753. (org-refile-cache-clear)
  10754. (let* ((actionmsg (cond (msg msg)
  10755. ((equal arg 3) "Refile (and keep)")
  10756. (t "Refile")))
  10757. (regionp (org-region-active-p))
  10758. (region-start (and regionp (region-beginning)))
  10759. (region-end (and regionp (region-end)))
  10760. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10761. pos it nbuf file level reversed)
  10762. (setq last-command nil)
  10763. (when regionp
  10764. (goto-char region-start)
  10765. (or (bolp) (goto-char (point-at-bol)))
  10766. (setq region-start (point))
  10767. (unless (or (org-kill-is-subtree-p
  10768. (buffer-substring region-start region-end))
  10769. (prog1 org-refile-active-region-within-subtree
  10770. (let ((s (point-at-eol)))
  10771. (org-toggle-heading)
  10772. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10773. (user-error "The region is not a (sequence of) subtree(s)")))
  10774. (if (equal arg '(16))
  10775. (org-refile-goto-last-stored)
  10776. (when (or
  10777. (and (equal arg 2)
  10778. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10779. (prog1
  10780. (setq it (list (or org-clock-heading "running clock")
  10781. (buffer-file-name
  10782. (marker-buffer org-clock-hd-marker))
  10783. ""
  10784. (marker-position org-clock-hd-marker)))
  10785. (setq arg nil)))
  10786. (setq it
  10787. (or rfloc
  10788. (let (heading-text)
  10789. (save-excursion
  10790. (unless (and arg (listp arg))
  10791. (org-back-to-heading t)
  10792. (setq heading-text
  10793. (replace-regexp-in-string
  10794. org-bracket-link-regexp
  10795. "\\3"
  10796. (or (nth 4 (org-heading-components))
  10797. ""))))
  10798. (org-refile-get-location
  10799. (cond ((and arg (listp arg)) "Goto")
  10800. (regionp (concat actionmsg " region to"))
  10801. (t (concat actionmsg " subtree \""
  10802. heading-text "\" to")))
  10803. default-buffer
  10804. (and (not (equal '(4) arg))
  10805. org-refile-allow-creating-parent-nodes)))))))
  10806. (setq file (nth 1 it)
  10807. pos (nth 3 it))
  10808. (when (and (not arg)
  10809. pos
  10810. (equal (buffer-file-name) file)
  10811. (if regionp
  10812. (and (>= pos region-start)
  10813. (<= pos region-end))
  10814. (and (>= pos (point))
  10815. (< pos (save-excursion
  10816. (org-end-of-subtree t t))))))
  10817. (error "Cannot refile to position inside the tree or region"))
  10818. (setq nbuf (or (find-buffer-visiting file)
  10819. (find-file-noselect file)))
  10820. (if (and arg (not (equal arg 3)))
  10821. (progn
  10822. (pop-to-buffer-same-window nbuf)
  10823. (goto-char pos)
  10824. (org-show-context 'org-goto))
  10825. (if regionp
  10826. (progn
  10827. (org-kill-new (buffer-substring region-start region-end))
  10828. (org-save-markers-in-region region-start region-end))
  10829. (org-copy-subtree 1 nil t))
  10830. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10831. (find-file-noselect file)))
  10832. (setq reversed (org-notes-order-reversed-p))
  10833. (org-with-wide-buffer
  10834. (if pos
  10835. (progn
  10836. (goto-char pos)
  10837. (looking-at org-outline-regexp)
  10838. (setq level (org-get-valid-level (funcall outline-level) 1))
  10839. (goto-char
  10840. (if reversed
  10841. (or (outline-next-heading) (point-max))
  10842. (or (save-excursion (org-get-next-sibling))
  10843. (org-end-of-subtree t t)
  10844. (point-max)))))
  10845. (setq level 1)
  10846. (if (not reversed)
  10847. (goto-char (point-max))
  10848. (goto-char (point-min))
  10849. (or (outline-next-heading) (goto-char (point-max)))))
  10850. (unless (bolp) (newline))
  10851. (org-paste-subtree level nil nil t)
  10852. (when org-log-refile
  10853. (org-add-log-setup 'refile nil nil org-log-refile)
  10854. (unless (eq org-log-refile 'note)
  10855. (save-excursion (org-add-log-note))))
  10856. (and org-auto-align-tags
  10857. (let ((org-loop-over-headlines-in-active-region nil))
  10858. (org-set-tags nil t)))
  10859. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10860. :last-refile)))
  10861. (when bookmark-name
  10862. (with-demoted-errors
  10863. (bookmark-set bookmark-name))))
  10864. ;; If we are refiling for capture, make sure that the
  10865. ;; last-capture pointers point here
  10866. (when (bound-and-true-p org-capture-is-refiling)
  10867. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10868. :last-capture-marker)))
  10869. (when bookmark-name
  10870. (with-demoted-errors
  10871. (bookmark-set bookmark-name))))
  10872. (move-marker org-capture-last-stored-marker (point)))
  10873. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10874. (run-hooks 'org-after-refile-insert-hook)))
  10875. (unless org-refile-keep
  10876. (if regionp
  10877. (delete-region (point) (+ (point) (- region-end region-start)))
  10878. (delete-region
  10879. (and (org-back-to-heading t) (point))
  10880. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10881. (when (featurep 'org-inlinetask)
  10882. (org-inlinetask-remove-END-maybe))
  10883. (setq org-markers-to-move nil)
  10884. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10885. (defun org-refile-goto-last-stored ()
  10886. "Go to the location where the last refile was stored."
  10887. (interactive)
  10888. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10889. (message "This is the location of the last refile"))
  10890. (defun org-refile--get-location (refloc tbl)
  10891. "When user refile to REFLOC, find the associated target in TBL.
  10892. Also check `org-refile-target-table'."
  10893. (car (delq
  10894. nil
  10895. (mapcar
  10896. (lambda (r) (or (assoc r tbl)
  10897. (assoc r org-refile-target-table)))
  10898. (list (replace-regexp-in-string "/$" "" refloc)
  10899. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10900. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10901. "Prompt the user for a refile location, using PROMPT.
  10902. PROMPT should not be suffixed with a colon and a space, because
  10903. this function appends the default value from
  10904. `org-refile-history' automatically, if that is not empty."
  10905. (let ((org-refile-targets org-refile-targets)
  10906. (org-refile-use-outline-path org-refile-use-outline-path))
  10907. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10908. (unless org-refile-target-table
  10909. (user-error "No refile targets"))
  10910. (let* ((cbuf (current-buffer))
  10911. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10912. (cfunc (if (and org-refile-use-outline-path
  10913. org-outline-path-complete-in-steps)
  10914. #'org-olpath-completing-read
  10915. #'completing-read))
  10916. (extra (if org-refile-use-outline-path "/" ""))
  10917. (cbnex (concat (buffer-name) extra))
  10918. (filename (and cfn (expand-file-name cfn)))
  10919. (tbl (mapcar
  10920. (lambda (x)
  10921. (if (and (not (member org-refile-use-outline-path
  10922. '(file full-file-path)))
  10923. (not (equal filename (nth 1 x))))
  10924. (cons (concat (car x) extra " ("
  10925. (file-name-nondirectory (nth 1 x)) ")")
  10926. (cdr x))
  10927. (cons (concat (car x) extra) (cdr x))))
  10928. org-refile-target-table))
  10929. (completion-ignore-case t)
  10930. cdef
  10931. (prompt (concat prompt
  10932. (or (and (car org-refile-history)
  10933. (concat " (default " (car org-refile-history) ")"))
  10934. (and (assoc cbnex tbl) (setq cdef cbnex)
  10935. (concat " (default " cbnex ")"))) ": "))
  10936. pa answ parent-target child parent old-hist)
  10937. (setq old-hist org-refile-history)
  10938. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10939. nil 'org-refile-history (or cdef (car org-refile-history))))
  10940. (if (setq pa (org-refile--get-location answ tbl))
  10941. (progn
  10942. (org-refile-check-position pa)
  10943. (when (or (not org-refile-history)
  10944. (not (eq old-hist org-refile-history))
  10945. (not (equal (car pa) (car org-refile-history))))
  10946. (setq org-refile-history
  10947. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10948. org-refile-history
  10949. (cdr org-refile-history))))
  10950. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10951. (pop org-refile-history)))
  10952. pa)
  10953. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10954. (progn
  10955. (setq parent (match-string 1 answ)
  10956. child (match-string 2 answ))
  10957. (setq parent-target (org-refile--get-location parent tbl))
  10958. (when (and parent-target
  10959. (or (eq new-nodes t)
  10960. (and (eq new-nodes 'confirm)
  10961. (y-or-n-p (format "Create new node \"%s\"? "
  10962. child)))))
  10963. (org-refile-new-child parent-target child)))
  10964. (user-error "Invalid target location")))))
  10965. (declare-function org-string-nw-p "org-macs" (s))
  10966. (defun org-refile-check-position (refile-pointer)
  10967. "Check if the refile pointer matches the headline to which it points."
  10968. (let* ((file (nth 1 refile-pointer))
  10969. (re (nth 2 refile-pointer))
  10970. (pos (nth 3 refile-pointer))
  10971. buffer)
  10972. (if (and (not (markerp pos)) (not file))
  10973. (user-error "Please indicate a target file in the refile path")
  10974. (when (org-string-nw-p re)
  10975. (setq buffer (if (markerp pos)
  10976. (marker-buffer pos)
  10977. (or (find-buffer-visiting file)
  10978. (find-file-noselect file))))
  10979. (with-current-buffer buffer
  10980. (org-with-wide-buffer
  10981. (goto-char pos)
  10982. (beginning-of-line 1)
  10983. (unless (looking-at-p re)
  10984. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10985. (defun org-refile-new-child (parent-target child)
  10986. "Use refile target PARENT-TARGET to add new CHILD below it."
  10987. (unless parent-target
  10988. (error "Cannot find parent for new node"))
  10989. (let ((file (nth 1 parent-target))
  10990. (pos (nth 3 parent-target))
  10991. level)
  10992. (with-current-buffer (or (find-buffer-visiting file)
  10993. (find-file-noselect file))
  10994. (org-with-wide-buffer
  10995. (if pos
  10996. (goto-char pos)
  10997. (goto-char (point-max))
  10998. (unless (bolp) (newline)))
  10999. (when (looking-at org-outline-regexp)
  11000. (setq level (funcall outline-level))
  11001. (org-end-of-subtree t t))
  11002. (org-back-over-empty-lines)
  11003. (insert "\n" (make-string
  11004. (if pos (org-get-valid-level level 1) 1) ?*)
  11005. " " child "\n")
  11006. (beginning-of-line 0)
  11007. (list (concat (car parent-target) "/" child) file "" (point))))))
  11008. (defun org-olpath-completing-read (prompt collection &rest args)
  11009. "Read an outline path like a file name."
  11010. (let ((thetable collection))
  11011. (apply #'completing-read
  11012. prompt
  11013. (lambda (string predicate &optional flag)
  11014. (cond
  11015. ((eq flag nil) (try-completion string thetable))
  11016. ((eq flag t)
  11017. (let ((l (length string)))
  11018. (mapcar (lambda (x)
  11019. (let ((r (substring x l))
  11020. (f (if (string-match " ([^)]*)$" x)
  11021. (match-string 0 x)
  11022. "")))
  11023. (if (string-match "/" r)
  11024. (concat string (substring r 0 (match-end 0)) f)
  11025. x)))
  11026. (all-completions string thetable predicate))))
  11027. ;; Exact match?
  11028. ((eq flag 'lambda) (assoc string thetable))))
  11029. args)))
  11030. ;;;; Dynamic blocks
  11031. (defun org-find-dblock (name)
  11032. "Find the first dynamic block with name NAME in the buffer.
  11033. If not found, stay at current position and return nil."
  11034. (let ((case-fold-search t) pos)
  11035. (save-excursion
  11036. (goto-char (point-min))
  11037. (setq pos (and (re-search-forward
  11038. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11039. (match-beginning 0))))
  11040. (when pos (goto-char pos))
  11041. pos))
  11042. (defun org-create-dblock (plist)
  11043. "Create a dynamic block section, with parameters taken from PLIST.
  11044. PLIST must contain a :name entry which is used as the name of the block."
  11045. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11046. (end-of-line 1)
  11047. (newline))
  11048. (let ((col (current-column))
  11049. (name (plist-get plist :name)))
  11050. (insert "#+BEGIN: " name)
  11051. (while plist
  11052. (if (eq (car plist) :name)
  11053. (setq plist (cddr plist))
  11054. (insert " " (prin1-to-string (pop plist)))))
  11055. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11056. (beginning-of-line -2)))
  11057. (defun org-prepare-dblock ()
  11058. "Prepare dynamic block for refresh.
  11059. This empties the block, puts the cursor at the insert position and returns
  11060. the property list including an extra property :name with the block name."
  11061. (unless (looking-at org-dblock-start-re)
  11062. (user-error "Not at a dynamic block"))
  11063. (let* ((begdel (1+ (match-end 0)))
  11064. (name (org-no-properties (match-string 1)))
  11065. (params (append (list :name name)
  11066. (read (concat "(" (match-string 3) ")")))))
  11067. (save-excursion
  11068. (beginning-of-line 1)
  11069. (skip-chars-forward " \t")
  11070. (setq params (plist-put params :indentation-column (current-column))))
  11071. (unless (re-search-forward org-dblock-end-re nil t)
  11072. (error "Dynamic block not terminated"))
  11073. (setq params
  11074. (append params
  11075. (list :content (buffer-substring
  11076. begdel (match-beginning 0)))))
  11077. (delete-region begdel (match-beginning 0))
  11078. (goto-char begdel)
  11079. (open-line 1)
  11080. params))
  11081. (defun org-map-dblocks (&optional command)
  11082. "Apply COMMAND to all dynamic blocks in the current buffer.
  11083. If COMMAND is not given, use `org-update-dblock'."
  11084. (let ((cmd (or command 'org-update-dblock)))
  11085. (save-excursion
  11086. (goto-char (point-min))
  11087. (while (re-search-forward org-dblock-start-re nil t)
  11088. (goto-char (match-beginning 0))
  11089. (save-excursion
  11090. (condition-case nil
  11091. (funcall cmd)
  11092. (error (message "Error during update of dynamic block"))))
  11093. (unless (re-search-forward org-dblock-end-re nil t)
  11094. (error "Dynamic block not terminated"))))))
  11095. (defun org-dblock-update (&optional arg)
  11096. "User command for updating dynamic blocks.
  11097. Update the dynamic block at point. With prefix ARG, update all dynamic
  11098. blocks in the buffer."
  11099. (interactive "P")
  11100. (if arg
  11101. (org-update-all-dblocks)
  11102. (or (looking-at org-dblock-start-re)
  11103. (org-beginning-of-dblock))
  11104. (org-update-dblock)))
  11105. (defun org-update-dblock ()
  11106. "Update the dynamic block at point.
  11107. This means to empty the block, parse for parameters and then call
  11108. the correct writing function."
  11109. (interactive)
  11110. (save-excursion
  11111. (let* ((win (selected-window))
  11112. (pos (point))
  11113. (line (org-current-line))
  11114. (params (org-prepare-dblock))
  11115. (name (plist-get params :name))
  11116. (indent (plist-get params :indentation-column))
  11117. (cmd (intern (concat "org-dblock-write:" name))))
  11118. (message "Updating dynamic block `%s' at line %d..." name line)
  11119. (funcall cmd params)
  11120. (message "Updating dynamic block `%s' at line %d...done" name line)
  11121. (goto-char pos)
  11122. (when (and indent (> indent 0))
  11123. (setq indent (make-string indent ?\ ))
  11124. (save-excursion
  11125. (select-window win)
  11126. (org-beginning-of-dblock)
  11127. (forward-line 1)
  11128. (while (not (looking-at org-dblock-end-re))
  11129. (insert indent)
  11130. (beginning-of-line 2))
  11131. (when (looking-at org-dblock-end-re)
  11132. (and (looking-at "[ \t]+")
  11133. (replace-match ""))
  11134. (insert indent)))))))
  11135. (defun org-beginning-of-dblock ()
  11136. "Find the beginning of the dynamic block at point.
  11137. Error if there is no such block at point."
  11138. (let ((pos (point))
  11139. beg)
  11140. (end-of-line 1)
  11141. (if (and (re-search-backward org-dblock-start-re nil t)
  11142. (setq beg (match-beginning 0))
  11143. (re-search-forward org-dblock-end-re nil t)
  11144. (> (match-end 0) pos))
  11145. (goto-char beg)
  11146. (goto-char pos)
  11147. (error "Not in a dynamic block"))))
  11148. (defun org-update-all-dblocks ()
  11149. "Update all dynamic blocks in the buffer.
  11150. This function can be used in a hook."
  11151. (interactive)
  11152. (when (derived-mode-p 'org-mode)
  11153. (org-map-dblocks 'org-update-dblock)))
  11154. ;;;; Completion
  11155. (declare-function org-export-backend-options "ox" (cl-x) t)
  11156. (defun org-get-export-keywords ()
  11157. "Return a list of all currently understood export keywords.
  11158. Export keywords include options, block names, attributes and
  11159. keywords relative to each registered export back-end."
  11160. (let (keywords)
  11161. (dolist (backend
  11162. (bound-and-true-p org-export-registered-backends)
  11163. (delq nil keywords))
  11164. ;; Back-end name (for keywords, like #+LATEX:)
  11165. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11166. (dolist (option-entry (org-export-backend-options backend))
  11167. ;; Back-end options.
  11168. (push (nth 1 option-entry) keywords)))))
  11169. (defconst org-options-keywords
  11170. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11171. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11172. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11173. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11174. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11175. (defcustom org-structure-template-alist
  11176. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11177. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11178. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11179. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11180. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11181. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11182. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11183. ("L" "#+LaTeX: ")
  11184. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11185. ("H" "#+HTML: ")
  11186. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11187. ("A" "#+ASCII: ")
  11188. ("i" "#+INDEX: ?")
  11189. ("I" "#+INCLUDE: %file ?"))
  11190. "Structure completion elements.
  11191. This is a list of abbreviation keys and values. The value gets inserted
  11192. if you type `<' followed by the key and then press the completion key,
  11193. usually `TAB'. %file will be replaced by a file name after prompting
  11194. for the file using completion. The cursor will be placed at the position
  11195. of the `?' in the template.
  11196. There are two templates for each key, the first uses the original Org syntax,
  11197. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11198. the default when the /org-mtags.el/ module has been loaded. See also the
  11199. variable `org-mtags-prefer-muse-templates'."
  11200. :group 'org-completion
  11201. :type '(repeat
  11202. (list
  11203. (string :tag "Key")
  11204. (string :tag "Template")))
  11205. :version "25.2"
  11206. :package-version '(Org . "8.3"))
  11207. (defun org-try-structure-completion ()
  11208. "Try to complete a structure template before point.
  11209. This looks for strings like \"<e\" on an otherwise empty line and
  11210. expands them."
  11211. (let ((l (buffer-substring (point-at-bol) (point)))
  11212. a)
  11213. (when (and (looking-at "[ \t]*$")
  11214. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11215. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11216. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11217. (match-beginning 1)) a)
  11218. t)))
  11219. (defun org-complete-expand-structure-template (start cell)
  11220. "Expand a structure template."
  11221. (let ((rpl (nth 1 cell))
  11222. (ind ""))
  11223. (delete-region start (point))
  11224. (when (string-match "\\`[ \t]*#\\+" rpl)
  11225. (cond
  11226. ((bolp))
  11227. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11228. (setq ind (buffer-substring (point-at-bol) (point))))
  11229. (t (newline))))
  11230. (setq start (point))
  11231. (when (string-match "%file" rpl)
  11232. (setq rpl (replace-match
  11233. (concat
  11234. "\""
  11235. (save-match-data
  11236. (abbreviate-file-name (read-file-name "Include file: ")))
  11237. "\"")
  11238. t t rpl)))
  11239. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11240. (concat "\n" ind)))
  11241. (insert rpl)
  11242. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11243. ;;;; TODO, DEADLINE, Comments
  11244. (defun org-toggle-comment ()
  11245. "Change the COMMENT state of an entry."
  11246. (interactive)
  11247. (save-excursion
  11248. (org-back-to-heading)
  11249. (let ((case-fold-search nil))
  11250. (looking-at org-complex-heading-regexp))
  11251. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11252. (skip-chars-forward " \t")
  11253. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11254. (if (org-in-commented-heading-p t)
  11255. (delete-region (point)
  11256. (progn (search-forward " " (line-end-position) 'move)
  11257. (skip-chars-forward " \t")
  11258. (point)))
  11259. (insert org-comment-string)
  11260. (unless (eolp) (insert " ")))))
  11261. (defvar org-last-todo-state-is-todo nil
  11262. "This is non-nil when the last TODO state change led to a TODO state.
  11263. If the last change removed the TODO tag or switched to DONE, then
  11264. this is nil.")
  11265. (defvar org-setting-tags nil) ; dynamically skipped
  11266. (defvar org-todo-setup-filter-hook nil
  11267. "Hook for functions that pre-filter todo specs.
  11268. Each function takes a todo spec and returns either nil or the spec
  11269. transformed into canonical form." )
  11270. (defvar org-todo-get-default-hook nil
  11271. "Hook for functions that get a default item for todo.
  11272. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11273. nil or a string to be used for the todo mark." )
  11274. (defvar org-agenda-headline-snapshot-before-repeat)
  11275. (defun org-current-effective-time ()
  11276. "Return current time adjusted for `org-extend-today-until' variable."
  11277. (let* ((ct (org-current-time))
  11278. (dct (decode-time ct))
  11279. (ct1
  11280. (cond
  11281. (org-use-last-clock-out-time-as-effective-time
  11282. (or (org-clock-get-last-clock-out-time) ct))
  11283. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11284. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11285. (t ct))))
  11286. ct1))
  11287. (defun org-todo-yesterday (&optional arg)
  11288. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11289. (interactive "P")
  11290. (if (eq major-mode 'org-agenda-mode)
  11291. (apply 'org-agenda-todo-yesterday arg)
  11292. (let* ((org-use-effective-time t)
  11293. (hour (nth 2 (decode-time (org-current-time))))
  11294. (org-extend-today-until (1+ hour)))
  11295. (org-todo arg))))
  11296. (defvar org-block-entry-blocking ""
  11297. "First entry preventing the TODO state change.")
  11298. (defun org-cancel-repeater ()
  11299. "Cancel a repeater by setting its numeric value to zero."
  11300. (interactive)
  11301. (save-excursion
  11302. (org-back-to-heading t)
  11303. (let ((bound1 (point))
  11304. (bound0 (save-excursion (outline-next-heading) (point))))
  11305. (when (and (re-search-forward
  11306. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11307. org-deadline-time-regexp "\\)\\|\\("
  11308. org-ts-regexp "\\)")
  11309. bound0 t)
  11310. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11311. bound1 t))
  11312. (replace-match "0" t nil nil 1)))))
  11313. (defvar org-state) ;; dynamically scoped into this function
  11314. (defun org-todo (&optional arg)
  11315. "Change the TODO state of an item.
  11316. The state of an item is given by a keyword at the start of the heading,
  11317. like
  11318. *** TODO Write paper
  11319. *** DONE Call mom
  11320. The different keywords are specified in the variable `org-todo-keywords'.
  11321. By default the available states are \"TODO\" and \"DONE\". So, for this
  11322. example: when the item starts with TODO, it is changed to DONE.
  11323. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11324. DONE are present, add TODO at the beginning of the heading.
  11325. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11326. state.
  11327. With numeric prefix ARG, switch to that state.
  11328. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11329. next set of TODO \
  11330. keywords (nextset).
  11331. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11332. prefix, circumvent any state blocking.
  11333. With a numeric prefix arg of 0, inhibit note taking for the change.
  11334. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11335. When called through ELisp, arg is also interpreted in the following way:
  11336. `none' -> empty state
  11337. \"\" -> switch to empty state
  11338. `done' -> switch to DONE
  11339. `nextset' -> switch to the next set of keywords
  11340. `previousset' -> switch to the previous set of keywords
  11341. \"WAITING\" -> switch to the specified keyword, but only if it
  11342. really is a member of `org-todo-keywords'."
  11343. (interactive "P")
  11344. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11345. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11346. 'region-start-level 'region))
  11347. org-loop-over-headlines-in-active-region)
  11348. (org-map-entries
  11349. `(org-todo ,arg)
  11350. org-loop-over-headlines-in-active-region
  11351. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11352. (when (equal arg '(16)) (setq arg 'nextset))
  11353. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11354. (let ((org-blocker-hook org-blocker-hook)
  11355. commentp
  11356. case-fold-search)
  11357. (when (equal arg '(64))
  11358. (setq arg nil org-blocker-hook nil))
  11359. (when (and org-blocker-hook
  11360. (or org-inhibit-blocking
  11361. (org-entry-get nil "NOBLOCKING")))
  11362. (setq org-blocker-hook nil))
  11363. (save-excursion
  11364. (catch 'exit
  11365. (org-back-to-heading t)
  11366. (when (org-in-commented-heading-p t)
  11367. (org-toggle-comment)
  11368. (setq commentp t))
  11369. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11370. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11371. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11372. (let* ((match-data (match-data))
  11373. (startpos (point-at-bol))
  11374. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11375. (org-log-done org-log-done)
  11376. (org-log-repeat org-log-repeat)
  11377. (org-todo-log-states org-todo-log-states)
  11378. (org-inhibit-logging
  11379. (if (equal arg 0)
  11380. (progn (setq arg nil) 'note) org-inhibit-logging))
  11381. (this (match-string 1))
  11382. (hl-pos (match-beginning 0))
  11383. (head (org-get-todo-sequence-head this))
  11384. (ass (assoc head org-todo-kwd-alist))
  11385. (interpret (nth 1 ass))
  11386. (done-word (nth 3 ass))
  11387. (final-done-word (nth 4 ass))
  11388. (org-last-state (or this ""))
  11389. (completion-ignore-case t)
  11390. (member (member this org-todo-keywords-1))
  11391. (tail (cdr member))
  11392. (org-state (cond
  11393. ((and org-todo-key-trigger
  11394. (or (and (equal arg '(4))
  11395. (eq org-use-fast-todo-selection 'prefix))
  11396. (and (not arg) org-use-fast-todo-selection
  11397. (not (eq org-use-fast-todo-selection
  11398. 'prefix)))))
  11399. ;; Use fast selection
  11400. (org-fast-todo-selection))
  11401. ((and (equal arg '(4))
  11402. (or (not org-use-fast-todo-selection)
  11403. (not org-todo-key-trigger)))
  11404. ;; Read a state with completion
  11405. (completing-read
  11406. "State: " (mapcar #'list org-todo-keywords-1)
  11407. nil t))
  11408. ((eq arg 'right)
  11409. (if this
  11410. (if tail (car tail) nil)
  11411. (car org-todo-keywords-1)))
  11412. ((eq arg 'left)
  11413. (unless (equal member org-todo-keywords-1)
  11414. (if this
  11415. (nth (- (length org-todo-keywords-1)
  11416. (length tail) 2)
  11417. org-todo-keywords-1)
  11418. (org-last org-todo-keywords-1))))
  11419. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11420. (setq arg nil))) ; hack to fall back to cycling
  11421. (arg
  11422. ;; user or caller requests a specific state
  11423. (cond
  11424. ((equal arg "") nil)
  11425. ((eq arg 'none) nil)
  11426. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11427. ((eq arg 'nextset)
  11428. (or (car (cdr (member head org-todo-heads)))
  11429. (car org-todo-heads)))
  11430. ((eq arg 'previousset)
  11431. (let ((org-todo-heads (reverse org-todo-heads)))
  11432. (or (car (cdr (member head org-todo-heads)))
  11433. (car org-todo-heads))))
  11434. ((car (member arg org-todo-keywords-1)))
  11435. ((stringp arg)
  11436. (user-error "State `%s' not valid in this file" arg))
  11437. ((nth (1- (prefix-numeric-value arg))
  11438. org-todo-keywords-1))))
  11439. ((null member) (or head (car org-todo-keywords-1)))
  11440. ((equal this final-done-word) nil) ;; -> make empty
  11441. ((null tail) nil) ;; -> first entry
  11442. ((memq interpret '(type priority))
  11443. (if (eq this-command last-command)
  11444. (car tail)
  11445. (if (> (length tail) 0)
  11446. (or done-word (car org-done-keywords))
  11447. nil)))
  11448. (t
  11449. (car tail))))
  11450. (org-state (or
  11451. (run-hook-with-args-until-success
  11452. 'org-todo-get-default-hook org-state org-last-state)
  11453. org-state))
  11454. (next (if org-state (concat " " org-state " ") " "))
  11455. (change-plist (list :type 'todo-state-change :from this :to org-state
  11456. :position startpos))
  11457. dolog now-done-p)
  11458. (when org-blocker-hook
  11459. (setq org-last-todo-state-is-todo
  11460. (not (member this org-done-keywords)))
  11461. (unless (save-excursion
  11462. (save-match-data
  11463. (org-with-wide-buffer
  11464. (run-hook-with-args-until-failure
  11465. 'org-blocker-hook change-plist))))
  11466. (if (called-interactively-p 'interactive)
  11467. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11468. this org-state org-block-entry-blocking)
  11469. ;; fail silently
  11470. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11471. this org-state org-block-entry-blocking)
  11472. (throw 'exit nil))))
  11473. (store-match-data match-data)
  11474. (replace-match next t t)
  11475. (cond ((equal this org-state)
  11476. (message "TODO state was already %s" (org-trim next)))
  11477. ((pos-visible-in-window-p hl-pos)
  11478. (message "TODO state changed to %s" (org-trim next))))
  11479. (unless head
  11480. (setq head (org-get-todo-sequence-head org-state)
  11481. ass (assoc head org-todo-kwd-alist)
  11482. interpret (nth 1 ass)
  11483. done-word (nth 3 ass)
  11484. final-done-word (nth 4 ass)))
  11485. (when (memq arg '(nextset previousset))
  11486. (message "Keyword-Set %d/%d: %s"
  11487. (- (length org-todo-sets) -1
  11488. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11489. (length org-todo-sets)
  11490. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11491. (setq org-last-todo-state-is-todo
  11492. (not (member org-state org-done-keywords)))
  11493. (setq now-done-p (and (member org-state org-done-keywords)
  11494. (not (member this org-done-keywords))))
  11495. (and logging (org-local-logging logging))
  11496. (when (and (or org-todo-log-states org-log-done)
  11497. (not (eq org-inhibit-logging t))
  11498. (not (memq arg '(nextset previousset))))
  11499. ;; we need to look at recording a time and note
  11500. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11501. (nth 2 (assoc this org-todo-log-states))))
  11502. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11503. (setq dolog 'time))
  11504. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11505. (and org-state
  11506. (member org-state org-not-done-keywords)
  11507. (not (member this org-not-done-keywords))))
  11508. ;; This is now a todo state and was not one before
  11509. ;; If there was a CLOSED time stamp, get rid of it.
  11510. (org-add-planning-info nil nil 'closed))
  11511. (when (and now-done-p org-log-done)
  11512. ;; It is now done, and it was not done before
  11513. (org-add-planning-info 'closed (org-current-effective-time))
  11514. (when (and (not dolog) (eq 'note org-log-done))
  11515. (org-add-log-setup 'done org-state this 'note)))
  11516. (when (and org-state dolog)
  11517. ;; This is a non-nil state, and we need to log it
  11518. (org-add-log-setup 'state org-state this dolog)))
  11519. ;; Fixup tag positioning
  11520. (org-todo-trigger-tag-changes org-state)
  11521. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11522. (when org-provide-todo-statistics
  11523. (org-update-parent-todo-statistics))
  11524. (run-hooks 'org-after-todo-state-change-hook)
  11525. (when (and arg (not (member org-state org-done-keywords)))
  11526. (setq head (org-get-todo-sequence-head org-state)))
  11527. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11528. ;; Do we need to trigger a repeat?
  11529. (when now-done-p
  11530. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11531. ;; This is for the agenda, take a snapshot of the headline.
  11532. (save-match-data
  11533. (setq org-agenda-headline-snapshot-before-repeat
  11534. (org-get-heading))))
  11535. (org-auto-repeat-maybe org-state))
  11536. ;; Fixup cursor location if close to the keyword
  11537. (when (and (outline-on-heading-p)
  11538. (not (bolp))
  11539. (save-excursion (beginning-of-line 1)
  11540. (looking-at org-todo-line-regexp))
  11541. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11542. (goto-char (or (match-end 2) (match-end 1)))
  11543. (and (looking-at " ") (just-one-space)))
  11544. (when org-trigger-hook
  11545. (save-excursion
  11546. (run-hook-with-args 'org-trigger-hook change-plist)))
  11547. (when commentp (org-toggle-comment))))))))
  11548. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11549. "Block turning an entry into a TODO, using the hierarchy.
  11550. This checks whether the current task should be blocked from state
  11551. changes. Such blocking occurs when:
  11552. 1. The task has children which are not all in a completed state.
  11553. 2. A task has a parent with the property :ORDERED:, and there
  11554. are siblings prior to the current task with incomplete
  11555. status.
  11556. 3. The parent of the task is blocked because it has siblings that should
  11557. be done first, or is child of a block grandparent TODO entry."
  11558. (if (not org-enforce-todo-dependencies)
  11559. t ; if locally turned off don't block
  11560. (catch 'dont-block
  11561. ;; If this is not a todo state change, or if this entry is already DONE,
  11562. ;; do not block
  11563. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11564. (member (plist-get change-plist :from)
  11565. (cons 'done org-done-keywords))
  11566. (member (plist-get change-plist :to)
  11567. (cons 'todo org-not-done-keywords))
  11568. (not (plist-get change-plist :to)))
  11569. (throw 'dont-block t))
  11570. ;; If this task has children, and any are undone, it's blocked
  11571. (save-excursion
  11572. (org-back-to-heading t)
  11573. (let ((this-level (funcall outline-level)))
  11574. (outline-next-heading)
  11575. (let ((child-level (funcall outline-level)))
  11576. (while (and (not (eobp))
  11577. (> child-level this-level))
  11578. ;; this todo has children, check whether they are all
  11579. ;; completed
  11580. (when (and (not (org-entry-is-done-p))
  11581. (org-entry-is-todo-p))
  11582. (setq org-block-entry-blocking (org-get-heading))
  11583. (throw 'dont-block nil))
  11584. (outline-next-heading)
  11585. (setq child-level (funcall outline-level))))))
  11586. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11587. ;; any previous siblings are undone, it's blocked
  11588. (save-excursion
  11589. (org-back-to-heading t)
  11590. (let* ((pos (point))
  11591. (parent-pos (and (org-up-heading-safe) (point))))
  11592. (unless parent-pos (throw 'dont-block t)) ; no parent
  11593. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11594. (forward-line 1)
  11595. (re-search-forward org-not-done-heading-regexp pos t))
  11596. (setq org-block-entry-blocking (match-string 0))
  11597. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11598. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11599. (while t
  11600. (goto-char parent-pos)
  11601. (unless (looking-at org-not-done-heading-regexp)
  11602. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11603. (setq pos (point))
  11604. (setq parent-pos (and (org-up-heading-safe) (point)))
  11605. (unless parent-pos (throw 'dont-block t)) ; no parent
  11606. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11607. (forward-line 1)
  11608. (re-search-forward org-not-done-heading-regexp pos t)
  11609. (setq org-block-entry-blocking (org-get-heading)))
  11610. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11611. (defcustom org-track-ordered-property-with-tag nil
  11612. "Should the ORDERED property also be shown as a tag?
  11613. The ORDERED property decides if an entry should require subtasks to be
  11614. completed in sequence. Since a property is not very visible, setting
  11615. this option means that toggling the ORDERED property with the command
  11616. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11617. not relevant for the behavior, but it makes things more visible.
  11618. Note that toggling the tag with tags commands will not change the property
  11619. and therefore not influence behavior!
  11620. This can be t, meaning the tag ORDERED should be used, It can also be a
  11621. string to select a different tag for this task."
  11622. :group 'org-todo
  11623. :type '(choice
  11624. (const :tag "No tracking" nil)
  11625. (const :tag "Track with ORDERED tag" t)
  11626. (string :tag "Use other tag")))
  11627. (defun org-toggle-ordered-property ()
  11628. "Toggle the ORDERED property of the current entry.
  11629. For better visibility, you can track the value of this property with a tag.
  11630. See variable `org-track-ordered-property-with-tag'."
  11631. (interactive)
  11632. (let* ((t1 org-track-ordered-property-with-tag)
  11633. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11634. (save-excursion
  11635. (org-back-to-heading)
  11636. (if (org-entry-get nil "ORDERED")
  11637. (progn
  11638. (org-delete-property "ORDERED")
  11639. (and tag (org-toggle-tag tag 'off))
  11640. (message "Subtasks can be completed in arbitrary order"))
  11641. (org-entry-put nil "ORDERED" "t")
  11642. (and tag (org-toggle-tag tag 'on))
  11643. (message "Subtasks must be completed in sequence")))))
  11644. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11645. (defun org-block-todo-from-checkboxes (change-plist)
  11646. "Block turning an entry into a TODO, using checkboxes.
  11647. This checks whether the current task should be blocked from state
  11648. changes because there are unchecked boxes in this entry."
  11649. (if (not org-enforce-todo-checkbox-dependencies)
  11650. t ; if locally turned off don't block
  11651. (catch 'dont-block
  11652. ;; If this is not a todo state change, or if this entry is already DONE,
  11653. ;; do not block
  11654. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11655. (member (plist-get change-plist :from)
  11656. (cons 'done org-done-keywords))
  11657. (member (plist-get change-plist :to)
  11658. (cons 'todo org-not-done-keywords))
  11659. (not (plist-get change-plist :to)))
  11660. (throw 'dont-block t))
  11661. ;; If this task has checkboxes that are not checked, it's blocked
  11662. (save-excursion
  11663. (org-back-to-heading t)
  11664. (let ((beg (point)) end)
  11665. (outline-next-heading)
  11666. (setq end (point))
  11667. (goto-char beg)
  11668. (when (org-list-search-forward
  11669. (concat (org-item-beginning-re)
  11670. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11671. "\\[[- ]\\]")
  11672. end t)
  11673. (when (boundp 'org-blocked-by-checkboxes)
  11674. (setq org-blocked-by-checkboxes t))
  11675. (throw 'dont-block nil))))
  11676. t))) ; do not block
  11677. (defun org-entry-blocked-p ()
  11678. "Non-nil if entry at point is blocked."
  11679. (and (not (org-entry-get nil "NOBLOCKING"))
  11680. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11681. (not (run-hook-with-args-until-failure
  11682. 'org-blocker-hook
  11683. (list :type 'todo-state-change
  11684. :position (point)
  11685. :from 'todo
  11686. :to 'done)))))
  11687. (defun org-update-statistics-cookies (all)
  11688. "Update the statistics cookie, either from TODO or from checkboxes.
  11689. This should be called with the cursor in a line with a statistics
  11690. cookie. When called with a \\[universal-argument] prefix, update
  11691. all statistics cookies in the buffer."
  11692. (interactive "P")
  11693. (if all
  11694. (progn
  11695. (org-update-checkbox-count 'all)
  11696. (org-map-entries 'org-update-parent-todo-statistics))
  11697. (if (not (org-at-heading-p))
  11698. (org-update-checkbox-count)
  11699. (let ((pos (point-marker))
  11700. end l1 l2)
  11701. (ignore-errors (org-back-to-heading t))
  11702. (if (not (org-at-heading-p))
  11703. (org-update-checkbox-count)
  11704. (setq l1 (org-outline-level))
  11705. (setq end (save-excursion
  11706. (outline-next-heading)
  11707. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11708. (point)))
  11709. (if (and (save-excursion
  11710. (re-search-forward
  11711. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11712. (not (save-excursion (re-search-forward
  11713. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11714. (org-update-checkbox-count)
  11715. (if (and l2 (> l2 l1))
  11716. (progn
  11717. (goto-char end)
  11718. (org-update-parent-todo-statistics))
  11719. (goto-char pos)
  11720. (beginning-of-line 1)
  11721. (while (re-search-forward
  11722. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11723. (point-at-eol) t)
  11724. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11725. (goto-char pos)
  11726. (move-marker pos nil)))))
  11727. (defvar org-entry-property-inherited-from) ;; defined below
  11728. (defun org-update-parent-todo-statistics ()
  11729. "Update any statistics cookie in the parent of the current headline.
  11730. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11731. the entire subtree and this will travel up the hierarchy and update
  11732. statistics everywhere."
  11733. (let* ((prop (save-excursion (org-up-heading-safe)
  11734. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11735. (recursive (or (not org-hierarchical-todo-statistics)
  11736. (and prop (string-match "\\<recursive\\>" prop))))
  11737. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11738. 0))
  11739. (first t)
  11740. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11741. level ltoggle l1 new ndel
  11742. (cnt-all 0) (cnt-done 0) is-percent kwd
  11743. checkbox-beg cookie-present)
  11744. (catch 'exit
  11745. (save-excursion
  11746. (beginning-of-line 1)
  11747. (setq ltoggle (funcall outline-level))
  11748. ;; Three situations are to consider:
  11749. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11750. ;; to the top-level ancestor on the headline;
  11751. ;; 2. If parent has "recursive" property, repeat up to the
  11752. ;; headline setting that property, taking inheritance into
  11753. ;; account;
  11754. ;; 3. Else, move up to direct parent and proceed only once.
  11755. (while (and (setq level (org-up-heading-safe))
  11756. (or recursive first)
  11757. (>= (point) lim))
  11758. (setq first nil cookie-present nil)
  11759. (unless (and level
  11760. (not (string-match
  11761. "\\<checkbox\\>"
  11762. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11763. "")))))
  11764. (throw 'exit nil))
  11765. (while (re-search-forward box-re (point-at-eol) t)
  11766. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11767. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11768. (save-match-data
  11769. (unless (outline-next-heading) (throw 'exit nil))
  11770. (while (and (looking-at org-complex-heading-regexp)
  11771. (> (setq l1 (length (match-string 1))) level))
  11772. (setq kwd (and (or recursive (= l1 ltoggle))
  11773. (match-string 2)))
  11774. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11775. (and (eq org-provide-todo-statistics t)
  11776. (or (member kwd org-done-keywords)))
  11777. (and (listp org-provide-todo-statistics)
  11778. (stringp (car org-provide-todo-statistics))
  11779. (or (member kwd org-provide-todo-statistics)
  11780. (member kwd org-done-keywords)))
  11781. (and (listp org-provide-todo-statistics)
  11782. (listp (car org-provide-todo-statistics))
  11783. (or (member kwd (car org-provide-todo-statistics))
  11784. (and (member kwd org-done-keywords)
  11785. (member kwd (cadr org-provide-todo-statistics))))))
  11786. (setq cnt-all (1+ cnt-all))
  11787. (and (eq org-provide-todo-statistics t)
  11788. kwd
  11789. (setq cnt-all (1+ cnt-all))))
  11790. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11791. (member kwd org-done-keywords))
  11792. (and (listp org-provide-todo-statistics)
  11793. (listp (car org-provide-todo-statistics))
  11794. (member kwd org-done-keywords)
  11795. (member kwd (cadr org-provide-todo-statistics)))
  11796. (and (listp org-provide-todo-statistics)
  11797. (stringp (car org-provide-todo-statistics))
  11798. (member kwd org-done-keywords)))
  11799. (setq cnt-done (1+ cnt-done)))
  11800. (outline-next-heading)))
  11801. (setq new
  11802. (if is-percent
  11803. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11804. (max 1 cnt-all)))
  11805. (format "[%d/%d]" cnt-done cnt-all))
  11806. ndel (- (match-end 0) checkbox-beg))
  11807. (goto-char checkbox-beg)
  11808. (insert new)
  11809. (delete-region (point) (+ (point) ndel))
  11810. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11811. (when cookie-present
  11812. (run-hook-with-args 'org-after-todo-statistics-hook
  11813. cnt-done (- cnt-all cnt-done))))))
  11814. (run-hooks 'org-todo-statistics-hook)))
  11815. (defvar org-after-todo-statistics-hook nil
  11816. "Hook that is called after a TODO statistics cookie has been updated.
  11817. Each function is called with two arguments: the number of not-done entries
  11818. and the number of done entries.
  11819. For example, the following function, when added to this hook, will switch
  11820. an entry to DONE when all children are done, and back to TODO when new
  11821. entries are set to a TODO status. Note that this hook is only called
  11822. when there is a statistics cookie in the headline!
  11823. (defun org-summary-todo (n-done n-not-done)
  11824. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11825. (let (org-log-done org-log-states) ; turn off logging
  11826. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11827. ")
  11828. (defvar org-todo-statistics-hook nil
  11829. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11830. This hook runs even if there is no statistics cookie present, in which case
  11831. `org-after-todo-statistics-hook' would not run.")
  11832. (defun org-todo-trigger-tag-changes (state)
  11833. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11834. (let ((l org-todo-state-tags-triggers)
  11835. changes)
  11836. (when (or (not state) (equal state ""))
  11837. (setq changes (append changes (cdr (assoc "" l)))))
  11838. (when (and (stringp state) (> (length state) 0))
  11839. (setq changes (append changes (cdr (assoc state l)))))
  11840. (when (member state org-not-done-keywords)
  11841. (setq changes (append changes (cdr (assq 'todo l)))))
  11842. (when (member state org-done-keywords)
  11843. (setq changes (append changes (cdr (assq 'done l)))))
  11844. (dolist (c changes)
  11845. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11846. (defun org-local-logging (value)
  11847. "Get logging settings from a property VALUE."
  11848. ;; Directly set the variables, they are already local.
  11849. (setq org-log-done nil
  11850. org-log-repeat nil
  11851. org-todo-log-states nil)
  11852. (dolist (w (org-split-string value))
  11853. (let (a)
  11854. (cond
  11855. ((setq a (assoc w org-startup-options))
  11856. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11857. (set (nth 1 a) (nth 2 a))))
  11858. ((setq a (org-extract-log-state-settings w))
  11859. (and (member (car a) org-todo-keywords-1)
  11860. (push a org-todo-log-states)))))))
  11861. (defun org-get-todo-sequence-head (kwd)
  11862. "Return the head of the TODO sequence to which KWD belongs.
  11863. If KWD is not set, check if there is a text property remembering the
  11864. right sequence."
  11865. (let (p)
  11866. (cond
  11867. ((not kwd)
  11868. (or (get-text-property (point-at-bol) 'org-todo-head)
  11869. (progn
  11870. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11871. nil (point-at-eol)))
  11872. (get-text-property p 'org-todo-head))))
  11873. ((not (member kwd org-todo-keywords-1))
  11874. (car org-todo-keywords-1))
  11875. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11876. (defun org-fast-todo-selection ()
  11877. "Fast TODO keyword selection with single keys.
  11878. Returns the new TODO keyword, or nil if no state change should occur."
  11879. (let* ((fulltable org-todo-key-alist)
  11880. (done-keywords org-done-keywords) ;; needed for the faces.
  11881. (maxlen (apply 'max (mapcar
  11882. (lambda (x)
  11883. (if (stringp (car x)) (string-width (car x)) 0))
  11884. fulltable)))
  11885. (expert nil)
  11886. (fwidth (+ maxlen 3 1 3))
  11887. (ncol (/ (- (window-width) 4) fwidth))
  11888. tg cnt e c tbl
  11889. groups ingroup)
  11890. (save-excursion
  11891. (save-window-excursion
  11892. (if expert
  11893. (set-buffer (get-buffer-create " *Org todo*"))
  11894. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11895. (erase-buffer)
  11896. (setq-local org-done-keywords done-keywords)
  11897. (setq tbl fulltable cnt 0)
  11898. (while (setq e (pop tbl))
  11899. (cond
  11900. ((equal e '(:startgroup))
  11901. (push '() groups) (setq ingroup t)
  11902. (unless (= cnt 0)
  11903. (setq cnt 0)
  11904. (insert "\n"))
  11905. (insert "{ "))
  11906. ((equal e '(:endgroup))
  11907. (setq ingroup nil cnt 0)
  11908. (insert "}\n"))
  11909. ((equal e '(:newline))
  11910. (unless (= cnt 0)
  11911. (setq cnt 0)
  11912. (insert "\n")
  11913. (setq e (car tbl))
  11914. (while (equal (car tbl) '(:newline))
  11915. (insert "\n")
  11916. (setq tbl (cdr tbl)))))
  11917. (t
  11918. (setq tg (car e) c (cdr e))
  11919. (when ingroup (push tg (car groups)))
  11920. (setq tg (org-add-props tg nil 'face
  11921. (org-get-todo-face tg)))
  11922. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11923. (insert "[" c "] " tg (make-string
  11924. (- fwidth 4 (length tg)) ?\ ))
  11925. (when (= (setq cnt (1+ cnt)) ncol)
  11926. (insert "\n")
  11927. (when ingroup (insert " "))
  11928. (setq cnt 0)))))
  11929. (insert "\n")
  11930. (goto-char (point-min))
  11931. (unless expert (org-fit-window-to-buffer))
  11932. (message "[a-z..]:Set [SPC]:clear")
  11933. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11934. (cond
  11935. ((or (= c ?\C-g)
  11936. (and (= c ?q) (not (rassoc c fulltable))))
  11937. (setq quit-flag t))
  11938. ((= c ?\ ) nil)
  11939. ((setq e (rassoc c fulltable) tg (car e))
  11940. tg)
  11941. (t (setq quit-flag t)))))))
  11942. (defun org-entry-is-todo-p ()
  11943. (member (org-get-todo-state) org-not-done-keywords))
  11944. (defun org-entry-is-done-p ()
  11945. (member (org-get-todo-state) org-done-keywords))
  11946. (defun org-get-todo-state ()
  11947. "Return the TODO keyword of the current subtree."
  11948. (save-excursion
  11949. (org-back-to-heading t)
  11950. (and (looking-at org-todo-line-regexp)
  11951. (match-end 2)
  11952. (match-string 2))))
  11953. (defun org-at-date-range-p (&optional inactive-ok)
  11954. "Non-nil if point is inside a date range.
  11955. When optional argument INACTIVE-OK is non-nil, also consider
  11956. inactive time ranges.
  11957. When this function returns a non-nil value, match data is set
  11958. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11959. on INACTIVE-OK."
  11960. (interactive)
  11961. (save-excursion
  11962. (catch 'exit
  11963. (let ((pos (point)))
  11964. (skip-chars-backward "^[<\r\n")
  11965. (skip-chars-backward "<[")
  11966. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11967. (>= (match-end 0) pos)
  11968. (throw 'exit t))
  11969. (skip-chars-backward "^<[\r\n")
  11970. (skip-chars-backward "<[")
  11971. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11972. (>= (match-end 0) pos)
  11973. (throw 'exit t)))
  11974. nil)))
  11975. (defun org-get-repeat (&optional tagline)
  11976. "Check if there is a deadline/schedule with repeater in this entry."
  11977. (save-match-data
  11978. (save-excursion
  11979. (org-back-to-heading t)
  11980. (and (re-search-forward (if tagline
  11981. (concat tagline "\\s-*" org-repeat-re)
  11982. org-repeat-re)
  11983. (org-entry-end-position) t)
  11984. (match-string-no-properties 1)))))
  11985. (defvar org-last-changed-timestamp)
  11986. (defvar org-last-inserted-timestamp)
  11987. (defvar org-log-post-message)
  11988. (defvar org-log-note-purpose)
  11989. (defvar org-log-note-how nil)
  11990. (defvar org-log-note-extra)
  11991. (defun org-auto-repeat-maybe (done-word)
  11992. "Check if the current headline contains a repeated time-stamp.
  11993. If yes, set TODO state back to what it was and change the base date
  11994. of repeating deadline/scheduled time stamps to new date.
  11995. This function is run automatically after each state change to a DONE state."
  11996. (let* ((repeat (org-get-repeat))
  11997. (aa (assoc org-last-state org-todo-kwd-alist))
  11998. (interpret (nth 1 aa))
  11999. (head (nth 2 aa))
  12000. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  12001. (msg "Entry repeats: ")
  12002. (org-log-done nil)
  12003. (org-todo-log-states nil))
  12004. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  12005. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  12006. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  12007. org-todo-repeat-to-state)))
  12008. (unless (and to-state (member to-state org-todo-keywords-1))
  12009. (setq to-state (if (eq interpret 'type) org-last-state head)))
  12010. (org-todo to-state))
  12011. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  12012. (org-entry-put nil "LAST_REPEAT" (format-time-string
  12013. (org-time-stamp-format t t))))
  12014. (when org-log-repeat
  12015. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  12016. (memq 'org-add-log-note post-command-hook))
  12017. ;; We are already setup for some record.
  12018. (when (eq org-log-repeat 'note)
  12019. ;; Make sure we take a note, not only a time stamp.
  12020. (setq org-log-note-how 'note))
  12021. ;; Set up for taking a record.
  12022. (org-add-log-setup 'state
  12023. (or done-word (car org-done-keywords))
  12024. org-last-state
  12025. org-log-repeat)))
  12026. (org-back-to-heading t)
  12027. (org-add-planning-info nil nil 'closed)
  12028. (let ((end (save-excursion (outline-next-heading) (point))))
  12029. (while (re-search-forward org-ts-regexp end t)
  12030. (when (save-match-data
  12031. (or (org-at-planning-p)
  12032. (org-at-property-p)
  12033. (eq (org-element-type (save-excursion
  12034. (backward-char)
  12035. (org-element-context)))
  12036. 'timestamp)))
  12037. (let ((type (cond ((match-end 1) org-scheduled-string)
  12038. ((match-end 3) org-deadline-string)
  12039. (t "Plain:")))
  12040. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  12041. (cond
  12042. ((not
  12043. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12044. ;; Time-stamps without a repeater are usually skipped.
  12045. ;; However, a SCHEDULED time-stamp without one is
  12046. ;; removed, as it is considered as no longer relevant.
  12047. (when (equal type org-scheduled-string)
  12048. (org-remove-timestamp-with-keyword type)))
  12049. (t
  12050. (let ((n (string-to-number (match-string 2 ts)))
  12051. (what (match-string 3 ts)))
  12052. (when (equal what "w") (setq n (* n 7) what "d"))
  12053. (when (and (equal what "h")
  12054. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12055. ts)))
  12056. (user-error
  12057. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12058. has been set"
  12059. n))
  12060. ;; Preparation, see if we need to modify the start
  12061. ;; date for the change.
  12062. (when (match-end 1)
  12063. (let ((time (save-match-data (org-time-string-to-time ts))))
  12064. (cond
  12065. ((equal (match-string 1 ts) ".")
  12066. ;; Shift starting date to today
  12067. (org-timestamp-change
  12068. (- (org-today) (time-to-days time))
  12069. 'day))
  12070. ((equal (match-string 1 ts) "+")
  12071. (let ((nshiftmax 10)
  12072. (nshift 0))
  12073. (while (or (= nshift 0)
  12074. (not (time-less-p (current-time) time)))
  12075. (when (= (cl-incf nshift) nshiftmax)
  12076. (or (y-or-n-p
  12077. (format "%d repeater intervals were not \
  12078. enough to shift date past today. Continue? "
  12079. nshift))
  12080. (user-error "Abort")))
  12081. (org-timestamp-change n (cdr (assoc what whata)))
  12082. (org-at-timestamp-p t)
  12083. (setq ts (match-string 1))
  12084. (setq time
  12085. (save-match-data
  12086. (org-time-string-to-time ts)))))
  12087. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12088. ;; Rematch, so that we have everything in
  12089. ;; place for the real shift.
  12090. (org-at-timestamp-p t)
  12091. (setq ts (match-string 1))
  12092. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12093. ts)))))
  12094. (save-excursion
  12095. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12096. (setq msg
  12097. (concat
  12098. msg type " " org-last-changed-timestamp " ")))))))))
  12099. (setq org-log-post-message msg)
  12100. (message "%s" msg))))
  12101. (defun org-show-todo-tree (arg)
  12102. "Make a compact tree which shows all headlines marked with TODO.
  12103. The tree will show the lines where the regexp matches, and all higher
  12104. headlines above the match.
  12105. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12106. With a numeric prefix N, construct a sparse tree for the Nth element
  12107. of `org-todo-keywords-1'."
  12108. (interactive "P")
  12109. (let ((case-fold-search nil)
  12110. (kwd-re
  12111. (cond ((null arg) org-not-done-regexp)
  12112. ((equal arg '(4))
  12113. (let ((kwd
  12114. (completing-read "Keyword (or KWD1|KWD2|...): "
  12115. (mapcar #'list org-todo-keywords-1))))
  12116. (concat "\\("
  12117. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12118. "\\)\\>")))
  12119. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12120. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12121. org-todo-keywords-1)))
  12122. (t (user-error "Invalid prefix argument: %s" arg)))))
  12123. (message "%d TODO entries found"
  12124. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12125. (defun org-deadline (arg &optional time)
  12126. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12127. With one universal prefix argument, remove any deadline from the item.
  12128. With two universal prefix arguments, prompt for a warning delay.
  12129. With argument TIME, set the deadline at the corresponding date. TIME
  12130. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12131. (interactive "P")
  12132. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12133. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12134. 'region-start-level 'region))
  12135. org-loop-over-headlines-in-active-region)
  12136. (org-map-entries
  12137. `(org-deadline ',arg ,time)
  12138. org-loop-over-headlines-in-active-region
  12139. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12140. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12141. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12142. (repeater (and old-date
  12143. (string-match
  12144. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12145. old-date)
  12146. (match-string 1 old-date))))
  12147. (cond
  12148. ((equal arg '(4))
  12149. (when (and old-date org-log-redeadline)
  12150. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12151. (org-remove-timestamp-with-keyword org-deadline-string)
  12152. (message "Item no longer has a deadline."))
  12153. ((equal arg '(16))
  12154. (save-excursion
  12155. (org-back-to-heading t)
  12156. (if (re-search-forward
  12157. org-deadline-time-regexp
  12158. (save-excursion (outline-next-heading) (point)) t)
  12159. (let* ((rpl0 (match-string 1))
  12160. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12161. (replace-match
  12162. (concat org-deadline-string
  12163. " <" rpl
  12164. (format " -%dd"
  12165. (abs
  12166. (- (time-to-days
  12167. (save-match-data
  12168. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12169. (time-to-days old-date-time))))
  12170. ">") t t))
  12171. (user-error "No deadline information to update"))))
  12172. (t
  12173. (org-add-planning-info 'deadline time 'closed)
  12174. (when (and old-date
  12175. org-log-redeadline
  12176. (not (equal old-date org-last-inserted-timestamp)))
  12177. (org-add-log-setup
  12178. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12179. (when repeater
  12180. (save-excursion
  12181. (org-back-to-heading t)
  12182. (when (re-search-forward (concat org-deadline-string " "
  12183. org-last-inserted-timestamp)
  12184. (save-excursion
  12185. (outline-next-heading) (point)) t)
  12186. (goto-char (1- (match-end 0)))
  12187. (insert " " repeater)
  12188. (setq org-last-inserted-timestamp
  12189. (concat (substring org-last-inserted-timestamp 0 -1)
  12190. " " repeater
  12191. (substring org-last-inserted-timestamp -1))))))
  12192. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12193. (defun org-schedule (arg &optional time)
  12194. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12195. With one universal prefix argument, remove any scheduling date from the item.
  12196. With two universal prefix arguments, prompt for a delay cookie.
  12197. With argument TIME, scheduled at the corresponding date. TIME can
  12198. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12199. (interactive "P")
  12200. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12201. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12202. 'region-start-level 'region))
  12203. org-loop-over-headlines-in-active-region)
  12204. (org-map-entries
  12205. `(org-schedule ',arg ,time)
  12206. org-loop-over-headlines-in-active-region
  12207. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12208. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12209. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12210. (repeater (and old-date
  12211. (string-match
  12212. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12213. old-date)
  12214. (match-string 1 old-date))))
  12215. (cond
  12216. ((equal arg '(4))
  12217. (progn
  12218. (when (and old-date org-log-reschedule)
  12219. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12220. (org-remove-timestamp-with-keyword org-scheduled-string)
  12221. (message "Item is no longer scheduled.")))
  12222. ((equal arg '(16))
  12223. (save-excursion
  12224. (org-back-to-heading t)
  12225. (if (re-search-forward
  12226. org-scheduled-time-regexp
  12227. (save-excursion (outline-next-heading) (point)) t)
  12228. (let* ((rpl0 (match-string 1))
  12229. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12230. (replace-match
  12231. (concat org-scheduled-string
  12232. " <" rpl
  12233. (format " -%dd"
  12234. (abs
  12235. (- (time-to-days
  12236. (save-match-data
  12237. (org-read-date nil t nil "Delay until" old-date-time)))
  12238. (time-to-days old-date-time))))
  12239. ">") t t))
  12240. (user-error "No scheduled information to update"))))
  12241. (t
  12242. (org-add-planning-info 'scheduled time 'closed)
  12243. (when (and old-date
  12244. org-log-reschedule
  12245. (not (equal old-date org-last-inserted-timestamp)))
  12246. (org-add-log-setup
  12247. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12248. (when repeater
  12249. (save-excursion
  12250. (org-back-to-heading t)
  12251. (when (re-search-forward (concat org-scheduled-string " "
  12252. org-last-inserted-timestamp)
  12253. (save-excursion
  12254. (outline-next-heading) (point)) t)
  12255. (goto-char (1- (match-end 0)))
  12256. (insert " " repeater)
  12257. (setq org-last-inserted-timestamp
  12258. (concat (substring org-last-inserted-timestamp 0 -1)
  12259. " " repeater
  12260. (substring org-last-inserted-timestamp -1))))))
  12261. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12262. (defun org-get-scheduled-time (pom &optional inherit)
  12263. "Get the scheduled time as a time tuple, of a format suitable
  12264. for calling org-schedule with, or if there is no scheduling,
  12265. returns nil."
  12266. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12267. (when time
  12268. (apply 'encode-time (org-parse-time-string time)))))
  12269. (defun org-get-deadline-time (pom &optional inherit)
  12270. "Get the deadline as a time tuple, of a format suitable for
  12271. calling org-deadline with, or if there is no scheduling, returns
  12272. nil."
  12273. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12274. (when time
  12275. (apply 'encode-time (org-parse-time-string time)))))
  12276. (defun org-remove-timestamp-with-keyword (keyword)
  12277. "Remove all time stamps with KEYWORD in the current entry."
  12278. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12279. beg)
  12280. (save-excursion
  12281. (org-back-to-heading t)
  12282. (setq beg (point))
  12283. (outline-next-heading)
  12284. (while (re-search-backward re beg t)
  12285. (replace-match "")
  12286. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12287. (equal (char-before) ?\ ))
  12288. (backward-delete-char 1)
  12289. (when (string-match "^[ \t]*$" (buffer-substring
  12290. (point-at-bol) (point-at-eol)))
  12291. (delete-region (point-at-bol)
  12292. (min (point-max) (1+ (point-at-eol))))))))))
  12293. (defvar org-time-was-given) ; dynamically scoped parameter
  12294. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12295. (defun org-at-planning-p ()
  12296. "Non-nil when point is on a planning info line."
  12297. ;; This is as accurate and faster than `org-element-at-point' since
  12298. ;; planning info location is fixed in the section.
  12299. (org-with-wide-buffer
  12300. (beginning-of-line)
  12301. (and (looking-at-p org-planning-line-re)
  12302. (eq (point)
  12303. (ignore-errors
  12304. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12305. (org-back-to-heading t)
  12306. (org-with-limited-levels (org-back-to-heading t)))
  12307. (line-beginning-position 2))))))
  12308. (defun org-add-planning-info (what &optional time &rest remove)
  12309. "Insert new timestamp with keyword in the planning line.
  12310. WHAT indicates what kind of time stamp to add. It is a symbol
  12311. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12312. the time to use. If none is given, the user is prompted for
  12313. a date. REMOVE indicates what kind of entries to remove. An old
  12314. WHAT entry will also be removed."
  12315. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12316. (catch 'exit
  12317. (when (and (memq what '(scheduled deadline))
  12318. (or (not time)
  12319. (and (stringp time)
  12320. (string-match "^[-+]+[0-9]" time))))
  12321. ;; Try to get a default date/time from existing timestamp
  12322. (save-excursion
  12323. (org-back-to-heading t)
  12324. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12325. (when (re-search-forward (if (eq what 'scheduled)
  12326. org-scheduled-time-regexp
  12327. org-deadline-time-regexp)
  12328. end t)
  12329. (setq ts (match-string 1)
  12330. default-time (apply 'encode-time (org-parse-time-string ts))
  12331. default-input (and ts (org-get-compact-tod ts)))))))
  12332. (when what
  12333. (setq time
  12334. (if (stringp time)
  12335. ;; This is a string (relative or absolute), set
  12336. ;; proper date.
  12337. (apply #'encode-time
  12338. (org-read-date-analyze
  12339. time default-time (decode-time default-time)))
  12340. ;; If necessary, get the time from the user
  12341. (or time (org-read-date nil 'to-time nil nil
  12342. default-time default-input)))))
  12343. (org-with-wide-buffer
  12344. (org-back-to-heading t)
  12345. (forward-line)
  12346. (unless (bolp) (insert "\n"))
  12347. (cond ((looking-at-p org-planning-line-re)
  12348. ;; Move to current indentation.
  12349. (skip-chars-forward " \t")
  12350. ;; Check if we have to remove something.
  12351. (dolist (type (if what (cons what remove) remove))
  12352. (save-excursion
  12353. (when (re-search-forward
  12354. (cl-case type
  12355. (closed org-closed-time-regexp)
  12356. (deadline org-deadline-time-regexp)
  12357. (scheduled org-scheduled-time-regexp)
  12358. (otherwise
  12359. (error "Invalid planning type: %s" type)))
  12360. (line-end-position) t)
  12361. ;; Delete until next keyword or end of line.
  12362. (delete-region
  12363. (match-beginning 0)
  12364. (if (re-search-forward org-keyword-time-not-clock-regexp
  12365. (line-end-position)
  12366. t)
  12367. (match-beginning 0)
  12368. (line-end-position))))))
  12369. ;; If there is nothing more to add and no more keyword
  12370. ;; is left, remove the line completely.
  12371. (if (and (looking-at-p "[ \t]*$") (not what))
  12372. (delete-region (line-beginning-position)
  12373. (line-beginning-position 2))
  12374. ;; If we removed last keyword, do not leave trailing
  12375. ;; white space at the end of line.
  12376. (let ((p (point)))
  12377. (save-excursion
  12378. (end-of-line)
  12379. (unless (= (skip-chars-backward " \t" p) 0)
  12380. (delete-region (point) (line-end-position)))))))
  12381. ((not what) (throw 'exit nil)) ; Nothing to do.
  12382. (t (insert-before-markers "\n")
  12383. (backward-char 1)
  12384. (when org-adapt-indentation
  12385. (indent-to-column (1+ (org-outline-level))))))
  12386. (when what
  12387. ;; Insert planning keyword.
  12388. (insert (cl-case what
  12389. (closed org-closed-string)
  12390. (deadline org-deadline-string)
  12391. (scheduled org-scheduled-string)
  12392. (otherwise (error "Invalid planning type: %s" what)))
  12393. " ")
  12394. ;; Insert associated timestamp.
  12395. (let ((ts (org-insert-time-stamp
  12396. time
  12397. (or org-time-was-given
  12398. (and (eq what 'closed) org-log-done-with-time))
  12399. (eq what 'closed)
  12400. nil nil (list org-end-time-was-given))))
  12401. (unless (eolp) (insert " "))
  12402. ts))))))
  12403. (defvar org-log-note-marker (make-marker)
  12404. "Marker pointing at the entry where the note is to be inserted.")
  12405. (defvar org-log-note-purpose nil)
  12406. (defvar org-log-note-state nil)
  12407. (defvar org-log-note-previous-state nil)
  12408. (defvar org-log-note-extra nil)
  12409. (defvar org-log-note-window-configuration nil)
  12410. (defvar org-log-note-return-to (make-marker))
  12411. (defvar org-log-note-effective-time nil
  12412. "Remembered current time so that dynamically scoped
  12413. `org-extend-today-until' affects timestamps in state change log")
  12414. (defvar org-log-post-message nil
  12415. "Message to be displayed after a log note has been stored.
  12416. The auto-repeater uses this.")
  12417. (defun org-add-note ()
  12418. "Add a note to the current entry.
  12419. This is done in the same way as adding a state change note."
  12420. (interactive)
  12421. (org-add-log-setup 'note))
  12422. (defun org-log-beginning (&optional create)
  12423. "Return expected start of log notes in current entry.
  12424. When optional argument CREATE is non-nil, the function creates
  12425. a drawer to store notes, if necessary. Returned position ignores
  12426. narrowing."
  12427. (org-with-wide-buffer
  12428. (let ((drawer (org-log-into-drawer)))
  12429. (cond
  12430. (drawer
  12431. (org-end-of-meta-data)
  12432. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12433. (end (if (org-at-heading-p) (point)
  12434. (save-excursion (outline-next-heading) (point))))
  12435. (case-fold-search t))
  12436. (catch 'exit
  12437. ;; Try to find existing drawer.
  12438. (while (re-search-forward regexp end t)
  12439. (let ((element (org-element-at-point)))
  12440. (when (eq (org-element-type element) 'drawer)
  12441. (let ((cend (org-element-property :contents-end element)))
  12442. (when (and (not org-log-states-order-reversed) cend)
  12443. (goto-char cend)))
  12444. (throw 'exit nil))))
  12445. ;; No drawer found. Create one, if permitted.
  12446. (when create
  12447. (unless (bolp) (insert "\n"))
  12448. (let ((beg (point)))
  12449. (insert ":" drawer ":\n:END:\n")
  12450. (org-indent-region beg (point)))
  12451. (end-of-line -1)))))
  12452. (t
  12453. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12454. (skip-chars-forward " \t\n")
  12455. (beginning-of-line)
  12456. (unless org-log-states-order-reversed
  12457. (org-skip-over-state-notes)
  12458. (skip-chars-backward " \t\n")
  12459. (forward-line)))))
  12460. (if (bolp) (point) (line-beginning-position 2))))
  12461. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12462. "Set up the post command hook to take a note.
  12463. If this is about to TODO state change, the new state is expected in STATE.
  12464. HOW is an indicator what kind of note should be created.
  12465. EXTRA is additional text that will be inserted into the notes buffer."
  12466. (move-marker org-log-note-marker (point))
  12467. (setq org-log-note-purpose purpose
  12468. org-log-note-state state
  12469. org-log-note-previous-state prev-state
  12470. org-log-note-how how
  12471. org-log-note-extra extra
  12472. org-log-note-effective-time (org-current-effective-time))
  12473. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12474. (defun org-skip-over-state-notes ()
  12475. "Skip past the list of State notes in an entry."
  12476. (when (ignore-errors (goto-char (org-in-item-p)))
  12477. (let* ((struct (org-list-struct))
  12478. (prevs (org-list-prevs-alist struct))
  12479. (regexp
  12480. (concat "[ \t]*- +"
  12481. (replace-regexp-in-string
  12482. " +" " +"
  12483. (org-replace-escapes
  12484. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12485. `(("%d" . ,org-ts-regexp-inactive)
  12486. ("%D" . ,org-ts-regexp)
  12487. ("%s" . "\"\\S-+\"")
  12488. ("%S" . "\"\\S-+\"")
  12489. ("%t" . ,org-ts-regexp-inactive)
  12490. ("%T" . ,org-ts-regexp)
  12491. ("%u" . ".*?")
  12492. ("%U" . ".*?")))))))
  12493. (while (looking-at-p regexp)
  12494. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12495. (org-list-get-item-end (point) struct)))))))
  12496. (defun org-add-log-note (&optional _purpose)
  12497. "Pop up a window for taking a note, and add this note later."
  12498. (remove-hook 'post-command-hook 'org-add-log-note)
  12499. (setq org-log-note-window-configuration (current-window-configuration))
  12500. (delete-other-windows)
  12501. (move-marker org-log-note-return-to (point))
  12502. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12503. (goto-char org-log-note-marker)
  12504. (org-switch-to-buffer-other-window "*Org Note*")
  12505. (erase-buffer)
  12506. (if (memq org-log-note-how '(time state))
  12507. (let (current-prefix-arg) (org-store-log-note))
  12508. (let ((org-inhibit-startup t)) (org-mode))
  12509. (insert (format "# Insert note for %s.
  12510. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12511. (cond
  12512. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12513. ((eq org-log-note-purpose 'done) "closed todo item")
  12514. ((eq org-log-note-purpose 'state)
  12515. (format "state change from \"%s\" to \"%s\""
  12516. (or org-log-note-previous-state "")
  12517. (or org-log-note-state "")))
  12518. ((eq org-log-note-purpose 'reschedule)
  12519. "rescheduling")
  12520. ((eq org-log-note-purpose 'delschedule)
  12521. "no longer scheduled")
  12522. ((eq org-log-note-purpose 'redeadline)
  12523. "changing deadline")
  12524. ((eq org-log-note-purpose 'deldeadline)
  12525. "removing deadline")
  12526. ((eq org-log-note-purpose 'refile)
  12527. "refiling")
  12528. ((eq org-log-note-purpose 'note)
  12529. "this entry")
  12530. (t (error "This should not happen")))))
  12531. (when org-log-note-extra (insert org-log-note-extra))
  12532. (setq-local org-finish-function 'org-store-log-note)
  12533. (run-hooks 'org-log-buffer-setup-hook)))
  12534. (defvar org-note-abort nil) ; dynamically scoped
  12535. (defun org-store-log-note ()
  12536. "Finish taking a log note, and insert it to where it belongs."
  12537. (let ((txt (prog1 (buffer-string)
  12538. (kill-buffer)))
  12539. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12540. lines)
  12541. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12542. (setq txt (replace-match "" t t txt)))
  12543. (when (string-match "\\s-+\\'" txt)
  12544. (setq txt (replace-match "" t t txt)))
  12545. (setq lines (org-split-string txt "\n"))
  12546. (when (org-string-nw-p note)
  12547. (setq note
  12548. (org-replace-escapes
  12549. note
  12550. (list (cons "%u" (user-login-name))
  12551. (cons "%U" user-full-name)
  12552. (cons "%t" (format-time-string
  12553. (org-time-stamp-format 'long 'inactive)
  12554. org-log-note-effective-time))
  12555. (cons "%T" (format-time-string
  12556. (org-time-stamp-format 'long nil)
  12557. org-log-note-effective-time))
  12558. (cons "%d" (format-time-string
  12559. (org-time-stamp-format nil 'inactive)
  12560. org-log-note-effective-time))
  12561. (cons "%D" (format-time-string
  12562. (org-time-stamp-format nil nil)
  12563. org-log-note-effective-time))
  12564. (cons "%s" (cond
  12565. ((not org-log-note-state) "")
  12566. ((string-match-p org-ts-regexp
  12567. org-log-note-state)
  12568. (format "\"[%s]\""
  12569. (substring org-log-note-state 1 -1)))
  12570. (t (format "\"%s\"" org-log-note-state))))
  12571. (cons "%S"
  12572. (cond
  12573. ((not org-log-note-previous-state) "")
  12574. ((string-match-p org-ts-regexp
  12575. org-log-note-previous-state)
  12576. (format "\"[%s]\""
  12577. (substring
  12578. org-log-note-previous-state 1 -1)))
  12579. (t (format "\"%s\""
  12580. org-log-note-previous-state)))))))
  12581. (when lines (setq note (concat note " \\\\")))
  12582. (push note lines))
  12583. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12584. (with-current-buffer (marker-buffer org-log-note-marker)
  12585. (org-with-wide-buffer
  12586. ;; Find location for the new note.
  12587. (goto-char org-log-note-marker)
  12588. (set-marker org-log-note-marker nil)
  12589. (goto-char (org-log-beginning t))
  12590. ;; Make sure point is at the beginning of an empty line.
  12591. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12592. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12593. ;; In an existing list, add a new item at the top level.
  12594. ;; Otherwise, indent line like a regular one.
  12595. (let ((itemp (org-in-item-p)))
  12596. (if itemp
  12597. (indent-line-to
  12598. (let ((struct (save-excursion
  12599. (goto-char itemp) (org-list-struct))))
  12600. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12601. (org-indent-line)))
  12602. (insert (org-list-bullet-string "-") (pop lines))
  12603. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12604. (dolist (line lines)
  12605. (insert "\n")
  12606. (indent-line-to ind)
  12607. (insert line)))
  12608. (message "Note stored")
  12609. (org-back-to-heading t)
  12610. (org-cycle-hide-drawers 'children))
  12611. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12612. ;; from within `org-add-log-note' because `buffer-undo-list'
  12613. ;; is then modified outside of `org-with-remote-undo'.
  12614. (when (eq this-command 'org-agenda-todo)
  12615. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12616. ;; Don't add undo information when called from `org-agenda-todo'.
  12617. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12618. (set-window-configuration org-log-note-window-configuration)
  12619. (with-current-buffer (marker-buffer org-log-note-return-to)
  12620. (goto-char org-log-note-return-to))
  12621. (move-marker org-log-note-return-to nil)
  12622. (when org-log-post-message (message "%s" org-log-post-message))))
  12623. (defun org-remove-empty-drawer-at (pos)
  12624. "Remove an empty drawer at position POS.
  12625. POS may also be a marker."
  12626. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12627. (org-with-wide-buffer
  12628. (goto-char pos)
  12629. (let ((drawer (org-element-at-point)))
  12630. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12631. (not (org-element-property :contents-begin drawer)))
  12632. (delete-region (org-element-property :begin drawer)
  12633. (progn (goto-char (org-element-property :end drawer))
  12634. (skip-chars-backward " \r\t\n")
  12635. (forward-line)
  12636. (point))))))))
  12637. (defvar org-ts-type nil)
  12638. (defun org-sparse-tree (&optional arg type)
  12639. "Create a sparse tree, prompt for the details.
  12640. This command can create sparse trees. You first need to select the type
  12641. of match used to create the tree:
  12642. t Show all TODO entries.
  12643. T Show entries with a specific TODO keyword.
  12644. m Show entries selected by a tags/property match.
  12645. p Enter a property name and its value (both with completion on existing
  12646. names/values) and show entries with that property.
  12647. r Show entries matching a regular expression (`/' can be used as well).
  12648. b Show deadlines and scheduled items before a date.
  12649. a Show deadlines and scheduled items after a date.
  12650. d Show deadlines due within `org-deadline-warning-days'.
  12651. D Show deadlines and scheduled items between a date range."
  12652. (interactive "P")
  12653. (setq type (or type org-sparse-tree-default-date-type))
  12654. (setq org-ts-type type)
  12655. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12656. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12657. \[c]ycle through date types: %s"
  12658. (cl-case type
  12659. (all "all timestamps")
  12660. (scheduled "only scheduled")
  12661. (deadline "only deadline")
  12662. (active "only active timestamps")
  12663. (inactive "only inactive timestamps")
  12664. (closed "with a closed time-stamp")
  12665. (otherwise "scheduled/deadline")))
  12666. (let ((answer (read-char-exclusive)))
  12667. (cl-case answer
  12668. (?c
  12669. (org-sparse-tree
  12670. arg
  12671. (cadr
  12672. (memq type '(nil all scheduled deadline active inactive closed)))))
  12673. (?d (call-interactively 'org-check-deadlines))
  12674. (?b (call-interactively 'org-check-before-date))
  12675. (?a (call-interactively 'org-check-after-date))
  12676. (?D (call-interactively 'org-check-dates-range))
  12677. (?t (call-interactively 'org-show-todo-tree))
  12678. (?T (org-show-todo-tree '(4)))
  12679. (?m (call-interactively 'org-match-sparse-tree))
  12680. ((?p ?P)
  12681. (let* ((kwd (completing-read
  12682. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12683. (value (completing-read
  12684. "Value: " (mapcar #'list (org-property-values kwd)))))
  12685. (unless (string-match "\\`{.*}\\'" value)
  12686. (setq value (concat "\"" value "\"")))
  12687. (org-match-sparse-tree arg (concat kwd "=" value))))
  12688. ((?r ?R ?/) (call-interactively 'org-occur))
  12689. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12690. (defvar-local org-occur-highlights nil
  12691. "List of overlays used for occur matches.")
  12692. (defvar-local org-occur-parameters nil
  12693. "Parameters of the active org-occur calls.
  12694. This is a list, each call to org-occur pushes as cons cell,
  12695. containing the regular expression and the callback, onto the list.
  12696. The list can contain several entries if `org-occur' has been called
  12697. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12698. will only contain one set of parameters. When the highlights are
  12699. removed (for example with `C-c C-c', or with the next edit (depending
  12700. on `org-remove-highlights-with-change'), this variable is emptied
  12701. as well.")
  12702. (defun org-occur (regexp &optional keep-previous callback)
  12703. "Make a compact tree which shows all matches of REGEXP.
  12704. The tree will show the lines where the regexp matches, and any other context
  12705. defined in `org-show-context-detail', which see.
  12706. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12707. done by a previous call to `org-occur' will be kept, to allow stacking of
  12708. calls to this command.
  12709. Optional argument CALLBACK can be a function of no argument. In this case,
  12710. it is called with point at the end of the match, match data being set
  12711. accordingly. Current match is shown only if the return value is non-nil.
  12712. The function must neither move point nor alter narrowing."
  12713. (interactive "sRegexp: \nP")
  12714. (when (equal regexp "")
  12715. (user-error "Regexp cannot be empty"))
  12716. (unless keep-previous
  12717. (org-remove-occur-highlights nil nil t))
  12718. (push (cons regexp callback) org-occur-parameters)
  12719. (let ((cnt 0))
  12720. (save-excursion
  12721. (goto-char (point-min))
  12722. (when (or (not keep-previous) ; do not want to keep
  12723. (not org-occur-highlights)) ; no previous matches
  12724. ;; hide everything
  12725. (org-overview))
  12726. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12727. (isearch-no-upper-case-p regexp t)
  12728. org-occur-case-fold-search)))
  12729. (while (re-search-forward regexp nil t)
  12730. (when (or (not callback)
  12731. (save-match-data (funcall callback)))
  12732. (setq cnt (1+ cnt))
  12733. (when org-highlight-sparse-tree-matches
  12734. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12735. (org-show-context 'occur-tree)))))
  12736. (when org-remove-highlights-with-change
  12737. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12738. nil 'local))
  12739. (unless org-sparse-tree-open-archived-trees
  12740. (org-hide-archived-subtrees (point-min) (point-max)))
  12741. (run-hooks 'org-occur-hook)
  12742. (when (called-interactively-p 'interactive)
  12743. (message "%d match(es) for regexp %s" cnt regexp))
  12744. cnt))
  12745. (defun org-occur-next-match (&optional n _reset)
  12746. "Function for `next-error-function' to find sparse tree matches.
  12747. N is the number of matches to move, when negative move backwards.
  12748. This function always goes back to the starting point when no
  12749. match is found."
  12750. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12751. (search-func (if (< n 0)
  12752. 'previous-single-char-property-change
  12753. 'next-single-char-property-change))
  12754. (n (abs n))
  12755. (pos (point))
  12756. p1)
  12757. (catch 'exit
  12758. (while (setq p1 (funcall search-func (point) 'org-type))
  12759. (when (equal p1 limit)
  12760. (goto-char pos)
  12761. (user-error "No more matches"))
  12762. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12763. (setq n (1- n))
  12764. (when (= n 0)
  12765. (goto-char p1)
  12766. (throw 'exit (point))))
  12767. (goto-char p1))
  12768. (goto-char p1)
  12769. (user-error "No more matches"))))
  12770. (defun org-show-context (&optional key)
  12771. "Make sure point and context are visible.
  12772. Optional argument KEY, when non-nil, is a symbol. See
  12773. `org-show-context-detail' for allowed values and how much is to
  12774. be shown."
  12775. (org-show-set-visibility
  12776. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12777. ((cdr (assq key org-show-context-detail)))
  12778. (t (cdr (assq 'default org-show-context-detail))))))
  12779. (defun org-show-set-visibility (detail)
  12780. "Set visibility around point according to DETAIL.
  12781. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12782. `tree', `canonical' or t. See `org-show-context-detail' for more
  12783. information."
  12784. ;; Show current heading and possibly its entry, following headline
  12785. ;; or all children.
  12786. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12787. (org-flag-heading nil)
  12788. (org-show-entry)
  12789. ;; If point is hidden within a drawer or a block, make sure to
  12790. ;; expose it.
  12791. (dolist (o (overlays-at (point)))
  12792. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12793. (delete-overlay o)))
  12794. (unless (org-before-first-heading-p)
  12795. (org-with-limited-levels
  12796. (cl-case detail
  12797. ((tree canonical t) (org-show-children))
  12798. ((nil minimal ancestors))
  12799. (t (save-excursion
  12800. (outline-next-heading)
  12801. (org-flag-heading nil)))))))
  12802. ;; Show all siblings.
  12803. (when (eq detail 'lineage) (org-show-siblings))
  12804. ;; Show ancestors, possibly with their children.
  12805. (when (memq detail '(ancestors lineage tree canonical t))
  12806. (save-excursion
  12807. (while (org-up-heading-safe)
  12808. (org-flag-heading nil)
  12809. (when (memq detail '(canonical t)) (org-show-entry))
  12810. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12811. (defvar org-reveal-start-hook nil
  12812. "Hook run before revealing a location.")
  12813. (defun org-reveal (&optional siblings)
  12814. "Show current entry, hierarchy above it, and the following headline.
  12815. This can be used to show a consistent set of context around
  12816. locations exposed with `org-show-context'.
  12817. With optional argument SIBLINGS, on each level of the hierarchy all
  12818. siblings are shown. This repairs the tree structure to what it would
  12819. look like when opened with hierarchical calls to `org-cycle'.
  12820. With a \\[universal-argument] \\[universal-argument] prefix, \
  12821. go to the parent and show the entire tree."
  12822. (interactive "P")
  12823. (run-hooks 'org-reveal-start-hook)
  12824. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12825. ((equal siblings '(16))
  12826. (save-excursion
  12827. (when (org-up-heading-safe)
  12828. (org-show-subtree)
  12829. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12830. (t (org-show-set-visibility 'lineage))))
  12831. (defun org-highlight-new-match (beg end)
  12832. "Highlight from BEG to END and mark the highlight is an occur headline."
  12833. (let ((ov (make-overlay beg end)))
  12834. (overlay-put ov 'face 'secondary-selection)
  12835. (overlay-put ov 'org-type 'org-occur)
  12836. (push ov org-occur-highlights)))
  12837. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12838. "Remove the occur highlights from the buffer.
  12839. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12840. from the `before-change-functions' in the current buffer."
  12841. (interactive)
  12842. (unless org-inhibit-highlight-removal
  12843. (mapc #'delete-overlay org-occur-highlights)
  12844. (setq org-occur-highlights nil)
  12845. (setq org-occur-parameters nil)
  12846. (unless noremove
  12847. (remove-hook 'before-change-functions
  12848. 'org-remove-occur-highlights 'local))))
  12849. ;;;; Priorities
  12850. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12851. "Regular expression matching the priority indicator.")
  12852. (defvar org-remove-priority-next-time nil)
  12853. (defun org-priority-up ()
  12854. "Increase the priority of the current item."
  12855. (interactive)
  12856. (org-priority 'up))
  12857. (defun org-priority-down ()
  12858. "Decrease the priority of the current item."
  12859. (interactive)
  12860. (org-priority 'down))
  12861. (defun org-priority (&optional action _show)
  12862. "Change the priority of an item.
  12863. ACTION can be `set', `up', `down', or a character."
  12864. (interactive "P")
  12865. (if (equal action '(4))
  12866. (org-show-priority)
  12867. (unless org-enable-priority-commands
  12868. (user-error "Priority commands are disabled"))
  12869. (setq action (or action 'set))
  12870. (let (current new news have remove)
  12871. (save-excursion
  12872. (org-back-to-heading t)
  12873. (when (looking-at org-priority-regexp)
  12874. (setq current (string-to-char (match-string 2))
  12875. have t))
  12876. (cond
  12877. ((eq action 'remove)
  12878. (setq remove t new ?\ ))
  12879. ((or (eq action 'set)
  12880. (integerp action))
  12881. (if (not (eq action 'set))
  12882. (setq new action)
  12883. (message "Priority %c-%c, SPC to remove: "
  12884. org-highest-priority org-lowest-priority)
  12885. (save-match-data
  12886. (setq new (read-char-exclusive))))
  12887. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12888. (= (upcase org-lowest-priority) org-lowest-priority))
  12889. (setq new (upcase new)))
  12890. (cond ((equal new ?\ ) (setq remove t))
  12891. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12892. (user-error "Priority must be between `%c' and `%c'"
  12893. org-highest-priority org-lowest-priority))))
  12894. ((eq action 'up)
  12895. (setq new (if have
  12896. (1- current) ; normal cycling
  12897. ;; last priority was empty
  12898. (if (eq last-command this-command)
  12899. org-lowest-priority ; wrap around empty to lowest
  12900. ;; default
  12901. (if org-priority-start-cycle-with-default
  12902. org-default-priority
  12903. (1- org-default-priority))))))
  12904. ((eq action 'down)
  12905. (setq new (if have
  12906. (1+ current) ; normal cycling
  12907. ;; last priority was empty
  12908. (if (eq last-command this-command)
  12909. org-highest-priority ; wrap around empty to highest
  12910. ;; default
  12911. (if org-priority-start-cycle-with-default
  12912. org-default-priority
  12913. (1+ org-default-priority))))))
  12914. (t (user-error "Invalid action")))
  12915. (when (or (< (upcase new) org-highest-priority)
  12916. (> (upcase new) org-lowest-priority))
  12917. (if (and (memq action '(up down))
  12918. (not have) (not (eq last-command this-command)))
  12919. ;; `new' is from default priority
  12920. (error
  12921. "The default can not be set, see `org-default-priority' why")
  12922. ;; normal cycling: `new' is beyond highest/lowest priority
  12923. ;; and is wrapped around to the empty priority
  12924. (setq remove t)))
  12925. (setq news (format "%c" new))
  12926. (if have
  12927. (if remove
  12928. (replace-match "" t t nil 1)
  12929. (replace-match news t t nil 2))
  12930. (if remove
  12931. (user-error "No priority cookie found in line")
  12932. (let ((case-fold-search nil))
  12933. (looking-at org-todo-line-regexp))
  12934. (if (match-end 2)
  12935. (progn
  12936. (goto-char (match-end 2))
  12937. (insert " [#" news "]"))
  12938. (goto-char (match-beginning 3))
  12939. (insert "[#" news "] "))))
  12940. (org-set-tags nil 'align))
  12941. (if remove
  12942. (message "Priority removed")
  12943. (message "Priority of current item set to %s" news)))))
  12944. (defun org-show-priority ()
  12945. "Show the priority of the current item.
  12946. This priority is composed of the main priority given with the [#A] cookies,
  12947. and by additional input from the age of a schedules or deadline entry."
  12948. (interactive)
  12949. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12950. (org-get-at-bol 'priority)
  12951. (save-excursion
  12952. (save-match-data
  12953. (beginning-of-line)
  12954. (and (looking-at org-heading-regexp)
  12955. (org-get-priority (match-string 0))))))))
  12956. (message "Priority is %d" (if pri pri -1000))))
  12957. (defun org-get-priority (s)
  12958. "Find priority cookie and return priority."
  12959. (save-match-data
  12960. (if (functionp org-get-priority-function)
  12961. (funcall org-get-priority-function)
  12962. (if (not (string-match org-priority-regexp s))
  12963. (* 1000 (- org-lowest-priority org-default-priority))
  12964. (* 1000 (- org-lowest-priority
  12965. (string-to-char (match-string 2 s))))))))
  12966. ;;;; Tags
  12967. (defvar org-agenda-archives-mode)
  12968. (defvar org-map-continue-from nil
  12969. "Position from where mapping should continue.
  12970. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12971. (defvar org-scanner-tags nil
  12972. "The current tag list while the tags scanner is running.")
  12973. (defvar org-trust-scanner-tags nil
  12974. "Should `org-get-tags-at' use the tags for the scanner.
  12975. This is for internal dynamical scoping only.
  12976. When this is non-nil, the function `org-get-tags-at' will return the value
  12977. of `org-scanner-tags' instead of building the list by itself. This
  12978. can lead to large speed-ups when the tags scanner is used in a file with
  12979. many entries, and when the list of tags is retrieved, for example to
  12980. obtain a list of properties. Building the tags list for each entry in such
  12981. a file becomes an N^2 operation - but with this variable set, it scales
  12982. as N.")
  12983. (defvar org--matcher-tags-todo-only nil)
  12984. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12985. "Scan headline tags with inheritance and produce output ACTION.
  12986. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12987. or `agenda' to produce an entry list for an agenda view. It can also be
  12988. a Lisp form or a function that should be called at each matched headline, in
  12989. this case the return value is a list of all return values from these calls.
  12990. MATCHER is a function accepting three arguments, returning
  12991. a non-nil value whenever a given set of tags qualifies a headline
  12992. for inclusion. See `org-make-tags-matcher' for more information.
  12993. As a special case, it can also be set to t (respectively nil) in
  12994. order to match all (respectively none) headline.
  12995. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12996. keyword are included in the output.
  12997. START-LEVEL can be a string with asterisks, reducing the scope to
  12998. headlines matching this string."
  12999. (require 'org-agenda)
  13000. (let* ((re (concat "^"
  13001. (if start-level
  13002. ;; Get the correct level to match
  13003. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  13004. org-outline-regexp)
  13005. " *\\(\\<\\("
  13006. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  13007. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  13008. (props (list 'face 'default
  13009. 'done-face 'org-agenda-done
  13010. 'undone-face 'default
  13011. 'mouse-face 'highlight
  13012. 'org-not-done-regexp org-not-done-regexp
  13013. 'org-todo-regexp org-todo-regexp
  13014. 'org-complex-heading-regexp org-complex-heading-regexp
  13015. 'help-echo
  13016. (format "mouse-2 or RET jump to org file %s"
  13017. (abbreviate-file-name
  13018. (or (buffer-file-name (buffer-base-buffer))
  13019. (buffer-name (buffer-base-buffer)))))))
  13020. (org-map-continue-from nil)
  13021. lspos tags tags-list
  13022. (tags-alist (list (cons 0 org-file-tags)))
  13023. (llast 0) rtn rtn1 level category i txt
  13024. todo marker entry priority
  13025. ts-date ts-date-type ts-date-pair)
  13026. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  13027. (setq action (list 'lambda nil action)))
  13028. (save-excursion
  13029. (goto-char (point-min))
  13030. (when (eq action 'sparse-tree)
  13031. (org-overview)
  13032. (org-remove-occur-highlights))
  13033. (while (let (case-fold-search)
  13034. (re-search-forward re nil t))
  13035. (setq org-map-continue-from nil)
  13036. (catch :skip
  13037. (setq todo
  13038. ;; TODO: is the 1-2 difference a bug?
  13039. (when (match-end 1) (match-string-no-properties 2))
  13040. tags (when (match-end 4) (match-string-no-properties 4)))
  13041. (goto-char (setq lspos (match-beginning 0)))
  13042. (setq level (org-reduced-level (org-outline-level))
  13043. category (org-get-category))
  13044. (when (eq action 'agenda)
  13045. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13046. ts-date (car ts-date-pair)
  13047. ts-date-type (cdr ts-date-pair)))
  13048. (setq i llast llast level)
  13049. ;; remove tag lists from same and sublevels
  13050. (while (>= i level)
  13051. (when (setq entry (assoc i tags-alist))
  13052. (setq tags-alist (delete entry tags-alist)))
  13053. (setq i (1- i)))
  13054. ;; add the next tags
  13055. (when tags
  13056. (setq tags (org-split-string tags ":")
  13057. tags-alist
  13058. (cons (cons level tags) tags-alist)))
  13059. ;; compile tags for current headline
  13060. (setq tags-list
  13061. (if org-use-tag-inheritance
  13062. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13063. tags)
  13064. org-scanner-tags tags-list)
  13065. (when org-use-tag-inheritance
  13066. (setcdr (car tags-alist)
  13067. (mapcar (lambda (x)
  13068. (setq x (copy-sequence x))
  13069. (org-add-prop-inherited x))
  13070. (cdar tags-alist))))
  13071. (when (and tags org-use-tag-inheritance
  13072. (or (not (eq t org-use-tag-inheritance))
  13073. org-tags-exclude-from-inheritance))
  13074. ;; Selective inheritance, remove uninherited ones.
  13075. (setcdr (car tags-alist)
  13076. (org-remove-uninherited-tags (cdar tags-alist))))
  13077. (when (and
  13078. ;; eval matcher only when the todo condition is OK
  13079. (and (or (not todo-only) (member todo org-not-done-keywords))
  13080. (if (functionp matcher)
  13081. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13082. (funcall matcher todo tags-list level))
  13083. matcher))
  13084. ;; Call the skipper, but return t if it does not
  13085. ;; skip, so that the `and' form continues evaluating.
  13086. (progn
  13087. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13088. t)
  13089. ;; Check if timestamps are deselecting this entry
  13090. (or (not todo-only)
  13091. (and (member todo org-not-done-keywords)
  13092. (or (not org-agenda-tags-todo-honor-ignore-options)
  13093. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13094. ;; select this headline
  13095. (cond
  13096. ((eq action 'sparse-tree)
  13097. (and org-highlight-sparse-tree-matches
  13098. (org-get-heading) (match-end 0)
  13099. (org-highlight-new-match
  13100. (match-beginning 1) (match-end 1)))
  13101. (org-show-context 'tags-tree))
  13102. ((eq action 'agenda)
  13103. (setq txt (org-agenda-format-item
  13104. ""
  13105. (concat
  13106. (if (eq org-tags-match-list-sublevels 'indented)
  13107. (make-string (1- level) ?.) "")
  13108. (org-get-heading))
  13109. (make-string level ?\s)
  13110. category
  13111. tags-list)
  13112. priority (org-get-priority txt))
  13113. (goto-char lspos)
  13114. (setq marker (org-agenda-new-marker))
  13115. (org-add-props txt props
  13116. 'org-marker marker 'org-hd-marker marker 'org-category category
  13117. 'todo-state todo
  13118. 'ts-date ts-date
  13119. 'priority priority
  13120. 'type (concat "tagsmatch" ts-date-type))
  13121. (push txt rtn))
  13122. ((functionp action)
  13123. (setq org-map-continue-from nil)
  13124. (save-excursion
  13125. (setq rtn1 (funcall action))
  13126. (push rtn1 rtn)))
  13127. (t (user-error "Invalid action")))
  13128. ;; if we are to skip sublevels, jump to end of subtree
  13129. (unless org-tags-match-list-sublevels
  13130. (org-end-of-subtree t)
  13131. (backward-char 1))))
  13132. ;; Get the correct position from where to continue
  13133. (if org-map-continue-from
  13134. (goto-char org-map-continue-from)
  13135. (and (= (point) lspos) (end-of-line 1)))))
  13136. (when (and (eq action 'sparse-tree)
  13137. (not org-sparse-tree-open-archived-trees))
  13138. (org-hide-archived-subtrees (point-min) (point-max)))
  13139. (nreverse rtn)))
  13140. (defun org-remove-uninherited-tags (tags)
  13141. "Remove all tags that are not inherited from the list TAGS."
  13142. (cond
  13143. ((eq org-use-tag-inheritance t)
  13144. (if org-tags-exclude-from-inheritance
  13145. (org-delete-all org-tags-exclude-from-inheritance tags)
  13146. tags))
  13147. ((not org-use-tag-inheritance) nil)
  13148. ((stringp org-use-tag-inheritance)
  13149. (delq nil (mapcar
  13150. (lambda (x)
  13151. (if (and (string-match org-use-tag-inheritance x)
  13152. (not (member x org-tags-exclude-from-inheritance)))
  13153. x nil))
  13154. tags)))
  13155. ((listp org-use-tag-inheritance)
  13156. (delq nil (mapcar
  13157. (lambda (x)
  13158. (if (member x org-use-tag-inheritance) x nil))
  13159. tags)))))
  13160. (defun org-match-sparse-tree (&optional todo-only match)
  13161. "Create a sparse tree according to tags string MATCH.
  13162. MATCH is a string with match syntax. It can contain a selection
  13163. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13164. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13165. those. See the manual for details.
  13166. If optional argument TODO-ONLY is non-nil, only select lines that
  13167. are also TODO tasks."
  13168. (interactive "P")
  13169. (org-agenda-prepare-buffers (list (current-buffer)))
  13170. (let ((org--matcher-tags-todo-only todo-only))
  13171. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13172. org--matcher-tags-todo-only)))
  13173. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13174. (defvar org-cached-props nil)
  13175. (defun org-cached-entry-get (pom property)
  13176. (if (or (eq t org-use-property-inheritance)
  13177. (and (stringp org-use-property-inheritance)
  13178. (let ((case-fold-search t))
  13179. (string-match-p org-use-property-inheritance property)))
  13180. (and (listp org-use-property-inheritance)
  13181. (member-ignore-case property org-use-property-inheritance)))
  13182. ;; Caching is not possible, check it directly.
  13183. (org-entry-get pom property 'inherit)
  13184. ;; Get all properties, so we can do complicated checks easily.
  13185. (cdr (assoc-string property
  13186. (or org-cached-props
  13187. (setq org-cached-props (org-entry-properties pom)))
  13188. t))))
  13189. (defun org-global-tags-completion-table (&optional files)
  13190. "Return the list of all tags in all agenda buffer/files.
  13191. Optional FILES argument is a list of files which can be used
  13192. instead of the agenda files."
  13193. (save-excursion
  13194. (org-uniquify
  13195. (delq nil
  13196. (apply #'append
  13197. (mapcar
  13198. (lambda (file)
  13199. (set-buffer (find-file-noselect file))
  13200. (mapcar (lambda (x)
  13201. (and (stringp (car-safe x))
  13202. (list (car-safe x))))
  13203. (or org-current-tag-alist (org-get-buffer-tags))))
  13204. (if (car-safe files) files
  13205. (org-agenda-files))))))))
  13206. (defun org-make-tags-matcher (match)
  13207. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13208. Returns a cons of the selection string MATCH and a function
  13209. implementing the matcher.
  13210. The matcher is to be called at an Org entry, with point on the
  13211. headline, and returns non-nil if the entry matches the selection
  13212. string MATCH. It must be called with three arguments: the TODO
  13213. keyword at the entry (or nil if none), the list of all tags at
  13214. the entry including inherited ones and the reduced level of the
  13215. headline. Additionally, the category of the entry, if any, must
  13216. be specified as the text property `org-category' on the headline.
  13217. This function sets the variable `org--matcher-tags-todo-only' to
  13218. a non-nil value if the matcher restricts matching to TODO
  13219. entries, otherwise it is not touched.
  13220. See also `org-scan-tags'."
  13221. (unless match
  13222. ;; Get a new match request, with completion against the global
  13223. ;; tags table and the local tags in current buffer.
  13224. (let ((org-last-tags-completion-table
  13225. (org-uniquify
  13226. (delq nil (append (org-get-buffer-tags)
  13227. (org-global-tags-completion-table))))))
  13228. (setq match
  13229. (completing-read
  13230. "Match: "
  13231. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13232. (let ((match0 match)
  13233. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13234. (start 0)
  13235. tagsmatch todomatch tagsmatcher todomatcher)
  13236. ;; Expand group tags.
  13237. (setq match (org-tags-expand match))
  13238. ;; Check if there is a TODO part of this match, which would be the
  13239. ;; part after a "/". To make sure that this slash is not part of
  13240. ;; a property value to be matched against, we also check that
  13241. ;; there is no / after that slash. First, find the last slash.
  13242. (let ((s 0))
  13243. (while (string-match "/+" match s)
  13244. (setq start (match-beginning 0))
  13245. (setq s (match-end 0))))
  13246. (if (and (string-match "/+" match start)
  13247. (not (string-match-p "\"" match start)))
  13248. ;; Match contains also a TODO-matching request.
  13249. (progn
  13250. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13251. (setq todomatch (substring match (match-end 0)))
  13252. (when (string-prefix-p "!" todomatch)
  13253. (setq org--matcher-tags-todo-only t)
  13254. (setq todomatch (substring todomatch 1)))
  13255. (when (string-match "\\`\\s-*\\'" todomatch)
  13256. (setq todomatch nil)))
  13257. ;; Only matching tags.
  13258. (setq tagsmatch match)
  13259. (setq todomatch nil))
  13260. ;; Make the tags matcher.
  13261. (when (org-string-nw-p tagsmatch)
  13262. (let ((orlist nil)
  13263. (orterms (org-split-string tagsmatch "|"))
  13264. term)
  13265. (while (setq term (pop orterms))
  13266. (while (and (equal (substring term -1) "\\") orterms)
  13267. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13268. (while (string-match re term)
  13269. (let* ((rest (substring term (match-end 0)))
  13270. (minus (and (match-end 1)
  13271. (equal (match-string 1 term) "-")))
  13272. (tag (save-match-data
  13273. (replace-regexp-in-string
  13274. "\\\\-" "-" (match-string 2 term))))
  13275. (regexp (eq (string-to-char tag) ?{))
  13276. (levelp (match-end 4))
  13277. (propp (match-end 5))
  13278. (mm
  13279. (cond
  13280. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13281. (levelp
  13282. `(,(org-op-to-function (match-string 3 term))
  13283. level
  13284. ,(string-to-number (match-string 4 term))))
  13285. (propp
  13286. (let* ((gv (pcase (upcase (match-string 5 term))
  13287. ("CATEGORY"
  13288. '(get-text-property (point) 'org-category))
  13289. ("TODO" 'todo)
  13290. (p `(org-cached-entry-get nil ,p))))
  13291. (pv (match-string 7 term))
  13292. (regexp (eq (string-to-char pv) ?{))
  13293. (strp (eq (string-to-char pv) ?\"))
  13294. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13295. (po (org-op-to-function (match-string 6 term)
  13296. (if timep 'time strp))))
  13297. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13298. (when timep (setq pv (org-matcher-time pv)))
  13299. (cond ((and regexp (eq po 'org<>))
  13300. `(not (string-match ,pv (or ,gv ""))))
  13301. (regexp `(string-match ,pv (or ,gv "")))
  13302. (strp `(,po (or ,gv "") ,pv))
  13303. (t
  13304. `(,po
  13305. (string-to-number (or ,gv ""))
  13306. ,(string-to-number pv))))))
  13307. (t `(member ,tag tags-list)))))
  13308. (push (if minus `(not ,mm) mm) tagsmatcher)
  13309. (setq term rest)))
  13310. (push `(and ,@tagsmatcher) orlist)
  13311. (setq tagsmatcher nil))
  13312. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13313. ;; Make the TODO matcher.
  13314. (when (org-string-nw-p todomatch)
  13315. (let ((orlist nil))
  13316. (dolist (term (org-split-string todomatch "|"))
  13317. (while (string-match re term)
  13318. (let* ((minus (and (match-end 1)
  13319. (equal (match-string 1 term) "-")))
  13320. (kwd (match-string 2 term))
  13321. (regexp (eq (string-to-char kwd) ?{))
  13322. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13323. `(equal todo ,kwd))))
  13324. (push (if minus `(not ,mm) mm) todomatcher))
  13325. (setq term (substring term (match-end 0))))
  13326. (push (if (> (length todomatcher) 1)
  13327. (cons 'and todomatcher)
  13328. (car todomatcher))
  13329. orlist)
  13330. (setq todomatcher nil))
  13331. (setq todomatcher (cons 'or orlist))))
  13332. ;; Return the string and function of the matcher. If no
  13333. ;; tags-specific or todo-specific matcher exists, match
  13334. ;; everything.
  13335. (let ((matcher (if (and tagsmatcher todomatcher)
  13336. `(and ,tagsmatcher ,todomatcher)
  13337. (or tagsmatcher todomatcher t))))
  13338. (when org--matcher-tags-todo-only
  13339. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13340. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13341. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13342. "Expand group tags in MATCH.
  13343. This replaces every group tag in MATCH with a regexp tag search.
  13344. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13345. will be replaced like this:
  13346. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13347. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13348. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13349. Replacing by a regexp preserves the structure of the match.
  13350. E.g., this expansion
  13351. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13352. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13353. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13354. A group tag in MATCH can contain regular expressions of its own.
  13355. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13356. will be replaced like this:
  13357. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13358. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13359. assumed to be a single group tag, and the function will return
  13360. the list of tags in this group.
  13361. When DOWNCASE is non-nil, expand downcased TAGS."
  13362. (if org-group-tags
  13363. (let* ((case-fold-search t)
  13364. (stable org-mode-syntax-table)
  13365. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13366. (taggroups (if downcased
  13367. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13368. taggroups)
  13369. taggroups))
  13370. (taggroups-keys (mapcar #'car taggroups))
  13371. (return-match (if downcased (downcase match) match))
  13372. (count 0)
  13373. (work-already-expanded tags-already-expanded)
  13374. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13375. ;; @ and _ are allowed as word-components in tags.
  13376. (modify-syntax-entry ?@ "w" stable)
  13377. (modify-syntax-entry ?_ "w" stable)
  13378. ;; Temporarily replace regexp-expressions in the match-expression.
  13379. (while (string-match "{.+?}" return-match)
  13380. (cl-incf count)
  13381. (push (match-string 0 return-match) regexps-in-match)
  13382. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13383. (while (and taggroups-keys
  13384. (with-syntax-table stable
  13385. (string-match
  13386. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13387. (regexp-opt taggroups-keys) "\\>\\)")
  13388. return-match)))
  13389. (let* ((dir (match-string 1 return-match))
  13390. (tag (match-string 2 return-match))
  13391. (tag (if downcased (downcase tag) tag)))
  13392. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13393. (member tag work-already-expanded))
  13394. (setq tags-in-group (assoc tag taggroups))
  13395. (push tag work-already-expanded)
  13396. ;; Recursively expand each tag in the group, if the tag hasn't
  13397. ;; already been expanded. Restore the match-data after all recursive calls.
  13398. (save-match-data
  13399. (let (tags-expanded)
  13400. (dolist (x (cdr tags-in-group))
  13401. (if (and (member x taggroups-keys)
  13402. (not (member x work-already-expanded)))
  13403. (setq tags-expanded
  13404. (delete-dups
  13405. (append
  13406. (org-tags-expand x t downcased
  13407. work-already-expanded)
  13408. tags-expanded)))
  13409. (setq tags-expanded
  13410. (append (list x) tags-expanded)))
  13411. (setq work-already-expanded
  13412. (delete-dups
  13413. (append tags-expanded
  13414. work-already-expanded))))
  13415. (setq tags-in-group
  13416. (delete-dups (cons (car tags-in-group)
  13417. tags-expanded)))))
  13418. ;; Filter tag-regexps from tags.
  13419. (setq regexp-in-group-escaped
  13420. (delq nil (mapcar (lambda (x)
  13421. (if (stringp x)
  13422. (and (equal "{" (substring x 0 1))
  13423. (equal "}" (substring x -1))
  13424. x)
  13425. x))
  13426. tags-in-group))
  13427. regexp-in-group
  13428. (mapcar (lambda (x)
  13429. (substring x 1 -1))
  13430. regexp-in-group-escaped)
  13431. tags-in-group
  13432. (delq nil (mapcar (lambda (x)
  13433. (if (stringp x)
  13434. (and (not (equal "{" (substring x 0 1)))
  13435. (not (equal "}" (substring x -1)))
  13436. x)
  13437. x))
  13438. tags-in-group)))
  13439. ;; If single-as-list, do no more in the while-loop.
  13440. (if (not single-as-list)
  13441. (progn
  13442. (when regexp-in-group
  13443. (setq regexp-in-group
  13444. (concat "\\|"
  13445. (mapconcat 'identity regexp-in-group
  13446. "\\|"))))
  13447. (setq tags-in-group
  13448. (concat dir
  13449. "{\\<"
  13450. (regexp-opt tags-in-group)
  13451. "\\>"
  13452. regexp-in-group
  13453. "}"))
  13454. (when (stringp tags-in-group)
  13455. (org-add-props tags-in-group '(grouptag t)))
  13456. (setq return-match
  13457. (replace-match tags-in-group t t return-match)))
  13458. (setq tags-in-group
  13459. (append regexp-in-group-escaped tags-in-group))))
  13460. (setq taggroups-keys (delete tag taggroups-keys))))
  13461. ;; Add the regular expressions back into the match-expression again.
  13462. (while regexps-in-match
  13463. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13464. (pop regexps-in-match)
  13465. return-match t t))
  13466. (cl-decf count))
  13467. (if single-as-list
  13468. (if tags-in-group tags-in-group (list return-match))
  13469. return-match))
  13470. (if single-as-list
  13471. (list (if downcased (downcase match) match))
  13472. match)))
  13473. (defun org-op-to-function (op &optional stringp)
  13474. "Turn an operator into the appropriate function."
  13475. (setq op
  13476. (cond
  13477. ((equal op "<" ) '(< string< org-time<))
  13478. ((equal op ">" ) '(> org-string> org-time>))
  13479. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13480. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13481. ((member op '("=" "==")) '(= string= org-time=))
  13482. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13483. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13484. (defun org<> (a b) (not (= a b)))
  13485. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13486. (defun org-string>= (a b) (not (string< a b)))
  13487. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13488. (defun org-string<> (a b) (not (string= a b)))
  13489. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13490. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13491. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13492. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13493. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13494. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13495. (defun org-2ft (s)
  13496. "Convert S to a floating point time.
  13497. If S is already a number, just return it. If it is a string, parse
  13498. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13499. (cond
  13500. ((numberp s) s)
  13501. ((stringp s)
  13502. (condition-case nil
  13503. (float-time (apply 'encode-time (org-parse-time-string s)))
  13504. (error 0.)))
  13505. (t 0.)))
  13506. (defun org-time-today ()
  13507. "Time in seconds today at 0:00.
  13508. Returns the float number of seconds since the beginning of the
  13509. epoch to the beginning of today (00:00)."
  13510. (float-time (apply 'encode-time
  13511. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13512. (defun org-matcher-time (s)
  13513. "Interpret a time comparison value."
  13514. (save-match-data
  13515. (cond
  13516. ((string= s "<now>") (float-time))
  13517. ((string= s "<today>") (org-time-today))
  13518. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13519. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13520. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13521. (+ (org-time-today)
  13522. (* (string-to-number (match-string 1 s))
  13523. (cdr (assoc (match-string 2 s)
  13524. '(("d" . 86400.0) ("w" . 604800.0)
  13525. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13526. (t (org-2ft s)))))
  13527. (defun org-match-any-p (re list)
  13528. "Does re match any element of list?"
  13529. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13530. (delq nil list))
  13531. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13532. (defvar org-tags-overlay (make-overlay 1 1))
  13533. (delete-overlay org-tags-overlay)
  13534. (defun org-get-local-tags-at (&optional pos)
  13535. "Get a list of tags defined in the current headline."
  13536. (org-get-tags-at pos 'local))
  13537. (defun org-get-local-tags ()
  13538. "Get a list of tags defined in the current headline."
  13539. (org-get-tags-at nil 'local))
  13540. (defun org-get-tags-at (&optional pos local)
  13541. "Get a list of all headline tags applicable at POS.
  13542. POS defaults to point. If tags are inherited, the list contains
  13543. the targets in the same sequence as the headlines appear, i.e.
  13544. the tags of the current headline come last.
  13545. When LOCAL is non-nil, only return tags from the current headline,
  13546. ignore inherited ones."
  13547. (interactive)
  13548. (if (and org-trust-scanner-tags
  13549. (or (not pos) (equal pos (point)))
  13550. (not local))
  13551. org-scanner-tags
  13552. (let (tags ltags lastpos parent)
  13553. (save-excursion
  13554. (save-restriction
  13555. (widen)
  13556. (goto-char (or pos (point)))
  13557. (save-match-data
  13558. (catch 'done
  13559. (condition-case nil
  13560. (progn
  13561. (org-back-to-heading t)
  13562. (while (not (equal lastpos (point)))
  13563. (setq lastpos (point))
  13564. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13565. (setq ltags (org-split-string
  13566. (match-string-no-properties 1) ":"))
  13567. (when parent
  13568. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13569. (setq tags (append
  13570. (if parent
  13571. (org-remove-uninherited-tags ltags)
  13572. ltags)
  13573. tags)))
  13574. (or org-use-tag-inheritance (throw 'done t))
  13575. (when local (throw 'done t))
  13576. (or (org-up-heading-safe) (error nil))
  13577. (setq parent t)))
  13578. (error nil)))))
  13579. (if local
  13580. tags
  13581. (reverse (delete-dups
  13582. (reverse (append
  13583. (org-remove-uninherited-tags
  13584. org-file-tags)
  13585. tags)))))))))
  13586. (defun org-add-prop-inherited (s)
  13587. (add-text-properties 0 (length s) '(inherited t) s)
  13588. s)
  13589. (defun org-toggle-tag (tag &optional onoff)
  13590. "Toggle the tag TAG for the current line.
  13591. If ONOFF is `on' or `off', don't toggle but set to this state."
  13592. (let (res current)
  13593. (save-excursion
  13594. (org-back-to-heading t)
  13595. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13596. (point-at-eol) t)
  13597. (progn
  13598. (setq current (match-string 1))
  13599. (replace-match ""))
  13600. (setq current ""))
  13601. (setq current (nreverse (org-split-string current ":")))
  13602. (cond
  13603. ((eq onoff 'on)
  13604. (setq res t)
  13605. (or (member tag current) (push tag current)))
  13606. ((eq onoff 'off)
  13607. (or (not (member tag current)) (setq current (delete tag current))))
  13608. (t (if (member tag current)
  13609. (setq current (delete tag current))
  13610. (setq res t)
  13611. (push tag current))))
  13612. (end-of-line 1)
  13613. (if current
  13614. (progn
  13615. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13616. (org-set-tags nil t))
  13617. (delete-horizontal-space))
  13618. (run-hooks 'org-after-tags-change-hook))
  13619. res))
  13620. (defun org--align-tags-here (to-col)
  13621. "Align tags on the current headline to TO-COL.
  13622. Assume point is on a headline."
  13623. (let ((pos (point)))
  13624. (beginning-of-line)
  13625. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13626. (>= pos (match-beginning 2)))
  13627. ;; No tags or point within tags: do not align.
  13628. (goto-char pos)
  13629. (goto-char (match-beginning 1))
  13630. (let ((shift (max (- (if (>= to-col 0) to-col
  13631. (- (abs to-col) (string-width (match-string 2))))
  13632. (current-column))
  13633. 1)))
  13634. (replace-match (make-string shift ?\s) nil nil nil 1)
  13635. ;; Preserve initial position, if possible. In any case, stop
  13636. ;; before tags.
  13637. (when (< pos (point)) (goto-char pos))))))
  13638. (defun org-set-tags-command (&optional arg just-align)
  13639. "Call the set-tags command for the current entry."
  13640. (interactive "P")
  13641. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13642. (org-set-tags arg just-align)
  13643. (save-excursion
  13644. (unless (and (org-region-active-p)
  13645. org-loop-over-headlines-in-active-region)
  13646. (org-back-to-heading t))
  13647. (org-set-tags arg just-align))))
  13648. (defun org-set-tags-to (data)
  13649. "Set the tags of the current entry to DATA, replacing the current tags.
  13650. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13651. If DATA is nil or the empty string, any tags will be removed."
  13652. (interactive "sTags: ")
  13653. (setq data
  13654. (cond
  13655. ((eq data nil) "")
  13656. ((equal data "") "")
  13657. ((stringp data)
  13658. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13659. ":"))
  13660. ((listp data)
  13661. (concat ":" (mapconcat 'identity data ":") ":"))))
  13662. (when data
  13663. (save-excursion
  13664. (org-back-to-heading t)
  13665. (when (let ((case-fold-search nil))
  13666. (looking-at org-complex-heading-regexp))
  13667. (if (match-end 5)
  13668. (progn
  13669. (goto-char (match-beginning 5))
  13670. (insert data)
  13671. (delete-region (point) (point-at-eol))
  13672. (org-set-tags nil 'align))
  13673. (goto-char (point-at-eol))
  13674. (insert " " data)
  13675. (org-set-tags nil 'align)))
  13676. (beginning-of-line 1)
  13677. (when (looking-at ".*?\\([ \t]+\\)$")
  13678. (delete-region (match-beginning 1) (match-end 1))))))
  13679. (defun org-align-all-tags ()
  13680. "Align the tags in all headings."
  13681. (interactive)
  13682. (save-excursion
  13683. (or (ignore-errors (org-back-to-heading t))
  13684. (outline-next-heading))
  13685. (if (org-at-heading-p)
  13686. (org-set-tags t)
  13687. (message "No headings"))))
  13688. (defvar org-indent-indentation-per-level)
  13689. (defun org-set-tags (&optional arg just-align)
  13690. "Set the tags for the current headline.
  13691. With prefix ARG, realign all tags in headings in the current buffer.
  13692. When JUST-ALIGN is non-nil, only align tags."
  13693. (interactive "P")
  13694. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13695. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13696. 'region-start-level
  13697. 'region))
  13698. org-loop-over-headlines-in-active-region)
  13699. (org-map-entries
  13700. ;; We don't use ARG and JUST-ALIGN here because these args
  13701. ;; are not useful when looping over headlines.
  13702. #'org-set-tags
  13703. org-loop-over-headlines-in-active-region
  13704. cl
  13705. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13706. (let ((org-setting-tags t))
  13707. (if arg
  13708. (save-excursion
  13709. (goto-char (point-min))
  13710. (while (re-search-forward org-outline-regexp-bol nil t)
  13711. (org-set-tags nil t)
  13712. (end-of-line))
  13713. (message "All tags realigned to column %d" org-tags-column))
  13714. (let* ((current (org-get-tags-string))
  13715. (tags
  13716. (if just-align current
  13717. ;; Get a new set of tags from the user.
  13718. (save-excursion
  13719. (let* ((seen)
  13720. (table
  13721. (setq
  13722. org-last-tags-completion-table
  13723. ;; Uniquify tags in alists, yet preserve
  13724. ;; structure (i.e., keywords).
  13725. (delq nil
  13726. (mapcar
  13727. (lambda (pair)
  13728. (let ((head (car pair)))
  13729. (cond ((symbolp head) pair)
  13730. ((member head seen) nil)
  13731. (t (push head seen)
  13732. pair))))
  13733. (append
  13734. (or org-current-tag-alist
  13735. (org-get-buffer-tags))
  13736. (and
  13737. org-complete-tags-always-offer-all-agenda-tags
  13738. (org-global-tags-completion-table
  13739. (org-agenda-files))))))))
  13740. (current-tags (org-split-string current ":"))
  13741. (inherited-tags
  13742. (nreverse (nthcdr (length current-tags)
  13743. (nreverse (org-get-tags-at))))))
  13744. (replace-regexp-in-string
  13745. "\\([-+&]+\\|,\\)"
  13746. ":"
  13747. (if (or (eq t org-use-fast-tag-selection)
  13748. (and org-use-fast-tag-selection
  13749. (delq nil (mapcar #'cdr table))))
  13750. (org-fast-tag-selection
  13751. current-tags inherited-tags table
  13752. (and org-fast-tag-selection-include-todo
  13753. org-todo-key-alist))
  13754. (let ((org-add-colon-after-tag-completion
  13755. (< 1 (length table))))
  13756. (org-trim
  13757. (completing-read
  13758. "Tags: "
  13759. #'org-tags-completion-function
  13760. nil nil current 'org-tags-history))))))))))
  13761. (when org-tags-sort-function
  13762. (setq tags
  13763. (mapconcat
  13764. #'identity
  13765. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13766. org-tags-sort-function)
  13767. ":")))
  13768. (if (not (org-string-nw-p tags)) (setq tags "")
  13769. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13770. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13771. ;; Insert new tags at the correct column.
  13772. (unless (equal current tags)
  13773. (save-excursion
  13774. (beginning-of-line)
  13775. (let ((case-fold-search nil))
  13776. (looking-at org-complex-heading-regexp))
  13777. ;; Remove current tags, if any.
  13778. (when (match-end 5) (replace-match "" nil nil nil 5))
  13779. ;; Insert new tags, if any. Otherwise, remove trailing
  13780. ;; white spaces.
  13781. (end-of-line)
  13782. (if (not (equal tags ""))
  13783. (insert " " tags)
  13784. (skip-chars-backward " \t")
  13785. (delete-region (point) (line-end-position)))))
  13786. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13787. ;; is on.
  13788. (unless (equal tags "")
  13789. (let* ((level (save-excursion
  13790. (beginning-of-line)
  13791. (skip-chars-forward "\\*")))
  13792. (offset (if (bound-and-true-p org-indent-mode)
  13793. (* (1- org-indent-indentation-per-level)
  13794. (1- level))
  13795. 0))
  13796. (tags-column
  13797. (+ org-tags-column
  13798. (if (> org-tags-column 0) (- offset) offset))))
  13799. (org--align-tags-here tags-column))))
  13800. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13801. (defun org-change-tag-in-region (beg end tag off)
  13802. "Add or remove TAG for each entry in the region.
  13803. This works in the agenda, and also in an Org buffer."
  13804. (interactive
  13805. (list (region-beginning) (region-end)
  13806. (let ((org-last-tags-completion-table
  13807. (if (derived-mode-p 'org-mode)
  13808. (org-uniquify
  13809. (delq nil (append (org-get-buffer-tags)
  13810. (org-global-tags-completion-table))))
  13811. (org-global-tags-completion-table))))
  13812. (completing-read
  13813. "Tag: " 'org-tags-completion-function nil nil nil
  13814. 'org-tags-history))
  13815. (progn
  13816. (message "[s]et or [r]emove? ")
  13817. (equal (read-char-exclusive) ?r))))
  13818. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13819. (let ((agendap (equal major-mode 'org-agenda-mode))
  13820. l1 l2 m buf pos newhead (cnt 0))
  13821. (goto-char end)
  13822. (setq l2 (1- (org-current-line)))
  13823. (goto-char beg)
  13824. (setq l1 (org-current-line))
  13825. (cl-loop for l from l1 to l2 do
  13826. (org-goto-line l)
  13827. (setq m (get-text-property (point) 'org-hd-marker))
  13828. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13829. (and agendap m))
  13830. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13831. pos (if agendap m (point)))
  13832. (with-current-buffer buf
  13833. (save-excursion
  13834. (save-restriction
  13835. (goto-char pos)
  13836. (setq cnt (1+ cnt))
  13837. (org-toggle-tag tag (if off 'off 'on))
  13838. (setq newhead (org-get-heading)))))
  13839. (and agendap (org-agenda-change-all-lines newhead m))))
  13840. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13841. (defun org-tags-completion-function (string _predicate &optional flag)
  13842. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13843. (confirm (lambda (x) (stringp (car x)))))
  13844. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13845. (setq s1 (match-string 1 string)
  13846. s2 (match-string 2 string))
  13847. (setq s1 "" s2 string))
  13848. (cond
  13849. ((eq flag nil)
  13850. ;; try completion
  13851. (setq rtn (try-completion s2 ctable confirm))
  13852. (when (stringp rtn)
  13853. (setq rtn
  13854. (concat s1 s2 (substring rtn (length s2))
  13855. (if (and org-add-colon-after-tag-completion
  13856. (assoc rtn ctable))
  13857. ":" ""))))
  13858. rtn)
  13859. ((eq flag t)
  13860. ;; all-completions
  13861. (all-completions s2 ctable confirm))
  13862. ((eq flag 'lambda)
  13863. ;; exact match?
  13864. (assoc s2 ctable)))))
  13865. (defun org-fast-tag-insert (kwd tags face &optional end)
  13866. "Insert KDW, and the TAGS, the latter with face FACE.
  13867. Also insert END."
  13868. (insert (format "%-12s" (concat kwd ":"))
  13869. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13870. (or end "")))
  13871. (defun org-fast-tag-show-exit (flag)
  13872. (save-excursion
  13873. (org-goto-line 3)
  13874. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13875. (replace-match ""))
  13876. (when flag
  13877. (end-of-line 1)
  13878. (org-move-to-column (- (window-width) 19) t)
  13879. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13880. (defun org-set-current-tags-overlay (current prefix)
  13881. "Add an overlay to CURRENT tag with PREFIX."
  13882. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13883. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13884. (org-overlay-display org-tags-overlay (concat prefix s))))
  13885. (defvar org-last-tag-selection-key nil)
  13886. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13887. "Fast tag selection with single keys.
  13888. CURRENT is the current list of tags in the headline, INHERITED is the
  13889. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13890. possibly with grouping information. TODO-TABLE is a similar table with
  13891. TODO keywords, should these have keys assigned to them.
  13892. If the keys are nil, a-z are automatically assigned.
  13893. Returns the new tags string, or nil to not change the current settings."
  13894. (let* ((fulltable (append table todo-table))
  13895. (maxlen (apply 'max (mapcar
  13896. (lambda (x)
  13897. (if (stringp (car x)) (string-width (car x)) 0))
  13898. fulltable)))
  13899. (buf (current-buffer))
  13900. (expert (eq org-fast-tag-selection-single-key 'expert))
  13901. (buffer-tags nil)
  13902. (fwidth (+ maxlen 3 1 3))
  13903. (ncol (/ (- (window-width) 4) fwidth))
  13904. (i-face 'org-done)
  13905. (c-face 'org-todo)
  13906. tg cnt e c char c1 c2 ntable tbl rtn
  13907. ov-start ov-end ov-prefix
  13908. (exit-after-next org-fast-tag-selection-single-key)
  13909. (done-keywords org-done-keywords)
  13910. groups ingroup intaggroup)
  13911. (save-excursion
  13912. (beginning-of-line 1)
  13913. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13914. (setq ov-start (match-beginning 1)
  13915. ov-end (match-end 1)
  13916. ov-prefix "")
  13917. (setq ov-start (1- (point-at-eol))
  13918. ov-end (1+ ov-start))
  13919. (skip-chars-forward "^\n\r")
  13920. (setq ov-prefix
  13921. (concat
  13922. (buffer-substring (1- (point)) (point))
  13923. (if (> (current-column) org-tags-column)
  13924. " "
  13925. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13926. (move-overlay org-tags-overlay ov-start ov-end)
  13927. (save-window-excursion
  13928. (if expert
  13929. (set-buffer (get-buffer-create " *Org tags*"))
  13930. (delete-other-windows)
  13931. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13932. (org-switch-to-buffer-other-window " *Org tags*"))
  13933. (erase-buffer)
  13934. (setq-local org-done-keywords done-keywords)
  13935. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13936. (org-fast-tag-insert "Current" current c-face "\n\n")
  13937. (org-fast-tag-show-exit exit-after-next)
  13938. (org-set-current-tags-overlay current ov-prefix)
  13939. (setq tbl fulltable char ?a cnt 0)
  13940. (while (setq e (pop tbl))
  13941. (cond
  13942. ((eq (car e) :startgroup)
  13943. (push '() groups) (setq ingroup t)
  13944. (unless (zerop cnt)
  13945. (setq cnt 0)
  13946. (insert "\n"))
  13947. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13948. ((eq (car e) :endgroup)
  13949. (setq ingroup nil cnt 0)
  13950. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13951. ((eq (car e) :startgrouptag)
  13952. (setq intaggroup t)
  13953. (unless (zerop cnt)
  13954. (setq cnt 0)
  13955. (insert "\n"))
  13956. (insert "[ "))
  13957. ((eq (car e) :endgrouptag)
  13958. (setq intaggroup nil cnt 0)
  13959. (insert "]\n"))
  13960. ((equal e '(:newline))
  13961. (unless (zerop cnt)
  13962. (setq cnt 0)
  13963. (insert "\n")
  13964. (setq e (car tbl))
  13965. (while (equal (car tbl) '(:newline))
  13966. (insert "\n")
  13967. (setq tbl (cdr tbl)))))
  13968. ((equal e '(:grouptags)) (insert " : "))
  13969. (t
  13970. (setq tg (copy-sequence (car e)) c2 nil)
  13971. (if (cdr e)
  13972. (setq c (cdr e))
  13973. ;; automatically assign a character.
  13974. (setq c1 (string-to-char
  13975. (downcase (substring
  13976. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13977. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13978. (while (or (rassoc char ntable) (rassoc char table))
  13979. (setq char (1+ char)))
  13980. (setq c2 c1))
  13981. (setq c (or c2 char)))
  13982. (when ingroup (push tg (car groups)))
  13983. (setq tg (org-add-props tg nil 'face
  13984. (cond
  13985. ((not (assoc tg table))
  13986. (org-get-todo-face tg))
  13987. ((member tg current) c-face)
  13988. ((member tg inherited) i-face))))
  13989. (when (equal (caar tbl) :grouptags)
  13990. (org-add-props tg nil 'face 'org-tag-group))
  13991. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13992. (insert "[" c "] " tg (make-string
  13993. (- fwidth 4 (length tg)) ?\ ))
  13994. (push (cons tg c) ntable)
  13995. (when (= (cl-incf cnt) ncol)
  13996. (insert "\n")
  13997. (when (or ingroup intaggroup) (insert " "))
  13998. (setq cnt 0)))))
  13999. (setq ntable (nreverse ntable))
  14000. (insert "\n")
  14001. (goto-char (point-min))
  14002. (unless expert (org-fit-window-to-buffer))
  14003. (setq rtn
  14004. (catch 'exit
  14005. (while t
  14006. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  14007. (if (not groups) "no " "")
  14008. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  14009. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  14010. (setq org-last-tag-selection-key c)
  14011. (cond
  14012. ((= c ?\r) (throw 'exit t))
  14013. ((= c ?!)
  14014. (setq groups (not groups))
  14015. (goto-char (point-min))
  14016. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  14017. ((= c ?\C-c)
  14018. (if (not expert)
  14019. (org-fast-tag-show-exit
  14020. (setq exit-after-next (not exit-after-next)))
  14021. (setq expert nil)
  14022. (delete-other-windows)
  14023. (set-window-buffer (split-window-vertically) " *Org tags*")
  14024. (org-switch-to-buffer-other-window " *Org tags*")
  14025. (org-fit-window-to-buffer)))
  14026. ((or (= c ?\C-g)
  14027. (and (= c ?q) (not (rassoc c ntable))))
  14028. (delete-overlay org-tags-overlay)
  14029. (setq quit-flag t))
  14030. ((= c ?\ )
  14031. (setq current nil)
  14032. (when exit-after-next (setq exit-after-next 'now)))
  14033. ((= c ?\t)
  14034. (condition-case nil
  14035. (setq tg (completing-read
  14036. "Tag: "
  14037. (or buffer-tags
  14038. (with-current-buffer buf
  14039. (setq buffer-tags
  14040. (org-get-buffer-tags))))))
  14041. (quit (setq tg "")))
  14042. (when (string-match "\\S-" tg)
  14043. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14044. (if (member tg current)
  14045. (setq current (delete tg current))
  14046. (push tg current)))
  14047. (when exit-after-next (setq exit-after-next 'now)))
  14048. ((setq e (rassoc c todo-table) tg (car e))
  14049. (with-current-buffer buf
  14050. (save-excursion (org-todo tg)))
  14051. (when exit-after-next (setq exit-after-next 'now)))
  14052. ((setq e (rassoc c ntable) tg (car e))
  14053. (if (member tg current)
  14054. (setq current (delete tg current))
  14055. (cl-loop for g in groups do
  14056. (when (member tg g)
  14057. (dolist (x g) (setq current (delete x current)))))
  14058. (push tg current))
  14059. (when exit-after-next (setq exit-after-next 'now))))
  14060. ;; Create a sorted list
  14061. (setq current
  14062. (sort current
  14063. (lambda (a b)
  14064. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14065. (when (eq exit-after-next 'now) (throw 'exit t))
  14066. (goto-char (point-min))
  14067. (beginning-of-line 2)
  14068. (delete-region (point) (point-at-eol))
  14069. (org-fast-tag-insert "Current" current c-face)
  14070. (org-set-current-tags-overlay current ov-prefix)
  14071. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14072. (setq tg (match-string 1))
  14073. (add-text-properties
  14074. (match-beginning 1) (match-end 1)
  14075. (list 'face
  14076. (cond
  14077. ((member tg current) c-face)
  14078. ((member tg inherited) i-face)
  14079. (t (get-text-property (match-beginning 1) 'face))))))
  14080. (goto-char (point-min)))))
  14081. (delete-overlay org-tags-overlay)
  14082. (if rtn
  14083. (mapconcat 'identity current ":")
  14084. nil))))
  14085. (defun org-get-tags-string ()
  14086. "Get the TAGS string in the current headline."
  14087. (unless (org-at-heading-p t)
  14088. (user-error "Not on a heading"))
  14089. (save-excursion
  14090. (beginning-of-line 1)
  14091. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14092. (match-string-no-properties 1)
  14093. "")))
  14094. (defun org-get-tags ()
  14095. "Get the list of tags specified in the current headline."
  14096. (org-split-string (org-get-tags-string) ":"))
  14097. (defun org-get-buffer-tags ()
  14098. "Get a table of all tags used in the buffer, for completion."
  14099. (org-with-wide-buffer
  14100. (goto-char (point-min))
  14101. (let ((tag-re (concat org-outline-regexp-bol
  14102. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14103. tags)
  14104. (while (re-search-forward tag-re nil t)
  14105. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14106. (push tag tags)))
  14107. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14108. ;;;; The mapping API
  14109. (defvar org-agenda-skip-comment-trees)
  14110. (defvar org-agenda-skip-function)
  14111. (defun org-map-entries (func &optional match scope &rest skip)
  14112. "Call FUNC at each headline selected by MATCH in SCOPE.
  14113. FUNC is a function or a lisp form. The function will be called without
  14114. arguments, with the cursor positioned at the beginning of the headline.
  14115. The return values of all calls to the function will be collected and
  14116. returned as a list.
  14117. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14118. does not need to preserve point. After evaluation, the cursor will be
  14119. moved to the end of the line (presumably of the headline of the
  14120. processed entry) and search continues from there. Under some
  14121. circumstances, this may not produce the wanted results. For example,
  14122. if you have removed (e.g. archived) the current (sub)tree it could
  14123. mean that the next entry will be skipped entirely. In such cases, you
  14124. can specify the position from where search should continue by making
  14125. FUNC set the variable `org-map-continue-from' to the desired buffer
  14126. position.
  14127. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14128. Only headlines that are matched by this query will be considered during
  14129. the iteration. When MATCH is nil or t, all headlines will be
  14130. visited by the iteration.
  14131. SCOPE determines the scope of this command. It can be any of:
  14132. nil The current buffer, respecting the restriction if any
  14133. tree The subtree started with the entry at point
  14134. region The entries within the active region, if any
  14135. region-start-level
  14136. The entries within the active region, but only those at
  14137. the same level than the first one.
  14138. file The current buffer, without restriction
  14139. file-with-archives
  14140. The current buffer, and any archives associated with it
  14141. agenda All agenda files
  14142. agenda-with-archives
  14143. All agenda files with any archive files associated with them
  14144. \(file1 file2 ...)
  14145. If this is a list, all files in the list will be scanned
  14146. The remaining args are treated as settings for the skipping facilities of
  14147. the scanner. The following items can be given here:
  14148. archive skip trees with the archive tag
  14149. comment skip trees with the COMMENT keyword
  14150. function or Emacs Lisp form:
  14151. will be used as value for `org-agenda-skip-function', so
  14152. whenever the function returns a position, FUNC will not be
  14153. called for that entry and search will continue from the
  14154. position returned
  14155. If your function needs to retrieve the tags including inherited tags
  14156. at the *current* entry, you can use the value of the variable
  14157. `org-scanner-tags' which will be much faster than getting the value
  14158. with `org-get-tags-at'. If your function gets properties with
  14159. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14160. to t around the call to `org-entry-properties' to get the same speedup.
  14161. Note that if your function moves around to retrieve tags and properties at
  14162. a *different* entry, you cannot use these techniques."
  14163. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14164. (not (org-region-active-p)))
  14165. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14166. (org-agenda-skip-archived-trees (memq 'archive skip))
  14167. (org-agenda-skip-comment-trees (memq 'comment skip))
  14168. (org-agenda-skip-function
  14169. (car (org-delete-all '(comment archive) skip)))
  14170. (org-tags-match-list-sublevels t)
  14171. (start-level (eq scope 'region-start-level))
  14172. matcher res
  14173. org-todo-keywords-for-agenda
  14174. org-done-keywords-for-agenda
  14175. org-todo-keyword-alist-for-agenda
  14176. org-tag-alist-for-agenda
  14177. org--matcher-tags-todo-only)
  14178. (cond
  14179. ((eq match t) (setq matcher t))
  14180. ((eq match nil) (setq matcher t))
  14181. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14182. (save-excursion
  14183. (save-restriction
  14184. (cond ((eq scope 'tree)
  14185. (org-back-to-heading t)
  14186. (org-narrow-to-subtree)
  14187. (setq scope nil))
  14188. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14189. (org-region-active-p))
  14190. ;; If needed, set start-level to a string like "2"
  14191. (when start-level
  14192. (save-excursion
  14193. (goto-char (region-beginning))
  14194. (unless (org-at-heading-p) (outline-next-heading))
  14195. (setq start-level (org-current-level))))
  14196. (narrow-to-region (region-beginning)
  14197. (save-excursion
  14198. (goto-char (region-end))
  14199. (unless (and (bolp) (org-at-heading-p))
  14200. (outline-next-heading))
  14201. (point)))
  14202. (setq scope nil)))
  14203. (if (not scope)
  14204. (progn
  14205. (org-agenda-prepare-buffers
  14206. (and buffer-file-name (list buffer-file-name)))
  14207. (setq res
  14208. (org-scan-tags
  14209. func matcher org--matcher-tags-todo-only start-level)))
  14210. ;; Get the right scope
  14211. (cond
  14212. ((and scope (listp scope) (symbolp (car scope)))
  14213. (setq scope (eval scope)))
  14214. ((eq scope 'agenda)
  14215. (setq scope (org-agenda-files t)))
  14216. ((eq scope 'agenda-with-archives)
  14217. (setq scope (org-agenda-files t))
  14218. (setq scope (org-add-archive-files scope)))
  14219. ((eq scope 'file)
  14220. (setq scope (and buffer-file-name (list buffer-file-name))))
  14221. ((eq scope 'file-with-archives)
  14222. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14223. (org-agenda-prepare-buffers scope)
  14224. (dolist (file scope)
  14225. (with-current-buffer (org-find-base-buffer-visiting file)
  14226. (org-with-wide-buffer
  14227. (goto-char (point-min))
  14228. (setq res
  14229. (append
  14230. res
  14231. (org-scan-tags
  14232. func matcher org--matcher-tags-todo-only)))))))))
  14233. res)))
  14234. ;;; Properties API
  14235. (defconst org-special-properties
  14236. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14237. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14238. "The special properties valid in Org mode.
  14239. These are properties that are not defined in the property drawer,
  14240. but in some other way.")
  14241. (defconst org-default-properties
  14242. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14243. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14244. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14245. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14246. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14247. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14248. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14249. "Some properties that are used by Org mode for various purposes.
  14250. Being in this list makes sure that they are offered for completion.")
  14251. (defun org--valid-property-p (property)
  14252. "Non nil when string PROPERTY is a valid property name."
  14253. (not
  14254. (or (equal property "")
  14255. (string-match-p "\\s-" property))))
  14256. (defun org--update-property-plist (key val props)
  14257. "Associate KEY to VAL in alist PROPS.
  14258. Modifications are made by side-effect. Return new alist."
  14259. (let* ((appending (string= (substring key -1) "+"))
  14260. (key (if appending (substring key 0 -1) key))
  14261. (old (assoc-string key props t)))
  14262. (if (not old) (cons (cons key val) props)
  14263. (setcdr old (if appending (concat (cdr old) " " val) val))
  14264. props)))
  14265. (defun org-get-property-block (&optional beg force)
  14266. "Return the (beg . end) range of the body of the property drawer.
  14267. BEG is the beginning of the current subtree, or of the part
  14268. before the first headline. If it is not given, it will be found.
  14269. If the drawer does not exist, create it if FORCE is non-nil, or
  14270. return nil."
  14271. (org-with-wide-buffer
  14272. (when beg (goto-char beg))
  14273. (unless (org-before-first-heading-p)
  14274. (let ((beg (cond (beg)
  14275. ((or (not (featurep 'org-inlinetask))
  14276. (org-inlinetask-in-task-p))
  14277. (org-back-to-heading t))
  14278. (t (org-with-limited-levels (org-back-to-heading t))))))
  14279. (forward-line)
  14280. (when (looking-at-p org-planning-line-re) (forward-line))
  14281. (cond ((looking-at org-property-drawer-re)
  14282. (forward-line)
  14283. (cons (point) (progn (goto-char (match-end 0))
  14284. (line-beginning-position))))
  14285. (force
  14286. (goto-char beg)
  14287. (org-insert-property-drawer)
  14288. (let ((pos (save-excursion (search-forward ":END:")
  14289. (line-beginning-position))))
  14290. (cons pos pos))))))))
  14291. (defun org-at-property-p ()
  14292. "Non-nil when point is inside a property drawer.
  14293. See `org-property-re' for match data, if applicable."
  14294. (save-excursion
  14295. (beginning-of-line)
  14296. (and (looking-at org-property-re)
  14297. (let ((property-drawer (save-match-data (org-get-property-block))))
  14298. (and property-drawer
  14299. (>= (point) (car property-drawer))
  14300. (< (point) (cdr property-drawer)))))))
  14301. (defun org-property-action ()
  14302. "Do an action on properties."
  14303. (interactive)
  14304. (unless (org-at-property-p) (user-error "Not at a property"))
  14305. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14306. (let ((c (read-char-exclusive)))
  14307. (cl-case c
  14308. (?s (call-interactively #'org-set-property))
  14309. (?d (call-interactively #'org-delete-property))
  14310. (?D (call-interactively #'org-delete-property-globally))
  14311. (?c (call-interactively #'org-compute-property-at-point))
  14312. (otherwise (user-error "No such property action %c" c)))))
  14313. (defun org-inc-effort ()
  14314. "Increment the value of the effort property in the current entry."
  14315. (interactive)
  14316. (org-set-effort nil t))
  14317. (defvar org-clock-effort) ; Defined in org-clock.el.
  14318. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14319. (defun org-set-effort (&optional value increment)
  14320. "Set the effort property of the current entry.
  14321. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14322. 10th allowed value.
  14323. When INCREMENT is non-nil, set the property to the next allowed value."
  14324. (interactive "P")
  14325. (when (equal value 0) (setq value 10))
  14326. (let* ((completion-ignore-case t)
  14327. (prop org-effort-property)
  14328. (cur (org-entry-get nil prop))
  14329. (allowed (org-property-get-allowed-values nil prop 'table))
  14330. (existing (mapcar 'list (org-property-values prop)))
  14331. (heading (nth 4 (org-heading-components)))
  14332. rpl
  14333. (val (cond
  14334. ((stringp value) value)
  14335. ((and allowed (integerp value))
  14336. (or (car (nth (1- value) allowed))
  14337. (car (org-last allowed))))
  14338. ((and allowed increment)
  14339. (or (cl-caadr (member (list cur) allowed))
  14340. (user-error "Allowed effort values are not set")))
  14341. (allowed
  14342. (message "Select 1-9,0, [RET%s]: %s"
  14343. (if cur (concat "=" cur) "")
  14344. (mapconcat 'car allowed " "))
  14345. (setq rpl (read-char-exclusive))
  14346. (if (equal rpl ?\r)
  14347. cur
  14348. (setq rpl (- rpl ?0))
  14349. (when (equal rpl 0) (setq rpl 10))
  14350. (if (and (> rpl 0) (<= rpl (length allowed)))
  14351. (car (nth (1- rpl) allowed))
  14352. (org-completing-read "Effort: " allowed nil))))
  14353. (t
  14354. (org-completing-read
  14355. (concat "Effort" (and cur (string-match "\\S-" cur)
  14356. (concat " [" cur "]"))
  14357. ": ")
  14358. existing nil nil "" nil cur)))))
  14359. (unless (equal (org-entry-get nil prop) val)
  14360. (org-entry-put nil prop val))
  14361. (org-refresh-property
  14362. '((effort . identity)
  14363. (effort-minutes . org-duration-string-to-minutes))
  14364. val)
  14365. (when (equal heading (bound-and-true-p org-clock-current-task))
  14366. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14367. (org-clock-update-mode-line))
  14368. (message "%s is now %s" prop val)))
  14369. (defun org-entry-properties (&optional pom which)
  14370. "Get all properties of the current entry.
  14371. When POM is a buffer position, get all properties from the entry
  14372. there instead.
  14373. This includes the TODO keyword, the tags, time strings for
  14374. deadline, scheduled, and clocking, and any additional properties
  14375. defined in the entry.
  14376. If WHICH is nil or `all', get all properties. If WHICH is
  14377. `special' or `standard', only get that subclass. If WHICH is
  14378. a string, only get that property.
  14379. Return value is an alist. Keys are properties, as upcased
  14380. strings."
  14381. (org-with-point-at pom
  14382. (when (and (derived-mode-p 'org-mode)
  14383. (ignore-errors (org-back-to-heading t)))
  14384. (catch 'exit
  14385. (let* ((beg (point))
  14386. (specific (and (stringp which) (upcase which)))
  14387. (which (cond ((not specific) which)
  14388. ((member specific org-special-properties) 'special)
  14389. (t 'standard)))
  14390. props)
  14391. ;; Get the special properties, like TODO and TAGS.
  14392. (when (memq which '(nil all special))
  14393. (when (or (not specific) (string= specific "CLOCKSUM"))
  14394. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14395. (when clocksum
  14396. (push (cons "CLOCKSUM"
  14397. (org-minutes-to-clocksum-string clocksum))
  14398. props)))
  14399. (when specific (throw 'exit props)))
  14400. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14401. (let ((clocksumt (get-text-property (point)
  14402. :org-clock-minutes-today)))
  14403. (when clocksumt
  14404. (push (cons "CLOCKSUM_T"
  14405. (org-minutes-to-clocksum-string clocksumt))
  14406. props)))
  14407. (when specific (throw 'exit props)))
  14408. (when (or (not specific) (string= specific "ITEM"))
  14409. (let ((case-fold-search nil))
  14410. (when (looking-at org-complex-heading-regexp)
  14411. (push (cons "ITEM"
  14412. (let ((title (match-string-no-properties 4)))
  14413. (if (org-string-nw-p title)
  14414. (org-remove-tabs title)
  14415. "")))
  14416. props)))
  14417. (when specific (throw 'exit props)))
  14418. (when (or (not specific) (string= specific "TODO"))
  14419. (let ((case-fold-search nil))
  14420. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14421. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14422. (when specific (throw 'exit props)))
  14423. (when (or (not specific) (string= specific "PRIORITY"))
  14424. (push (cons "PRIORITY"
  14425. (if (looking-at org-priority-regexp)
  14426. (match-string-no-properties 2)
  14427. (char-to-string org-default-priority)))
  14428. props)
  14429. (when specific (throw 'exit props)))
  14430. (when (or (not specific) (string= specific "FILE"))
  14431. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14432. props)
  14433. (when specific (throw 'exit props)))
  14434. (when (or (not specific) (string= specific "TAGS"))
  14435. (let ((value (org-string-nw-p (org-get-tags-string))))
  14436. (when value (push (cons "TAGS" value) props)))
  14437. (when specific (throw 'exit props)))
  14438. (when (or (not specific) (string= specific "ALLTAGS"))
  14439. (let ((value (org-get-tags-at)))
  14440. (when value
  14441. (push (cons "ALLTAGS"
  14442. (format ":%s:" (mapconcat #'identity value ":")))
  14443. props)))
  14444. (when specific (throw 'exit props)))
  14445. (when (or (not specific) (string= specific "BLOCKED"))
  14446. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14447. (when specific (throw 'exit props)))
  14448. (when (or (not specific)
  14449. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14450. (forward-line)
  14451. (when (looking-at-p org-planning-line-re)
  14452. (end-of-line)
  14453. (let ((bol (line-beginning-position))
  14454. ;; Backward compatibility: time keywords used to
  14455. ;; be configurable (before 8.3). Make sure we
  14456. ;; get the correct keyword.
  14457. (key-assoc `(("CLOSED" . ,org-closed-string)
  14458. ("DEADLINE" . ,org-deadline-string)
  14459. ("SCHEDULED" . ,org-scheduled-string))))
  14460. (dolist (pair (if specific (list (assoc specific key-assoc))
  14461. key-assoc))
  14462. (save-excursion
  14463. (when (search-backward (cdr pair) bol t)
  14464. (goto-char (match-end 0))
  14465. (skip-chars-forward " \t")
  14466. (and (looking-at org-ts-regexp-both)
  14467. (push (cons (car pair)
  14468. (match-string-no-properties 0))
  14469. props)))))))
  14470. (when specific (throw 'exit props)))
  14471. (when (or (not specific)
  14472. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14473. (let ((find-ts
  14474. (lambda (end ts)
  14475. ;; Fix next time-stamp before END. TS is the
  14476. ;; list of time-stamps found so far.
  14477. (let ((ts ts)
  14478. (regexp (cond
  14479. ((string= specific "TIMESTAMP")
  14480. org-ts-regexp)
  14481. ((string= specific "TIMESTAMP_IA")
  14482. org-ts-regexp-inactive)
  14483. ((assoc "TIMESTAMP_IA" ts)
  14484. org-ts-regexp)
  14485. ((assoc "TIMESTAMP" ts)
  14486. org-ts-regexp-inactive)
  14487. (t org-ts-regexp-both))))
  14488. (catch 'next
  14489. (while (re-search-forward regexp end t)
  14490. (backward-char)
  14491. (let ((object (org-element-context)))
  14492. ;; Accept to match timestamps in node
  14493. ;; properties, too.
  14494. (when (memq (org-element-type object)
  14495. '(node-property timestamp))
  14496. (let ((type
  14497. (org-element-property :type object)))
  14498. (cond
  14499. ((and (memq type '(active active-range))
  14500. (not (equal specific "TIMESTAMP_IA")))
  14501. (unless (assoc "TIMESTAMP" ts)
  14502. (push (cons "TIMESTAMP"
  14503. (org-element-property
  14504. :raw-value object))
  14505. ts)
  14506. (when specific (throw 'exit ts))))
  14507. ((and (memq type '(inactive inactive-range))
  14508. (not (string= specific "TIMESTAMP")))
  14509. (unless (assoc "TIMESTAMP_IA" ts)
  14510. (push (cons "TIMESTAMP_IA"
  14511. (org-element-property
  14512. :raw-value object))
  14513. ts)
  14514. (when specific (throw 'exit ts))))))
  14515. ;; Both timestamp types are found,
  14516. ;; move to next part.
  14517. (when (= (length ts) 2) (throw 'next ts)))))
  14518. ts)))))
  14519. (goto-char beg)
  14520. ;; First look for timestamps within headline.
  14521. (let ((ts (funcall find-ts (line-end-position) nil)))
  14522. (if (= (length ts) 2) (setq props (nconc ts props))
  14523. (forward-line)
  14524. ;; Then find timestamps in the section, skipping
  14525. ;; planning line.
  14526. (when (looking-at-p org-planning-line-re)
  14527. (forward-line))
  14528. (let ((end (save-excursion (outline-next-heading))))
  14529. (setq props (nconc (funcall find-ts end ts) props))))))))
  14530. ;; Get the standard properties, like :PROP:.
  14531. (when (memq which '(nil all standard))
  14532. ;; If we are looking after a specific property, delegate
  14533. ;; to `org-entry-get', which is faster. However, make an
  14534. ;; exception for "CATEGORY", since it can be also set
  14535. ;; through keywords (i.e. #+CATEGORY).
  14536. (if (and specific (not (equal specific "CATEGORY")))
  14537. (let ((value (org-entry-get beg specific nil t)))
  14538. (throw 'exit (and value (list (cons specific value)))))
  14539. (let ((range (org-get-property-block beg)))
  14540. (when range
  14541. (let ((end (cdr range)) seen-base)
  14542. (goto-char (car range))
  14543. ;; Unlike to `org--update-property-plist', we
  14544. ;; handle the case where base values is found
  14545. ;; after its extension. We also forbid standard
  14546. ;; properties to be named as special properties.
  14547. (while (re-search-forward org-property-re end t)
  14548. (let* ((key (upcase (match-string-no-properties 2)))
  14549. (extendp (string-match-p "\\+\\'" key))
  14550. (key-base (if extendp (substring key 0 -1) key))
  14551. (value (match-string-no-properties 3)))
  14552. (cond
  14553. ((member-ignore-case key-base org-special-properties))
  14554. (extendp
  14555. (setq props
  14556. (org--update-property-plist key value props)))
  14557. ((member key seen-base))
  14558. (t (push key seen-base)
  14559. (let ((p (assoc-string key props t)))
  14560. (if p (setcdr p (concat value " " (cdr p)))
  14561. (push (cons key value) props))))))))))))
  14562. (unless (assoc "CATEGORY" props)
  14563. (push (cons "CATEGORY" (org-get-category beg)) props)
  14564. (when (string= specific "CATEGORY") (throw 'exit props)))
  14565. ;; Return value.
  14566. props)))))
  14567. (defun org-property--local-values (property literal-nil)
  14568. "Return value for PROPERTY in current entry.
  14569. Value is a list whose car is the base value for PROPERTY and cdr
  14570. a list of accumulated values. Return nil if neither is found in
  14571. the entry. Also return nil when PROPERTY is set to \"nil\",
  14572. unless LITERAL-NIL is non-nil."
  14573. (let ((range (org-get-property-block)))
  14574. (when range
  14575. (goto-char (car range))
  14576. (let* ((case-fold-search t)
  14577. (end (cdr range))
  14578. (value
  14579. ;; Base value.
  14580. (save-excursion
  14581. (let ((v (and (re-search-forward
  14582. (org-re-property property nil t) end t)
  14583. (match-string-no-properties 3))))
  14584. (list (if literal-nil v (org-not-nil v)))))))
  14585. ;; Find additional values.
  14586. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14587. (while (re-search-forward property+ end t)
  14588. (push (match-string-no-properties 3) value)))
  14589. ;; Return final values.
  14590. (and (not (equal value '(nil))) (nreverse value))))))
  14591. (defun org-entry-get (pom property &optional inherit literal-nil)
  14592. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14593. If INHERIT is non-nil and the entry does not have the property,
  14594. then also check higher levels of the hierarchy. If INHERIT is
  14595. the symbol `selective', use inheritance only if the setting in
  14596. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14597. If the property is present but empty, the return value is the
  14598. empty string. If the property is not present at all, nil is
  14599. returned. In any other case, return the value as a string.
  14600. Search is case-insensitive.
  14601. If LITERAL-NIL is set, return the string value \"nil\" as
  14602. a string, do not interpret it as the list atom nil. This is used
  14603. for inheritance when a \"nil\" value can supersede a non-nil
  14604. value higher up the hierarchy."
  14605. (org-with-point-at pom
  14606. (cond
  14607. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14608. ;; We need a special property. Use `org-entry-properties' to
  14609. ;; retrieve it, but specify the wanted property.
  14610. (cdr (assoc-string property (org-entry-properties nil property))))
  14611. ((and inherit
  14612. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14613. (org-entry-get-with-inheritance property literal-nil))
  14614. (t
  14615. (let* ((local (org-property--local-values property literal-nil))
  14616. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14617. (if literal-nil value (org-not-nil value)))))))
  14618. (defun org-property-or-variable-value (var &optional inherit)
  14619. "Check if there is a property fixing the value of VAR.
  14620. If yes, return this value. If not, return the current value of the variable."
  14621. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14622. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14623. (read prop)
  14624. (symbol-value var))))
  14625. (defun org-entry-delete (pom property)
  14626. "Delete PROPERTY from entry at point-or-marker POM.
  14627. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14628. non-nil when a property was removed."
  14629. (unless (member property org-special-properties)
  14630. (org-with-point-at pom
  14631. (let ((range (org-get-property-block)))
  14632. (when range
  14633. (let* ((begin (car range))
  14634. (origin (cdr range))
  14635. (end (copy-marker origin))
  14636. (re (org-re-property
  14637. (concat (regexp-quote property) "\\+?") t t)))
  14638. (goto-char begin)
  14639. (while (re-search-forward re end t)
  14640. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14641. ;; If drawer is empty, remove it altogether.
  14642. (when (= begin end)
  14643. (delete-region (line-beginning-position 0)
  14644. (line-beginning-position 2)))
  14645. ;; Return non-nil if some property was removed.
  14646. (prog1 (/= end origin) (set-marker end nil))))))))
  14647. ;; Multi-values properties are properties that contain multiple values
  14648. ;; These values are assumed to be single words, separated by whitespace.
  14649. (defun org-entry-add-to-multivalued-property (pom property value)
  14650. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14651. (let* ((old (org-entry-get pom property))
  14652. (values (and old (org-split-string old "[ \t]"))))
  14653. (setq value (org-entry-protect-space value))
  14654. (unless (member value values)
  14655. (setq values (append values (list value)))
  14656. (org-entry-put pom property
  14657. (mapconcat 'identity values " ")))))
  14658. (defun org-entry-remove-from-multivalued-property (pom property value)
  14659. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14660. (let* ((old (org-entry-get pom property))
  14661. (values (and old (org-split-string old "[ \t]"))))
  14662. (setq value (org-entry-protect-space value))
  14663. (when (member value values)
  14664. (setq values (delete value values))
  14665. (org-entry-put pom property
  14666. (mapconcat 'identity values " ")))))
  14667. (defun org-entry-member-in-multivalued-property (pom property value)
  14668. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14669. (let* ((old (org-entry-get pom property))
  14670. (values (and old (org-split-string old "[ \t]"))))
  14671. (setq value (org-entry-protect-space value))
  14672. (member value values)))
  14673. (defun org-entry-get-multivalued-property (pom property)
  14674. "Return a list of values in a multivalued property."
  14675. (let* ((value (org-entry-get pom property))
  14676. (values (and value (org-split-string value "[ \t]"))))
  14677. (mapcar 'org-entry-restore-space values)))
  14678. (defun org-entry-put-multivalued-property (pom property &rest values)
  14679. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14680. VALUES should be a list of strings. Spaces will be protected."
  14681. (org-entry-put pom property
  14682. (mapconcat 'org-entry-protect-space values " "))
  14683. (let* ((value (org-entry-get pom property))
  14684. (values (and value (org-split-string value "[ \t]"))))
  14685. (mapcar 'org-entry-restore-space values)))
  14686. (defun org-entry-protect-space (s)
  14687. "Protect spaces and newline in string S."
  14688. (while (string-match " " s)
  14689. (setq s (replace-match "%20" t t s)))
  14690. (while (string-match "\n" s)
  14691. (setq s (replace-match "%0A" t t s)))
  14692. s)
  14693. (defun org-entry-restore-space (s)
  14694. "Restore spaces and newline in string S."
  14695. (while (string-match "%20" s)
  14696. (setq s (replace-match " " t t s)))
  14697. (while (string-match "%0A" s)
  14698. (setq s (replace-match "\n" t t s)))
  14699. s)
  14700. (defvar org-entry-property-inherited-from (make-marker)
  14701. "Marker pointing to the entry from where a property was inherited.
  14702. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14703. location of the entry where the inheritance search matched. If there was
  14704. no match, the marker will point nowhere.
  14705. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14706. is set.")
  14707. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14708. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14709. The search will stop at the first ancestor which has the property defined.
  14710. If the value found is \"nil\", return nil to show that the property
  14711. should be considered as undefined (this is the meaning of nil here).
  14712. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14713. (move-marker org-entry-property-inherited-from nil)
  14714. (org-with-wide-buffer
  14715. (let (value)
  14716. (catch 'exit
  14717. (while t
  14718. (let ((v (org-property--local-values property literal-nil)))
  14719. (when v
  14720. (setq value
  14721. (concat (mapconcat #'identity (delq nil v) " ")
  14722. (and value " ")
  14723. value)))
  14724. (cond
  14725. ((car v)
  14726. (org-back-to-heading t)
  14727. (move-marker org-entry-property-inherited-from (point))
  14728. (throw 'exit nil))
  14729. ((org-up-heading-safe))
  14730. (t
  14731. (let ((global
  14732. (cdr (or (assoc-string property org-file-properties t)
  14733. (assoc-string property org-global-properties t)
  14734. (assoc-string property org-global-properties-fixed t)))))
  14735. (cond ((not global))
  14736. (value (setq value (concat global " " value)))
  14737. (t (setq value global))))
  14738. (throw 'exit nil))))))
  14739. (if literal-nil value (org-not-nil value)))))
  14740. (defvar org-property-changed-functions nil
  14741. "Hook called when the value of a property has changed.
  14742. Each hook function should accept two arguments, the name of the property
  14743. and the new value.")
  14744. (defun org-entry-put (pom property value)
  14745. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14746. If the value is nil, it is converted to the empty string. If it
  14747. is not a string, an error is raised. Also raise an error on
  14748. invalid property names.
  14749. PROPERTY can be any regular property (see
  14750. `org-special-properties'). It can also be \"TODO\",
  14751. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14752. For the last two properties, VALUE may have any of the special
  14753. values \"earlier\" and \"later\". The function then increases or
  14754. decreases scheduled or deadline date by one day."
  14755. (cond ((null value) (setq value ""))
  14756. ((not (stringp value)) (error "Properties values should be strings"))
  14757. ((not (org--valid-property-p property))
  14758. (user-error "Invalid property name: \"%s\"" property)))
  14759. (org-with-point-at pom
  14760. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14761. (org-back-to-heading t)
  14762. (org-with-limited-levels (org-back-to-heading t)))
  14763. (let ((beg (point)))
  14764. (cond
  14765. ((equal property "TODO")
  14766. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14767. ((not (member value org-todo-keywords-1))
  14768. (user-error "\"%s\" is not a valid TODO state" value)))
  14769. (org-todo value)
  14770. (org-set-tags nil 'align))
  14771. ((equal property "PRIORITY")
  14772. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14773. (org-set-tags nil 'align))
  14774. ((equal property "SCHEDULED")
  14775. (forward-line)
  14776. (if (and (looking-at-p org-planning-line-re)
  14777. (re-search-forward
  14778. org-scheduled-time-regexp (line-end-position) t))
  14779. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14780. ((string= value "later") (org-timestamp-change 1 'day))
  14781. ((string= value "") (org-schedule '(4)))
  14782. (t (org-schedule nil value)))
  14783. (if (member value '("earlier" "later" ""))
  14784. (call-interactively #'org-schedule)
  14785. (org-schedule nil value))))
  14786. ((equal property "DEADLINE")
  14787. (forward-line)
  14788. (if (and (looking-at-p org-planning-line-re)
  14789. (re-search-forward
  14790. org-deadline-time-regexp (line-end-position) t))
  14791. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14792. ((string= value "later") (org-timestamp-change 1 'day))
  14793. ((string= value "") (org-deadline '(4)))
  14794. (t (org-deadline nil value)))
  14795. (if (member value '("earlier" "later" ""))
  14796. (call-interactively #'org-deadline)
  14797. (org-deadline nil value))))
  14798. ((member property org-special-properties)
  14799. (error "The %s property cannot be set with `org-entry-put'" property))
  14800. (t
  14801. (let* ((range (org-get-property-block beg 'force))
  14802. (end (cdr range))
  14803. (case-fold-search t))
  14804. (goto-char (car range))
  14805. (if (re-search-forward (org-re-property property nil t) end t)
  14806. (progn (delete-region (match-beginning 0) (match-end 0))
  14807. (goto-char (match-beginning 0)))
  14808. (goto-char end)
  14809. (insert "\n")
  14810. (backward-char))
  14811. (insert ":" property ":")
  14812. (when value (insert " " value))
  14813. (org-indent-line)))))
  14814. (run-hook-with-args 'org-property-changed-functions property value)))
  14815. (defun org-buffer-property-keys
  14816. (&optional specials defaults columns ignore-malformed)
  14817. "Get all property keys in the current buffer.
  14818. When SPECIALS is non-nil, also list the special properties that
  14819. reflect things like tags and TODO state.
  14820. When DEFAULTS is non-nil, also include properties that has
  14821. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14822. DESCRIPTION, LOCATION, and LOGGING and others.
  14823. When COLUMNS in non-nil, also include property names given in
  14824. COLUMN formats in the current buffer.
  14825. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14826. automatically performed, such drawers will be silently ignored."
  14827. (let ((case-fold-search t)
  14828. (props (append
  14829. (and specials org-special-properties)
  14830. (and defaults (cons org-effort-property org-default-properties))
  14831. nil)))
  14832. (org-with-wide-buffer
  14833. (goto-char (point-min))
  14834. (while (re-search-forward org-property-start-re nil t)
  14835. (let ((range (org-get-property-block)))
  14836. (catch 'skip
  14837. (unless range
  14838. (when (and (not ignore-malformed)
  14839. (not (org-before-first-heading-p))
  14840. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14841. (line-beginning-position))))
  14842. (org-get-property-block nil t))
  14843. (throw 'skip nil))
  14844. (goto-char (car range))
  14845. (let ((begin (car range))
  14846. (end (cdr range)))
  14847. ;; Make sure that found property block is not located
  14848. ;; before current point, as it would generate an infloop.
  14849. ;; It can happen, for example, in the following
  14850. ;; situation:
  14851. ;;
  14852. ;; * Headline
  14853. ;; :PROPERTIES:
  14854. ;; ...
  14855. ;; :END:
  14856. ;; *************** Inlinetask
  14857. ;; #+BEGIN_EXAMPLE
  14858. ;; :PROPERTIES:
  14859. ;; #+END_EXAMPLE
  14860. ;;
  14861. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14862. (while (< (point) end)
  14863. (let ((p (progn (looking-at org-property-re)
  14864. (match-string-no-properties 2))))
  14865. ;; Only add true property name, not extension symbol.
  14866. (push (if (not (string-match-p "\\+\\'" p)) p
  14867. (substring p 0 -1))
  14868. props))
  14869. (forward-line))))
  14870. (outline-next-heading)))
  14871. (when columns
  14872. (goto-char (point-min))
  14873. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14874. (let ((element (org-element-at-point)))
  14875. (when (memq (org-element-type element) '(keyword node-property))
  14876. (let ((value (org-element-property :value element))
  14877. (start 0))
  14878. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14879. (setq start (match-end 0))
  14880. (let ((p (match-string-no-properties 1 value)))
  14881. (unless (member-ignore-case p org-special-properties)
  14882. (push p props))))))))))
  14883. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14884. (defun org-property-values (key)
  14885. "List all non-nil values of property KEY in current buffer."
  14886. (org-with-wide-buffer
  14887. (goto-char (point-min))
  14888. (let ((case-fold-search t)
  14889. (re (org-re-property key))
  14890. values)
  14891. (while (re-search-forward re nil t)
  14892. (push (org-entry-get (point) key) values))
  14893. (delete-dups values))))
  14894. (defun org-insert-property-drawer ()
  14895. "Insert a property drawer into the current entry."
  14896. (org-with-wide-buffer
  14897. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14898. (org-back-to-heading t)
  14899. (org-with-limited-levels (org-back-to-heading t)))
  14900. (forward-line)
  14901. (when (looking-at-p org-planning-line-re) (forward-line))
  14902. (unless (looking-at-p org-property-drawer-re)
  14903. ;; Make sure we start editing a line from current entry, not from
  14904. ;; next one. It prevents extending text properties or overlays
  14905. ;; belonging to the latter.
  14906. (when (bolp) (backward-char))
  14907. (let ((begin (1+ (point)))
  14908. (inhibit-read-only t))
  14909. (insert "\n:PROPERTIES:\n:END:")
  14910. (when (eobp) (insert "\n"))
  14911. (org-indent-region begin (point))))))
  14912. (defun org-insert-drawer (&optional arg drawer)
  14913. "Insert a drawer at point.
  14914. When optional argument ARG is non-nil, insert a property drawer.
  14915. Optional argument DRAWER, when non-nil, is a string representing
  14916. drawer's name. Otherwise, the user is prompted for a name.
  14917. If a region is active, insert the drawer around that region
  14918. instead.
  14919. Point is left between drawer's boundaries."
  14920. (interactive "P")
  14921. (let* ((drawer (if arg "PROPERTIES"
  14922. (or drawer (read-from-minibuffer "Drawer: ")))))
  14923. (cond
  14924. ;; With C-u, fall back on `org-insert-property-drawer'
  14925. (arg (org-insert-property-drawer))
  14926. ;; Check validity of suggested drawer's name.
  14927. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14928. (user-error "Invalid drawer name"))
  14929. ;; With an active region, insert a drawer at point.
  14930. ((not (org-region-active-p))
  14931. (progn
  14932. (unless (bolp) (insert "\n"))
  14933. (insert (format ":%s:\n\n:END:\n" drawer))
  14934. (forward-line -2)))
  14935. ;; Otherwise, insert the drawer at point
  14936. (t
  14937. (let ((rbeg (region-beginning))
  14938. (rend (copy-marker (region-end))))
  14939. (unwind-protect
  14940. (progn
  14941. (goto-char rbeg)
  14942. (beginning-of-line)
  14943. (when (save-excursion
  14944. (re-search-forward org-outline-regexp-bol rend t))
  14945. (user-error "Drawers cannot contain headlines"))
  14946. ;; Position point at the beginning of the first
  14947. ;; non-blank line in region. Insert drawer's opening
  14948. ;; there, then indent it.
  14949. (org-skip-whitespace)
  14950. (beginning-of-line)
  14951. (insert ":" drawer ":\n")
  14952. (forward-line -1)
  14953. (indent-for-tab-command)
  14954. ;; Move point to the beginning of the first blank line
  14955. ;; after the last non-blank line in region. Insert
  14956. ;; drawer's closing, then indent it.
  14957. (goto-char rend)
  14958. (skip-chars-backward " \r\t\n")
  14959. (insert "\n:END:")
  14960. (deactivate-mark t)
  14961. (indent-for-tab-command)
  14962. (unless (eolp) (insert "\n")))
  14963. ;; Clear marker, whatever the outcome of insertion is.
  14964. (set-marker rend nil)))))))
  14965. (defvar org-property-set-functions-alist nil
  14966. "Property set function alist.
  14967. Each entry should have the following format:
  14968. (PROPERTY . READ-FUNCTION)
  14969. The read function will be called with the same argument as
  14970. `org-completing-read'.")
  14971. (defun org-set-property-function (property)
  14972. "Get the function that should be used to set PROPERTY.
  14973. This is computed according to `org-property-set-functions-alist'."
  14974. (or (cdr (assoc property org-property-set-functions-alist))
  14975. 'org-completing-read))
  14976. (defun org-read-property-value (property)
  14977. "Read PROPERTY value from user."
  14978. (let* ((completion-ignore-case t)
  14979. (allowed (org-property-get-allowed-values nil property 'table))
  14980. (cur (org-entry-get nil property))
  14981. (prompt (concat property " value"
  14982. (if (and cur (string-match "\\S-" cur))
  14983. (concat " [" cur "]") "") ": "))
  14984. (set-function (org-set-property-function property))
  14985. (val (if allowed
  14986. (funcall set-function prompt allowed nil
  14987. (not (get-text-property 0 'org-unrestricted
  14988. (caar allowed))))
  14989. (funcall set-function prompt
  14990. (mapcar 'list (org-property-values property))
  14991. nil nil "" nil cur))))
  14992. (org-trim val)))
  14993. (defvar org-last-set-property nil)
  14994. (defvar org-last-set-property-value nil)
  14995. (defun org-read-property-name ()
  14996. "Read a property name."
  14997. (let ((completion-ignore-case t)
  14998. (default-prop (or (and (org-at-property-p)
  14999. (match-string-no-properties 2))
  15000. org-last-set-property)))
  15001. (org-completing-read
  15002. (concat "Property"
  15003. (if default-prop (concat " [" default-prop "]") "")
  15004. ": ")
  15005. (mapcar #'list (org-buffer-property-keys nil t t))
  15006. nil nil nil nil default-prop)))
  15007. (defun org-set-property-and-value (use-last)
  15008. "Allow to set [PROPERTY]: [value] direction from prompt.
  15009. When use-default, don't even ask, just use the last
  15010. \"[PROPERTY]: [value]\" string from the history."
  15011. (interactive "P")
  15012. (let* ((completion-ignore-case t)
  15013. (pv (or (and use-last org-last-set-property-value)
  15014. (org-completing-read
  15015. "Enter a \"[Property]: [value]\" pair: "
  15016. nil nil nil nil nil
  15017. org-last-set-property-value)))
  15018. prop val)
  15019. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  15020. (setq prop (match-string 1 pv)
  15021. val (match-string 2 pv))
  15022. (org-set-property prop val))))
  15023. (defun org-set-property (property value)
  15024. "In the current entry, set PROPERTY to VALUE.
  15025. When called interactively, this will prompt for a property name, offering
  15026. completion on existing and default properties. And then it will prompt
  15027. for a value, offering completion either on allowed values (via an inherited
  15028. xxx_ALL property) or on existing values in other instances of this property
  15029. in the current file.
  15030. Throw an error when trying to set a property with an invalid name."
  15031. (interactive (list nil nil))
  15032. (let ((property (or property (org-read-property-name))))
  15033. ;; `org-entry-put' also makes the following check, but this one
  15034. ;; avoids polluting `org-last-set-property' and
  15035. ;; `org-last-set-property-value' needlessly.
  15036. (unless (org--valid-property-p property)
  15037. (user-error "Invalid property name: \"%s\"" property))
  15038. (let ((value (or value (org-read-property-value property)))
  15039. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15040. (setq org-last-set-property property)
  15041. (setq org-last-set-property-value (concat property ": " value))
  15042. ;; Possibly postprocess the inserted value:
  15043. (when fn (setq value (funcall fn value)))
  15044. (unless (equal (org-entry-get nil property) value)
  15045. (org-entry-put nil property value)))))
  15046. (defun org-find-property (property &optional value)
  15047. "Find first entry in buffer that sets PROPERTY.
  15048. When optional argument VALUE is non-nil, only consider an entry
  15049. if it contains PROPERTY set to this value. If PROPERTY should be
  15050. explicitly set to nil, use string \"nil\" for VALUE.
  15051. Return position where the entry begins, or nil if there is no
  15052. such entry. If narrowing is in effect, only search the visible
  15053. part of the buffer."
  15054. (save-excursion
  15055. (goto-char (point-min))
  15056. (let ((case-fold-search t)
  15057. (re (org-re-property property nil (not value) value)))
  15058. (catch 'exit
  15059. (while (re-search-forward re nil t)
  15060. (when (if value (org-at-property-p)
  15061. (org-entry-get (point) property nil t))
  15062. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15063. (defun org-delete-property (property)
  15064. "In the current entry, delete PROPERTY."
  15065. (interactive
  15066. (let* ((completion-ignore-case t)
  15067. (cat (org-entry-get (point) "CATEGORY"))
  15068. (props0 (org-entry-properties nil 'standard))
  15069. (props (if cat props0
  15070. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15071. (prop (if (< 1 (length props))
  15072. (completing-read "Property: " props nil t)
  15073. (caar props))))
  15074. (list prop)))
  15075. (if (not property)
  15076. (message "No property to delete in this entry")
  15077. (org-entry-delete nil property)
  15078. (message "Property \"%s\" deleted" property)))
  15079. (defun org-delete-property-globally (property)
  15080. "Remove PROPERTY globally, from all entries.
  15081. This function ignores narrowing, if any."
  15082. (interactive
  15083. (let* ((completion-ignore-case t)
  15084. (prop (completing-read
  15085. "Globally remove property: "
  15086. (mapcar #'list (org-buffer-property-keys)))))
  15087. (list prop)))
  15088. (org-with-wide-buffer
  15089. (goto-char (point-min))
  15090. (let ((count 0)
  15091. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15092. (while (re-search-forward re nil t)
  15093. (when (org-entry-delete (point) property) (cl-incf count)))
  15094. (message "Property \"%s\" removed from %d entries" property count))))
  15095. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15096. (defun org-compute-property-at-point ()
  15097. "Compute the property at point.
  15098. This looks for an enclosing column format, extracts the operator and
  15099. then applies it to the property in the column format's scope."
  15100. (interactive)
  15101. (unless (org-at-property-p)
  15102. (user-error "Not at a property"))
  15103. (let ((prop (match-string-no-properties 2)))
  15104. (org-columns-get-format-and-top-level)
  15105. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15106. (user-error "No operator defined for property %s" prop))
  15107. (org-columns-compute prop)))
  15108. (defvar org-property-allowed-value-functions nil
  15109. "Hook for functions supplying allowed values for a specific property.
  15110. The functions must take a single argument, the name of the property, and
  15111. return a flat list of allowed values. If \":ETC\" is one of
  15112. the values, this means that these values are intended as defaults for
  15113. completion, but that other values should be allowed too.
  15114. The functions must return nil if they are not responsible for this
  15115. property.")
  15116. (defun org-property-get-allowed-values (pom property &optional table)
  15117. "Get allowed values for the property PROPERTY.
  15118. When TABLE is non-nil, return an alist that can directly be used for
  15119. completion."
  15120. (let (vals)
  15121. (cond
  15122. ((equal property "TODO")
  15123. (setq vals (org-with-point-at pom
  15124. (append org-todo-keywords-1 '("")))))
  15125. ((equal property "PRIORITY")
  15126. (let ((n org-lowest-priority))
  15127. (while (>= n org-highest-priority)
  15128. (push (char-to-string n) vals)
  15129. (setq n (1- n)))))
  15130. ((equal property "CATEGORY"))
  15131. ((member property org-special-properties))
  15132. ((setq vals (run-hook-with-args-until-success
  15133. 'org-property-allowed-value-functions property)))
  15134. (t
  15135. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15136. (when (and vals (string-match "\\S-" vals))
  15137. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15138. (setq vals (mapcar (lambda (x)
  15139. (cond ((stringp x) x)
  15140. ((numberp x) (number-to-string x))
  15141. ((symbolp x) (symbol-name x))
  15142. (t "???")))
  15143. vals)))))
  15144. (when (member ":ETC" vals)
  15145. (setq vals (remove ":ETC" vals))
  15146. (org-add-props (car vals) '(org-unrestricted t)))
  15147. (if table (mapcar 'list vals) vals)))
  15148. (defun org-property-previous-allowed-value (&optional _previous)
  15149. "Switch to the next allowed value for this property."
  15150. (interactive)
  15151. (org-property-next-allowed-value t))
  15152. (defun org-property-next-allowed-value (&optional previous)
  15153. "Switch to the next allowed value for this property."
  15154. (interactive)
  15155. (unless (org-at-property-p)
  15156. (user-error "Not at a property"))
  15157. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15158. (key (match-string 2))
  15159. (value (match-string 3))
  15160. (allowed (or (org-property-get-allowed-values (point) key)
  15161. (and (member value '("[ ]" "[-]" "[X]"))
  15162. '("[ ]" "[X]"))))
  15163. (heading (save-match-data (nth 4 (org-heading-components))))
  15164. nval)
  15165. (unless allowed
  15166. (user-error "Allowed values for this property have not been defined"))
  15167. (when previous (setq allowed (reverse allowed)))
  15168. (when (member value allowed)
  15169. (setq nval (car (cdr (member value allowed)))))
  15170. (setq nval (or nval (car allowed)))
  15171. (when (equal nval value)
  15172. (user-error "Only one allowed value for this property"))
  15173. (org-at-property-p)
  15174. (replace-match (concat " :" key ": " nval) t t)
  15175. (org-indent-line)
  15176. (beginning-of-line 1)
  15177. (skip-chars-forward " \t")
  15178. (when (equal prop org-effort-property)
  15179. (org-refresh-property
  15180. '((effort . identity)
  15181. (effort-minutes . org-duration-string-to-minutes))
  15182. nval)
  15183. (when (string= org-clock-current-task heading)
  15184. (setq org-clock-effort nval)
  15185. (org-clock-update-mode-line)))
  15186. (run-hook-with-args 'org-property-changed-functions key nval)))
  15187. (defun org-find-olp (path &optional this-buffer)
  15188. "Return a marker pointing to the entry at outline path OLP.
  15189. If anything goes wrong, throw an error.
  15190. You can wrap this call to catch the error like this:
  15191. (condition-case msg
  15192. (org-mobile-locate-entry (match-string 4))
  15193. (error (nth 1 msg)))
  15194. The return value will then be either a string with the error message,
  15195. or a marker if everything is OK.
  15196. If THIS-BUFFER is set, the outline path does not contain a file,
  15197. only headings."
  15198. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15199. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15200. (level 1)
  15201. (lmin 1)
  15202. (lmax 1)
  15203. end found flevel)
  15204. (unless buffer (error "File not found :%s" file))
  15205. (with-current-buffer buffer
  15206. (org-with-wide-buffer
  15207. (goto-char (point-min))
  15208. (dolist (heading path)
  15209. (let ((re (format org-complex-heading-regexp-format
  15210. (regexp-quote heading)))
  15211. (cnt 0))
  15212. (while (re-search-forward re end t)
  15213. (setq level (- (match-end 1) (match-beginning 1)))
  15214. (when (and (>= level lmin) (<= level lmax))
  15215. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15216. (when (= cnt 0)
  15217. (error "Heading not found on level %d: %s" lmax heading))
  15218. (when (> cnt 1)
  15219. (error "Heading not unique on level %d: %s" lmax heading))
  15220. (goto-char found)
  15221. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15222. (setq end (save-excursion (org-end-of-subtree t t)))))
  15223. (when (org-at-heading-p)
  15224. (point-marker))))))
  15225. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15226. "Find node HEADING in BUFFER.
  15227. Return a marker to the heading if it was found, or nil if not.
  15228. If POS-ONLY is set, return just the position instead of a marker.
  15229. The heading text must match exact, but it may have a TODO keyword,
  15230. a priority cookie and tags in the standard locations."
  15231. (with-current-buffer (or buffer (current-buffer))
  15232. (org-with-wide-buffer
  15233. (goto-char (point-min))
  15234. (let (case-fold-search)
  15235. (when (re-search-forward
  15236. (format org-complex-heading-regexp-format
  15237. (regexp-quote heading)) nil t)
  15238. (if pos-only
  15239. (match-beginning 0)
  15240. (move-marker (make-marker) (match-beginning 0))))))))
  15241. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15242. "Find Org node headline HEADING in all .org files in directory DIR.
  15243. When the target headline is found, return a marker to this location."
  15244. (let ((files (directory-files (or dir default-directory)
  15245. t "\\`[^.#].*\\.org\\'"))
  15246. visiting m buffer)
  15247. (catch 'found
  15248. (dolist (file files)
  15249. (message "trying %s" file)
  15250. (setq visiting (org-find-base-buffer-visiting file))
  15251. (setq buffer (or visiting (find-file-noselect file)))
  15252. (setq m (org-find-exact-headline-in-buffer
  15253. heading buffer))
  15254. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15255. (and m (throw 'found m))))))
  15256. (defun org-find-entry-with-id (ident)
  15257. "Locate the entry that contains the ID property with exact value IDENT.
  15258. IDENT can be a string, a symbol or a number, this function will search for
  15259. the string representation of it.
  15260. Return the position where this entry starts, or nil if there is no such entry."
  15261. (interactive "sID: ")
  15262. (let ((id (cond
  15263. ((stringp ident) ident)
  15264. ((symbolp ident) (symbol-name ident))
  15265. ((numberp ident) (number-to-string ident))
  15266. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15267. (org-with-wide-buffer (org-find-property "ID" id))))
  15268. ;;;; Timestamps
  15269. (defvar org-last-changed-timestamp nil)
  15270. (defvar org-last-inserted-timestamp nil
  15271. "The last time stamp inserted with `org-insert-time-stamp'.")
  15272. (defvar org-ts-what) ; dynamically scoped parameter
  15273. (defun org-time-stamp (arg &optional inactive)
  15274. "Prompt for a date/time and insert a time stamp.
  15275. If the user specifies a time like HH:MM or if this command is
  15276. called with at least one prefix argument, the time stamp contains
  15277. the date and the time. Otherwise, only the date is included.
  15278. All parts of a date not specified by the user are filled in from
  15279. the timestamp at point, if any, or the current date/time
  15280. otherwise.
  15281. If there is already a timestamp at the cursor, it is replaced.
  15282. With two universal prefix arguments, insert an active timestamp
  15283. with the current time without prompting the user.
  15284. When called from lisp, the timestamp is inactive if INACTIVE is
  15285. non-nil."
  15286. (interactive "P")
  15287. (let* ((ts (cond
  15288. ((org-at-date-range-p t)
  15289. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15290. ((org-at-timestamp-p t) (match-string 0))))
  15291. ;; Default time is either the timestamp at point or today.
  15292. ;; When entering a range, only the range start is considered.
  15293. (default-time (if (not ts) (current-time)
  15294. (apply #'encode-time (org-parse-time-string ts))))
  15295. (default-input (and ts (org-get-compact-tod ts)))
  15296. (repeater (and ts
  15297. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15298. (match-string 0 ts)))
  15299. org-time-was-given
  15300. org-end-time-was-given
  15301. (time
  15302. (and (if (equal arg '(16)) (current-time)
  15303. ;; Preserve `this-command' and `last-command'.
  15304. (let ((this-command this-command)
  15305. (last-command last-command))
  15306. (org-read-date
  15307. arg 'totime nil nil default-time default-input
  15308. inactive))))))
  15309. (cond
  15310. ((and ts
  15311. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15312. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15313. (insert "--")
  15314. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15315. (ts
  15316. ;; Make sure we're on a timestamp. When in the middle of a date
  15317. ;; range, move arbitrarily to range end.
  15318. (unless (org-at-timestamp-p t)
  15319. (skip-chars-forward "-")
  15320. (org-at-timestamp-p t))
  15321. (replace-match "")
  15322. (setq org-last-changed-timestamp
  15323. (org-insert-time-stamp
  15324. time (or org-time-was-given arg)
  15325. inactive nil nil (list org-end-time-was-given)))
  15326. (when repeater
  15327. (backward-char)
  15328. (insert " " repeater)
  15329. (setq org-last-changed-timestamp
  15330. (concat (substring org-last-inserted-timestamp 0 -1)
  15331. " " repeater ">")))
  15332. (message "Timestamp updated"))
  15333. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15334. (t (org-insert-time-stamp
  15335. time (or org-time-was-given arg) inactive nil nil
  15336. (list org-end-time-was-given))))))
  15337. ;; FIXME: can we use this for something else, like computing time differences?
  15338. (defun org-get-compact-tod (s)
  15339. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15340. (let* ((t1 (match-string 1 s))
  15341. (h1 (string-to-number (match-string 2 s)))
  15342. (m1 (string-to-number (match-string 3 s)))
  15343. (t2 (and (match-end 4) (match-string 5 s)))
  15344. (h2 (and t2 (string-to-number (match-string 6 s))))
  15345. (m2 (and t2 (string-to-number (match-string 7 s))))
  15346. dh dm)
  15347. (if (not t2)
  15348. t1
  15349. (setq dh (- h2 h1) dm (- m2 m1))
  15350. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15351. (concat t1 "+" (number-to-string dh)
  15352. (and (/= 0 dm) (format ":%02d" dm)))))))
  15353. (defun org-time-stamp-inactive (&optional arg)
  15354. "Insert an inactive time stamp.
  15355. An inactive time stamp is enclosed in square brackets instead of angle
  15356. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15357. does not link to the calendar and cannot be changed with the S-cursor keys.
  15358. So these are more for recording a certain time/date."
  15359. (interactive "P")
  15360. (org-time-stamp arg 'inactive))
  15361. (defvar org-date-ovl (make-overlay 1 1))
  15362. (overlay-put org-date-ovl 'face 'org-date-selected)
  15363. (delete-overlay org-date-ovl)
  15364. (defvar org-ans1) ; dynamically scoped parameter
  15365. (defvar org-ans2) ; dynamically scoped parameter
  15366. (defvar org-plain-time-of-day-regexp) ; defined below
  15367. (defvar org-overriding-default-time nil) ; dynamically scoped
  15368. (defvar org-read-date-overlay nil)
  15369. (defvar org-dcst nil) ; dynamically scoped
  15370. (defvar org-read-date-history nil)
  15371. (defvar org-read-date-final-answer nil)
  15372. (defvar org-read-date-analyze-futurep nil)
  15373. (defvar org-read-date-analyze-forced-year nil)
  15374. (defvar org-read-date-inactive)
  15375. (defvar org-read-date-minibuffer-local-map
  15376. (let* ((map (make-sparse-keymap)))
  15377. (set-keymap-parent map minibuffer-local-map)
  15378. (org-defkey map (kbd ".")
  15379. (lambda () (interactive)
  15380. ;; Are we at the beginning of the prompt?
  15381. (if (looking-back "^[^:]+: "
  15382. (let ((inhibit-field-text-motion t))
  15383. (line-beginning-position)))
  15384. (org-eval-in-calendar '(calendar-goto-today))
  15385. (insert "."))))
  15386. (org-defkey map (kbd "C-.")
  15387. (lambda () (interactive)
  15388. (org-eval-in-calendar '(calendar-goto-today))))
  15389. (org-defkey map [(meta shift left)]
  15390. (lambda () (interactive)
  15391. (org-eval-in-calendar '(calendar-backward-month 1))))
  15392. (org-defkey map [(meta shift right)]
  15393. (lambda () (interactive)
  15394. (org-eval-in-calendar '(calendar-forward-month 1))))
  15395. (org-defkey map [(meta shift up)]
  15396. (lambda () (interactive)
  15397. (org-eval-in-calendar '(calendar-backward-year 1))))
  15398. (org-defkey map [(meta shift down)]
  15399. (lambda () (interactive)
  15400. (org-eval-in-calendar '(calendar-forward-year 1))))
  15401. (org-defkey map [?\e (shift left)]
  15402. (lambda () (interactive)
  15403. (org-eval-in-calendar '(calendar-backward-month 1))))
  15404. (org-defkey map [?\e (shift right)]
  15405. (lambda () (interactive)
  15406. (org-eval-in-calendar '(calendar-forward-month 1))))
  15407. (org-defkey map [?\e (shift up)]
  15408. (lambda () (interactive)
  15409. (org-eval-in-calendar '(calendar-backward-year 1))))
  15410. (org-defkey map [?\e (shift down)]
  15411. (lambda () (interactive)
  15412. (org-eval-in-calendar '(calendar-forward-year 1))))
  15413. (org-defkey map [(shift up)]
  15414. (lambda () (interactive)
  15415. (org-eval-in-calendar '(calendar-backward-week 1))))
  15416. (org-defkey map [(shift down)]
  15417. (lambda () (interactive)
  15418. (org-eval-in-calendar '(calendar-forward-week 1))))
  15419. (org-defkey map [(shift left)]
  15420. (lambda () (interactive)
  15421. (org-eval-in-calendar '(calendar-backward-day 1))))
  15422. (org-defkey map [(shift right)]
  15423. (lambda () (interactive)
  15424. (org-eval-in-calendar '(calendar-forward-day 1))))
  15425. (org-defkey map "!"
  15426. (lambda () (interactive)
  15427. (org-eval-in-calendar '(diary-view-entries))
  15428. (message "")))
  15429. (org-defkey map ">"
  15430. (lambda () (interactive)
  15431. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15432. (org-defkey map "<"
  15433. (lambda () (interactive)
  15434. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15435. (org-defkey map "\C-v"
  15436. (lambda () (interactive)
  15437. (org-eval-in-calendar
  15438. '(calendar-scroll-left-three-months 1))))
  15439. (org-defkey map "\M-v"
  15440. (lambda () (interactive)
  15441. (org-eval-in-calendar
  15442. '(calendar-scroll-right-three-months 1))))
  15443. map)
  15444. "Keymap for minibuffer commands when using `org-read-date'.")
  15445. (defvar org-def)
  15446. (defvar org-defdecode)
  15447. (defvar org-with-time)
  15448. (defvar calendar-setup) ; Dynamically scoped.
  15449. (defun org-read-date (&optional with-time to-time from-string prompt
  15450. default-time default-input inactive)
  15451. "Read a date, possibly a time, and make things smooth for the user.
  15452. The prompt will suggest to enter an ISO date, but you can also enter anything
  15453. which will at least partially be understood by `parse-time-string'.
  15454. Unrecognized parts of the date will default to the current day, month, year,
  15455. hour and minute. If this command is called to replace a timestamp at point,
  15456. or to enter the second timestamp of a range, the default time is taken
  15457. from the existing stamp. Furthermore, the command prefers the future,
  15458. so if you are giving a date where the year is not given, and the day-month
  15459. combination is already past in the current year, it will assume you
  15460. mean next year. For details, see the manual. A few examples:
  15461. 3-2-5 --> 2003-02-05
  15462. feb 15 --> currentyear-02-15
  15463. 2/15 --> currentyear-02-15
  15464. sep 12 9 --> 2009-09-12
  15465. 12:45 --> today 12:45
  15466. 22 sept 0:34 --> currentyear-09-22 0:34
  15467. 12 --> currentyear-currentmonth-12
  15468. Fri --> nearest Friday after today
  15469. -Tue --> last Tuesday
  15470. etc.
  15471. Furthermore you can specify a relative date by giving, as the *first* thing
  15472. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15473. change in days weeks, months, years.
  15474. With a single plus or minus, the date is relative to today. With a double
  15475. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15476. +4d --> four days from today
  15477. +4 --> same as above
  15478. +2w --> two weeks from today
  15479. ++5 --> five days from default date
  15480. The function understands only English month and weekday abbreviations.
  15481. While prompting, a calendar is popped up - you can also select the
  15482. date with the mouse (button 1). The calendar shows a period of three
  15483. months. To scroll it to other months, use the keys `>' and `<'.
  15484. If you don't like the calendar, turn it off with
  15485. (setq org-read-date-popup-calendar nil)
  15486. With optional argument TO-TIME, the date will immediately be converted
  15487. to an internal time.
  15488. With an optional argument WITH-TIME, the prompt will suggest to
  15489. also insert a time. Note that when WITH-TIME is not set, you can
  15490. still enter a time, and this function will inform the calling routine
  15491. about this change. The calling routine may then choose to change the
  15492. format used to insert the time stamp into the buffer to include the time.
  15493. With optional argument FROM-STRING, read from this string instead from
  15494. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15495. the time/date that is used for everything that is not specified by the
  15496. user."
  15497. (require 'parse-time)
  15498. (let* ((org-with-time with-time)
  15499. (org-time-stamp-rounding-minutes
  15500. (if (equal org-with-time '(16))
  15501. '(0 0)
  15502. org-time-stamp-rounding-minutes))
  15503. (org-dcst org-display-custom-times)
  15504. (ct (org-current-time))
  15505. (org-def (or org-overriding-default-time default-time ct))
  15506. (org-defdecode (decode-time org-def))
  15507. (cur-frame (selected-frame))
  15508. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15509. (calendar-setup
  15510. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15511. (calendar-move-hook nil)
  15512. (calendar-view-diary-initially-flag nil)
  15513. (calendar-view-holidays-initially-flag nil)
  15514. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15515. ;; Rationalize `org-def' and `org-defdecode', if required.
  15516. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15517. (setf (nth 2 org-defdecode) -1)
  15518. (setf (nth 1 org-defdecode) 59)
  15519. (setq org-def (apply #'encode-time org-defdecode))
  15520. (setq org-defdecode (decode-time org-def)))
  15521. (let* ((timestr (format-time-string
  15522. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15523. org-def))
  15524. (prompt (concat (if prompt (concat prompt " ") "")
  15525. (format "Date+time [%s]: " timestr))))
  15526. (cond
  15527. (from-string (setq ans from-string))
  15528. (org-read-date-popup-calendar
  15529. (save-excursion
  15530. (save-window-excursion
  15531. (calendar)
  15532. (when (eq calendar-setup 'calendar-only)
  15533. (setq cal-frame
  15534. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15535. (select-frame cal-frame))
  15536. (org-eval-in-calendar '(setq cursor-type nil) t)
  15537. (unwind-protect
  15538. (progn
  15539. (calendar-forward-day (- (time-to-days org-def)
  15540. (calendar-absolute-from-gregorian
  15541. (calendar-current-date))))
  15542. (org-eval-in-calendar nil t)
  15543. (let* ((old-map (current-local-map))
  15544. (map (copy-keymap calendar-mode-map))
  15545. (minibuffer-local-map
  15546. (copy-keymap org-read-date-minibuffer-local-map)))
  15547. (org-defkey map (kbd "RET") 'org-calendar-select)
  15548. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15549. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15550. (unwind-protect
  15551. (progn
  15552. (use-local-map map)
  15553. (setq org-read-date-inactive inactive)
  15554. (add-hook 'post-command-hook 'org-read-date-display)
  15555. (setq org-ans0
  15556. (read-string prompt
  15557. default-input
  15558. 'org-read-date-history
  15559. nil))
  15560. ;; org-ans0: from prompt
  15561. ;; org-ans1: from mouse click
  15562. ;; org-ans2: from calendar motion
  15563. (setq ans
  15564. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15565. (remove-hook 'post-command-hook 'org-read-date-display)
  15566. (use-local-map old-map)
  15567. (when org-read-date-overlay
  15568. (delete-overlay org-read-date-overlay)
  15569. (setq org-read-date-overlay nil)))))
  15570. (bury-buffer "*Calendar*")
  15571. (when cal-frame
  15572. (delete-frame cal-frame)
  15573. (select-frame-set-input-focus cur-frame))))))
  15574. (t ; Naked prompt only
  15575. (unwind-protect
  15576. (setq ans (read-string prompt default-input
  15577. 'org-read-date-history timestr))
  15578. (when org-read-date-overlay
  15579. (delete-overlay org-read-date-overlay)
  15580. (setq org-read-date-overlay nil))))))
  15581. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15582. (when org-read-date-analyze-forced-year
  15583. (message "Year was forced into %s"
  15584. (if org-read-date-force-compatible-dates
  15585. "compatible range (1970-2037)"
  15586. "range representable on this machine"))
  15587. (ding))
  15588. ;; One round trip to get rid of 34th of August and stuff like that....
  15589. (setq final (decode-time (apply 'encode-time final)))
  15590. (setq org-read-date-final-answer ans)
  15591. (if to-time
  15592. (apply 'encode-time final)
  15593. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15594. (format "%04d-%02d-%02d %02d:%02d"
  15595. (nth 5 final) (nth 4 final) (nth 3 final)
  15596. (nth 2 final) (nth 1 final))
  15597. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15598. (defun org-read-date-display ()
  15599. "Display the current date prompt interpretation in the minibuffer."
  15600. (when org-read-date-display-live
  15601. (when org-read-date-overlay
  15602. (delete-overlay org-read-date-overlay))
  15603. (when (minibufferp (current-buffer))
  15604. (save-excursion
  15605. (end-of-line 1)
  15606. (while (not (equal (buffer-substring
  15607. (max (point-min) (- (point) 4)) (point))
  15608. " "))
  15609. (insert " ")))
  15610. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15611. " " (or org-ans1 org-ans2)))
  15612. (org-end-time-was-given nil)
  15613. (f (org-read-date-analyze ans org-def org-defdecode))
  15614. (fmts (if org-dcst
  15615. org-time-stamp-custom-formats
  15616. org-time-stamp-formats))
  15617. (fmt (if (or org-with-time
  15618. (and (boundp 'org-time-was-given) org-time-was-given))
  15619. (cdr fmts)
  15620. (car fmts)))
  15621. (txt (format-time-string fmt (apply 'encode-time f)))
  15622. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15623. (txt (concat "=> " txt)))
  15624. (when (and org-end-time-was-given
  15625. (string-match org-plain-time-of-day-regexp txt))
  15626. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15627. org-end-time-was-given
  15628. (substring txt (match-end 0)))))
  15629. (when org-read-date-analyze-futurep
  15630. (setq txt (concat txt " (=>F)")))
  15631. (setq org-read-date-overlay
  15632. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15633. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15634. (defun org-read-date-analyze (ans def defdecode)
  15635. "Analyze the combined answer of the date prompt."
  15636. ;; FIXME: cleanup and comment
  15637. ;; Pass `current-time' result to `decode-time' (instead of calling
  15638. ;; without arguments) so that only `current-time' has to be
  15639. ;; overriden in tests.
  15640. (let ((org-def def)
  15641. (org-defdecode defdecode)
  15642. (nowdecode (decode-time (current-time)))
  15643. delta deltan deltaw deltadef year month day
  15644. hour minute second wday pm h2 m2 tl wday1
  15645. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15646. (setq org-read-date-analyze-futurep nil
  15647. org-read-date-analyze-forced-year nil)
  15648. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15649. (setq ans "+0"))
  15650. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15651. (setq ans (replace-match "" t t ans)
  15652. deltan (car delta)
  15653. deltaw (nth 1 delta)
  15654. deltadef (nth 2 delta)))
  15655. ;; Check if there is an iso week date in there. If yes, store the
  15656. ;; info and postpone interpreting it until the rest of the parsing
  15657. ;; is done.
  15658. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15659. (setq iso-year (when (match-end 1)
  15660. (org-small-year-to-year
  15661. (string-to-number (match-string 1 ans))))
  15662. iso-weekday (when (match-end 3)
  15663. (string-to-number (match-string 3 ans)))
  15664. iso-week (string-to-number (match-string 2 ans)))
  15665. (setq ans (replace-match "" t t ans)))
  15666. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15667. (when (string-match
  15668. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15669. (setq year (if (match-end 2)
  15670. (string-to-number (match-string 2 ans))
  15671. (progn (setq kill-year t)
  15672. (string-to-number (format-time-string "%Y"))))
  15673. month (string-to-number (match-string 3 ans))
  15674. day (string-to-number (match-string 4 ans)))
  15675. (setq year (org-small-year-to-year year))
  15676. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15677. t nil ans)))
  15678. ;; Help matching dotted european dates
  15679. (when (string-match
  15680. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15681. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15682. (setq kill-year t)
  15683. (string-to-number (format-time-string "%Y")))
  15684. day (string-to-number (match-string 1 ans))
  15685. month (string-to-number (match-string 2 ans))
  15686. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15687. t nil ans)))
  15688. ;; Help matching american dates, like 5/30 or 5/30/7
  15689. (when (string-match
  15690. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15691. (setq year (if (match-end 4)
  15692. (string-to-number (match-string 4 ans))
  15693. (progn (setq kill-year t)
  15694. (string-to-number (format-time-string "%Y"))))
  15695. month (string-to-number (match-string 1 ans))
  15696. day (string-to-number (match-string 2 ans)))
  15697. (setq year (org-small-year-to-year year))
  15698. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15699. t nil ans)))
  15700. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15701. ;; If there is a time with am/pm, and *no* time without it, we convert
  15702. ;; so that matching will be successful.
  15703. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15704. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15705. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15706. (setq hour (string-to-number (match-string 1 ans))
  15707. minute (if (match-end 3)
  15708. (string-to-number (match-string 3 ans))
  15709. 0)
  15710. pm (equal ?p
  15711. (string-to-char (downcase (match-string 4 ans)))))
  15712. (if (and (= hour 12) (not pm))
  15713. (setq hour 0)
  15714. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15715. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15716. t t ans))))
  15717. ;; Check if a time range is given as a duration
  15718. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15719. (setq hour (string-to-number (match-string 1 ans))
  15720. h2 (+ hour (string-to-number (match-string 3 ans)))
  15721. minute (string-to-number (match-string 2 ans))
  15722. m2 (+ minute (if (match-end 5) (string-to-number
  15723. (match-string 5 ans))0)))
  15724. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15725. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15726. t t ans)))
  15727. ;; Check if there is a time range
  15728. (when (boundp 'org-end-time-was-given)
  15729. (setq org-time-was-given nil)
  15730. (when (and (string-match org-plain-time-of-day-regexp ans)
  15731. (match-end 8))
  15732. (setq org-end-time-was-given (match-string 8 ans))
  15733. (setq ans (concat (substring ans 0 (match-beginning 7))
  15734. (substring ans (match-end 7))))))
  15735. (setq tl (parse-time-string ans)
  15736. day (or (nth 3 tl) (nth 3 org-defdecode))
  15737. month
  15738. (cond ((nth 4 tl))
  15739. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15740. ;; Day was specified. Make sure DAY+MONTH
  15741. ;; combination happens in the future.
  15742. ((nth 3 tl)
  15743. (setq futurep t)
  15744. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15745. (nth 4 nowdecode)))
  15746. (t (nth 4 org-defdecode)))
  15747. year
  15748. (cond ((and (not kill-year) (nth 5 tl)))
  15749. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15750. ;; Month was guessed in the future and is at least
  15751. ;; equal to NOWDECODE's. Fix year accordingly.
  15752. (futurep
  15753. (if (or (> month (nth 4 nowdecode))
  15754. (>= day (nth 3 nowdecode)))
  15755. (nth 5 nowdecode)
  15756. (1+ (nth 5 nowdecode))))
  15757. ;; Month was specified. Make sure MONTH+YEAR
  15758. ;; combination happens in the future.
  15759. ((nth 4 tl)
  15760. (setq futurep t)
  15761. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15762. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15763. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15764. (t (nth 5 nowdecode))))
  15765. (t (nth 5 org-defdecode)))
  15766. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15767. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15768. second (or (nth 0 tl) 0)
  15769. wday (nth 6 tl))
  15770. (when (and (eq org-read-date-prefer-future 'time)
  15771. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15772. (equal day (nth 3 nowdecode))
  15773. (equal month (nth 4 nowdecode))
  15774. (equal year (nth 5 nowdecode))
  15775. (nth 2 tl)
  15776. (or (< (nth 2 tl) (nth 2 nowdecode))
  15777. (and (= (nth 2 tl) (nth 2 nowdecode))
  15778. (nth 1 tl)
  15779. (< (nth 1 tl) (nth 1 nowdecode)))))
  15780. (setq day (1+ day)
  15781. futurep t))
  15782. ;; Special date definitions below
  15783. (cond
  15784. (iso-week
  15785. ;; There was an iso week
  15786. (require 'cal-iso)
  15787. (setq futurep nil)
  15788. (setq year (or iso-year year)
  15789. day (or iso-weekday wday 1)
  15790. wday nil ; to make sure that the trigger below does not match
  15791. iso-date (calendar-gregorian-from-absolute
  15792. (calendar-iso-to-absolute
  15793. (list iso-week day year))))
  15794. ; FIXME: Should we also push ISO weeks into the future?
  15795. ; (when (and org-read-date-prefer-future
  15796. ; (not iso-year)
  15797. ; (< (calendar-absolute-from-gregorian iso-date)
  15798. ; (time-to-days (current-time))))
  15799. ; (setq year (1+ year)
  15800. ; iso-date (calendar-gregorian-from-absolute
  15801. ; (calendar-iso-to-absolute
  15802. ; (list iso-week day year)))))
  15803. (setq month (car iso-date)
  15804. year (nth 2 iso-date)
  15805. day (nth 1 iso-date)))
  15806. (deltan
  15807. (setq futurep nil)
  15808. (unless deltadef
  15809. ;; Pass `current-time' result to `decode-time' (instead of
  15810. ;; calling without arguments) so that only `current-time' has
  15811. ;; to be overriden in tests.
  15812. (let ((now (decode-time (current-time))))
  15813. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15814. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15815. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15816. ((equal deltaw "m") (setq month (+ month deltan)))
  15817. ((equal deltaw "y") (setq year (+ year deltan)))))
  15818. ((and wday (not (nth 3 tl)))
  15819. ;; Weekday was given, but no day, so pick that day in the week
  15820. ;; on or after the derived date.
  15821. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15822. (unless (equal wday wday1)
  15823. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15824. (when (and (boundp 'org-time-was-given)
  15825. (nth 2 tl))
  15826. (setq org-time-was-given t))
  15827. (when (< year 100) (setq year (+ 2000 year)))
  15828. ;; Check of the date is representable
  15829. (if org-read-date-force-compatible-dates
  15830. (progn
  15831. (when (< year 1970)
  15832. (setq year 1970 org-read-date-analyze-forced-year t))
  15833. (when (> year 2037)
  15834. (setq year 2037 org-read-date-analyze-forced-year t)))
  15835. (condition-case nil
  15836. (ignore (encode-time second minute hour day month year))
  15837. (error
  15838. (setq year (nth 5 org-defdecode))
  15839. (setq org-read-date-analyze-forced-year t))))
  15840. (setq org-read-date-analyze-futurep futurep)
  15841. (list second minute hour day month year)))
  15842. (defvar parse-time-weekdays)
  15843. (defun org-read-date-get-relative (s today default)
  15844. "Check string S for special relative date string.
  15845. TODAY and DEFAULT are internal times, for today and for a default.
  15846. Return shift list (N what def-flag)
  15847. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15848. N is the number of WHATs to shift.
  15849. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15850. the DEFAULT date rather than TODAY."
  15851. (require 'parse-time)
  15852. (when (and
  15853. (string-match
  15854. (concat
  15855. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15856. "\\([0-9]+\\)?"
  15857. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15858. "\\([ \t]\\|$\\)") s)
  15859. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15860. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15861. (string-to-char (substring (match-string 1 s) -1))
  15862. ?+))
  15863. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15864. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15865. (what (if (match-end 3) (match-string 3 s) "d"))
  15866. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15867. (date (if rel default today))
  15868. (wday (nth 6 (decode-time date)))
  15869. delta)
  15870. (if wday1
  15871. (progn
  15872. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15873. (when (= delta 0) (setq delta 7))
  15874. (when (= dir ?-)
  15875. (setq delta (- delta 7))
  15876. (when (= delta 0) (setq delta -7)))
  15877. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15878. (list delta "d" rel))
  15879. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15880. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15881. "Turn a user-specified date into the internal representation.
  15882. The internal representation needed by the calendar is (month day year).
  15883. This is a wrapper to handle the brain-dead convention in calendar that
  15884. user function argument order change dependent on argument order."
  15885. (pcase calendar-date-style
  15886. (`american (list arg1 arg2 arg3))
  15887. (`european (list arg2 arg1 arg3))
  15888. (`iso (list arg2 arg3 arg1))))
  15889. (defun org-eval-in-calendar (form &optional keepdate)
  15890. "Eval FORM in the calendar window and return to current window.
  15891. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15892. (let ((sf (selected-frame))
  15893. (sw (selected-window)))
  15894. (select-window (get-buffer-window "*Calendar*" t))
  15895. (eval form)
  15896. (when (and (not keepdate) (calendar-cursor-to-date))
  15897. (let* ((date (calendar-cursor-to-date))
  15898. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15899. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15900. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15901. (select-window sw)
  15902. (select-frame-set-input-focus sf)))
  15903. (defun org-calendar-select ()
  15904. "Return to `org-read-date' with the date currently selected.
  15905. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15906. (interactive)
  15907. (when (calendar-cursor-to-date)
  15908. (let* ((date (calendar-cursor-to-date))
  15909. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15910. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15911. (when (active-minibuffer-window) (exit-minibuffer))))
  15912. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15913. "Insert a date stamp for the date given by the internal TIME.
  15914. See `format-time-string' for the format of TIME.
  15915. WITH-HM means use the stamp format that includes the time of the day.
  15916. INACTIVE means use square brackets instead of angular ones, so that the
  15917. stamp will not contribute to the agenda.
  15918. PRE and POST are optional strings to be inserted before and after the
  15919. stamp.
  15920. The command returns the inserted time stamp."
  15921. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15922. stamp)
  15923. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15924. (insert-before-markers (or pre ""))
  15925. (when (listp extra)
  15926. (setq extra (car extra))
  15927. (if (and (stringp extra)
  15928. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15929. (setq extra (format "-%02d:%02d"
  15930. (string-to-number (match-string 1 extra))
  15931. (string-to-number (match-string 2 extra))))
  15932. (setq extra nil)))
  15933. (when extra
  15934. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15935. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15936. (insert-before-markers (or post ""))
  15937. (setq org-last-inserted-timestamp stamp)))
  15938. (defun org-toggle-time-stamp-overlays ()
  15939. "Toggle the use of custom time stamp formats."
  15940. (interactive)
  15941. (setq org-display-custom-times (not org-display-custom-times))
  15942. (unless org-display-custom-times
  15943. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15944. (while (setq p (next-single-property-change p 'display))
  15945. (when (and (get-text-property p 'display)
  15946. (eq (get-text-property p 'face) 'org-date))
  15947. (remove-text-properties
  15948. p (setq p (next-single-property-change p 'display))
  15949. '(display t))))
  15950. (set-buffer-modified-p bmp)))
  15951. (org-restart-font-lock)
  15952. (setq org-table-may-need-update t)
  15953. (if org-display-custom-times
  15954. (message "Time stamps are overlaid with custom format")
  15955. (message "Time stamp overlays removed")))
  15956. (defun org-display-custom-time (beg end)
  15957. "Overlay modified time stamp format over timestamp between BEG and END."
  15958. (let* ((ts (buffer-substring beg end))
  15959. t1 w1 with-hm tf time str w2 (off 0))
  15960. (save-match-data
  15961. (setq t1 (org-parse-time-string ts t))
  15962. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15963. (setq off (- (match-end 0) (match-beginning 0)))))
  15964. (setq end (- end off))
  15965. (setq w1 (- end beg)
  15966. with-hm (and (nth 1 t1) (nth 2 t1))
  15967. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15968. time (org-fix-decoded-time t1)
  15969. str (org-add-props
  15970. (format-time-string
  15971. (substring tf 1 -1) (apply 'encode-time time))
  15972. nil 'mouse-face 'highlight)
  15973. w2 (length str))
  15974. (unless (= w2 w1)
  15975. (add-text-properties (1+ beg) (+ 2 beg)
  15976. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15977. (put-text-property beg end 'display str)))
  15978. (defun org-fix-decoded-time (time)
  15979. "Set 0 instead of nil for the first 6 elements of time.
  15980. Don't touch the rest."
  15981. (let ((n 0))
  15982. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15983. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15984. "Difference between TIMESTAMP-STRING and now in days.
  15985. If SECONDS is non-nil, return the difference in seconds."
  15986. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15987. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15988. (funcall fdiff (current-time)))))
  15989. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15990. "Is the time in TIMESTAMP-STRING close to the current date?"
  15991. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15992. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15993. (not (org-entry-is-done-p))))
  15994. (defun org-get-wdays (ts &optional delay zero-delay)
  15995. "Get the deadline lead time appropriate for timestring TS.
  15996. When DELAY is non-nil, get the delay time for scheduled items
  15997. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15998. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15999. don't try to find the delay cookie in the scheduled timestamp."
  16000. (let ((tv (if delay org-scheduled-delay-days
  16001. org-deadline-warning-days)))
  16002. (cond
  16003. ((or (and delay (< tv 0))
  16004. (and delay zero-delay (<= tv 0))
  16005. (and (not delay) (<= tv 0)))
  16006. ;; Enforce this value no matter what
  16007. (- tv))
  16008. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  16009. ;; lead time is specified.
  16010. (floor (* (string-to-number (match-string 1 ts))
  16011. (cdr (assoc (match-string 2 ts)
  16012. '(("d" . 1) ("w" . 7)
  16013. ("m" . 30.4) ("y" . 365.25)
  16014. ("h" . 0.041667)))))))
  16015. ;; go for the default.
  16016. (t tv))))
  16017. (defun org-calendar-select-mouse (ev)
  16018. "Return to `org-read-date' with the date currently selected.
  16019. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  16020. (interactive "e")
  16021. (mouse-set-point ev)
  16022. (when (calendar-cursor-to-date)
  16023. (let* ((date (calendar-cursor-to-date))
  16024. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  16025. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  16026. (when (active-minibuffer-window) (exit-minibuffer))))
  16027. (defun org-check-deadlines (ndays)
  16028. "Check if there are any deadlines due or past due.
  16029. A deadline is considered due if it happens within `org-deadline-warning-days'
  16030. days from today's date. If the deadline appears in an entry marked DONE,
  16031. it is not shown. A numeric prefix argument NDAYS can be used to test that
  16032. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  16033. are shown."
  16034. (interactive "P")
  16035. (let* ((org-warn-days
  16036. (cond
  16037. ((equal ndays '(4)) 100000)
  16038. (ndays (prefix-numeric-value ndays))
  16039. (t (abs org-deadline-warning-days))))
  16040. (case-fold-search nil)
  16041. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16042. (callback
  16043. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16044. (message "%d deadlines past-due or due within %d days"
  16045. (org-occur regexp nil callback)
  16046. org-warn-days)))
  16047. (defsubst org-re-timestamp (type)
  16048. "Return a regexp for timestamp TYPE.
  16049. Allowed values for TYPE are:
  16050. all: all timestamps
  16051. active: only active timestamps (<...>)
  16052. inactive: only inactive timestamps ([...])
  16053. scheduled: only scheduled timestamps
  16054. deadline: only deadline timestamps
  16055. closed: only closed time-stamps
  16056. When TYPE is nil, fall back on returning a regexp that matches
  16057. both scheduled and deadline timestamps."
  16058. (cl-case type
  16059. (all org-ts-regexp-both)
  16060. (active org-ts-regexp)
  16061. (inactive org-ts-regexp-inactive)
  16062. (scheduled org-scheduled-time-regexp)
  16063. (deadline org-deadline-time-regexp)
  16064. (closed org-closed-time-regexp)
  16065. (otherwise
  16066. (concat "\\<"
  16067. (regexp-opt (list org-deadline-string org-scheduled-string))
  16068. " *<\\([^>]+\\)>"))))
  16069. (defun org-check-before-date (d)
  16070. "Check if there are deadlines or scheduled entries before date D."
  16071. (interactive (list (org-read-date)))
  16072. (let* ((case-fold-search nil)
  16073. (regexp (org-re-timestamp org-ts-type))
  16074. (ts-type org-ts-type)
  16075. (callback
  16076. (lambda ()
  16077. (let ((match (match-string 1)))
  16078. (and (if (memq ts-type '(active inactive all))
  16079. (eq (org-element-type (save-excursion
  16080. (backward-char)
  16081. (org-element-context)))
  16082. 'timestamp)
  16083. (org-at-planning-p))
  16084. (time-less-p
  16085. (org-time-string-to-time match)
  16086. (org-time-string-to-time d)))))))
  16087. (message "%d entries before %s"
  16088. (org-occur regexp nil callback)
  16089. d)))
  16090. (defun org-check-after-date (d)
  16091. "Check if there are deadlines or scheduled entries after date D."
  16092. (interactive (list (org-read-date)))
  16093. (let* ((case-fold-search nil)
  16094. (regexp (org-re-timestamp org-ts-type))
  16095. (ts-type org-ts-type)
  16096. (callback
  16097. (lambda ()
  16098. (let ((match (match-string 1)))
  16099. (and (if (memq ts-type '(active inactive all))
  16100. (eq (org-element-type (save-excursion
  16101. (backward-char)
  16102. (org-element-context)))
  16103. 'timestamp)
  16104. (org-at-planning-p))
  16105. (not (time-less-p
  16106. (org-time-string-to-time match)
  16107. (org-time-string-to-time d))))))))
  16108. (message "%d entries after %s"
  16109. (org-occur regexp nil callback)
  16110. d)))
  16111. (defun org-check-dates-range (start-date end-date)
  16112. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16113. (interactive (list (org-read-date nil nil nil "Range starts")
  16114. (org-read-date nil nil nil "Range end")))
  16115. (let ((case-fold-search nil)
  16116. (regexp (org-re-timestamp org-ts-type))
  16117. (callback
  16118. (let ((type org-ts-type))
  16119. (lambda ()
  16120. (let ((match (match-string 1)))
  16121. (and
  16122. (if (memq type '(active inactive all))
  16123. (eq (org-element-type (save-excursion
  16124. (backward-char)
  16125. (org-element-context)))
  16126. 'timestamp)
  16127. (org-at-planning-p))
  16128. (not (time-less-p
  16129. (org-time-string-to-time match)
  16130. (org-time-string-to-time start-date)))
  16131. (time-less-p
  16132. (org-time-string-to-time match)
  16133. (org-time-string-to-time end-date))))))))
  16134. (message "%d entries between %s and %s"
  16135. (org-occur regexp nil callback) start-date end-date)))
  16136. (defun org-evaluate-time-range (&optional to-buffer)
  16137. "Evaluate a time range by computing the difference between start and end.
  16138. Normally the result is just printed in the echo area, but with prefix arg
  16139. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16140. If the time range is actually in a table, the result is inserted into the
  16141. next column.
  16142. For time difference computation, a year is assumed to be exactly 365
  16143. days in order to avoid rounding problems."
  16144. (interactive "P")
  16145. (or
  16146. (org-clock-update-time-maybe)
  16147. (save-excursion
  16148. (unless (org-at-date-range-p t)
  16149. (goto-char (point-at-bol))
  16150. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16151. (unless (org-at-date-range-p t)
  16152. (user-error "Not at a time-stamp range, and none found in current line")))
  16153. (let* ((ts1 (match-string 1))
  16154. (ts2 (match-string 2))
  16155. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16156. (match-end (match-end 0))
  16157. (time1 (org-time-string-to-time ts1))
  16158. (time2 (org-time-string-to-time ts2))
  16159. (t1 (float-time time1))
  16160. (t2 (float-time time2))
  16161. (diff (abs (- t2 t1)))
  16162. (negative (< (- t2 t1) 0))
  16163. ;; (ys (floor (* 365 24 60 60)))
  16164. (ds (* 24 60 60))
  16165. (hs (* 60 60))
  16166. (fy "%dy %dd %02d:%02d")
  16167. (fy1 "%dy %dd")
  16168. (fd "%dd %02d:%02d")
  16169. (fd1 "%dd")
  16170. (fh "%02d:%02d")
  16171. y d h m align)
  16172. (if havetime
  16173. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16174. y 0
  16175. d (floor (/ diff ds)) diff (mod diff ds)
  16176. h (floor (/ diff hs)) diff (mod diff hs)
  16177. m (floor (/ diff 60)))
  16178. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16179. y 0
  16180. d (floor (+ (/ diff ds) 0.5))
  16181. h 0 m 0))
  16182. (if (not to-buffer)
  16183. (message "%s" (org-make-tdiff-string y d h m))
  16184. (if (org-at-table-p)
  16185. (progn
  16186. (goto-char match-end)
  16187. (setq align t)
  16188. (and (looking-at " *|") (goto-char (match-end 0))))
  16189. (goto-char match-end))
  16190. (when (looking-at
  16191. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16192. (replace-match ""))
  16193. (when negative (insert " -"))
  16194. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16195. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16196. (insert " " (format fh h m))))
  16197. (when align (org-table-align))
  16198. (message "Time difference inserted")))))
  16199. (defun org-make-tdiff-string (y d h m)
  16200. (let ((fmt "")
  16201. (l nil))
  16202. (when (> y 0)
  16203. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16204. (push y l))
  16205. (when (> d 0)
  16206. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16207. (push d l))
  16208. (when (> h 0)
  16209. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16210. (push h l))
  16211. (when (> m 0)
  16212. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16213. (push m l))
  16214. (apply 'format fmt (nreverse l))))
  16215. (defun org-time-string-to-time (s &optional buffer pos)
  16216. "Convert a timestamp string into internal time."
  16217. (condition-case errdata
  16218. (apply 'encode-time (org-parse-time-string s))
  16219. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16220. s (if (not (and buffer pos))
  16221. ""
  16222. (format-message " at %d in buffer `%s'" pos buffer))
  16223. (cdr errdata)))))
  16224. (defun org-time-string-to-seconds (s)
  16225. "Convert a timestamp string to a number of seconds."
  16226. (float-time (org-time-string-to-time s)))
  16227. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16228. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16229. "Convert time stamp S to an absolute day number.
  16230. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16231. stamp, get the closest date to DAYNR. If PREFER is
  16232. `past' (respectively `future') return a date past (respectively
  16233. after) or equal to DAYNR.
  16234. POS is the location of time stamp S, as a buffer position in
  16235. BUFFER.
  16236. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16237. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16238. signalled."
  16239. (cond
  16240. ((string-match "\\`%%\\((.*)\\)" s)
  16241. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16242. ;; only able to match individual dates. If it fails, raise an
  16243. ;; error.
  16244. (if (and daynr
  16245. (org-diary-sexp-entry
  16246. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16247. daynr
  16248. (signal 'org-diary-sexp-no-match (list s))))
  16249. ((and daynr show-all) (org-closest-date s daynr prefer))
  16250. (t (time-to-days
  16251. (condition-case errdata
  16252. (apply #'encode-time (org-parse-time-string s))
  16253. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16254. s
  16255. (if (not (and buffer pos)) ""
  16256. (format-message " at %d in buffer `%s'" pos buffer))
  16257. (cdr errdata))))))))
  16258. (defun org-days-to-iso-week (days)
  16259. "Return the iso week number."
  16260. (require 'cal-iso)
  16261. (car (calendar-iso-from-absolute days)))
  16262. (defun org-small-year-to-year (year)
  16263. "Convert 2-digit years into 4-digit years.
  16264. YEAR is expanded into one of the 30 next years, if possible, or
  16265. into a past one. Any year larger than 99 is returned unchanged."
  16266. (if (>= year 100) year
  16267. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16268. (century (/ current 100))
  16269. (offset (- year (% current 100))))
  16270. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16271. ((> offset -70) (+ (* century 100) year))
  16272. (t (+ (* (1+ century) 100) year))))))
  16273. (defun org-time-from-absolute (d)
  16274. "Return the time corresponding to date D.
  16275. D may be an absolute day number, or a calendar-type list (month day year)."
  16276. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16277. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16278. (defvar org-agenda-current-date)
  16279. (defun org-calendar-holiday ()
  16280. "List of holidays, for Diary display in Org mode."
  16281. (require 'holidays)
  16282. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16283. (and hl (mapconcat #'identity hl "; "))))
  16284. (defun org-diary-sexp-entry (sexp entry d)
  16285. "Process a SEXP diary ENTRY for date D."
  16286. (require 'diary-lib)
  16287. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16288. ;; dynamically.
  16289. (let* ((sexp `(let ((entry ,entry)
  16290. (date ',d))
  16291. ,(car (read-from-string sexp))))
  16292. (result (if calendar-debug-sexp (eval sexp)
  16293. (condition-case nil
  16294. (eval sexp)
  16295. (error
  16296. (beep)
  16297. (message "Bad sexp at line %d in %s: %s"
  16298. (org-current-line)
  16299. (buffer-file-name) sexp)
  16300. (sleep-for 2))))))
  16301. (cond ((stringp result) (split-string result "; "))
  16302. ((and (consp result)
  16303. (not (consp (cdr result)))
  16304. (stringp (cdr result))) (cdr result))
  16305. ((and (consp result)
  16306. (stringp (car result))) result)
  16307. (result entry))))
  16308. (defun org-diary-to-ical-string (frombuf)
  16309. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16310. This uses the icalendar.el library."
  16311. (let* ((tmpdir temporary-file-directory)
  16312. (tmpfile (make-temp-name
  16313. (expand-file-name "orgics" tmpdir)))
  16314. buf rtn b e)
  16315. (with-current-buffer frombuf
  16316. (icalendar-export-region (point-min) (point-max) tmpfile)
  16317. (setq buf (find-buffer-visiting tmpfile))
  16318. (set-buffer buf)
  16319. (goto-char (point-min))
  16320. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16321. (setq b (match-beginning 0)))
  16322. (goto-char (point-max))
  16323. (when (re-search-backward "^END:VEVENT" nil t)
  16324. (setq e (match-end 0)))
  16325. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16326. (kill-buffer buf)
  16327. (delete-file tmpfile)
  16328. rtn))
  16329. (defun org-closest-date (start current prefer)
  16330. "Return closest date to CURRENT starting from START.
  16331. CURRENT and START are both time stamps.
  16332. When PREFER is `past', return a date that is either CURRENT or
  16333. past. When PREFER is `future', return a date that is either
  16334. CURRENT or future.
  16335. Only time stamps with a repeater are modified. Any other time
  16336. stamp stay unchanged. In any case, return value is an absolute
  16337. day number."
  16338. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16339. ;; No repeater. Do not shift time stamp.
  16340. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16341. (let ((value (string-to-number (match-string 1 start)))
  16342. (type (match-string 2 start)))
  16343. (if (= 0 value)
  16344. ;; Repeater with a 0-value is considered as void.
  16345. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16346. (let* ((base (org-date-to-gregorian start))
  16347. (target (org-date-to-gregorian current))
  16348. (sday (calendar-absolute-from-gregorian base))
  16349. (cday (calendar-absolute-from-gregorian target))
  16350. n1 n2)
  16351. ;; If START is already past CURRENT, just return START.
  16352. (if (<= cday sday) sday
  16353. ;; Compute closest date before (N1) and closest date past
  16354. ;; (N2) CURRENT.
  16355. (pcase type
  16356. ("h"
  16357. (let ((missing-hours
  16358. (mod (+ (- (* 24 (- cday sday))
  16359. (nth 2 (org-parse-time-string start)))
  16360. org-extend-today-until)
  16361. value)))
  16362. (setf n1 (if (= missing-hours 0) cday
  16363. (- cday (1+ (/ missing-hours 24)))))
  16364. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16365. ((or "d" "w")
  16366. (let ((value (if (equal type "w") (* 7 value) value)))
  16367. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16368. (setf n2 (+ n1 value))))
  16369. ("m"
  16370. (let* ((add-months
  16371. (lambda (d n)
  16372. ;; Add N months to gregorian date D, i.e.,
  16373. ;; a list (MONTH DAY YEAR). Return a valid
  16374. ;; gregorian date.
  16375. (let ((m (+ (nth 0 d) n)))
  16376. (list (mod m 12)
  16377. (nth 1 d)
  16378. (+ (/ m 12) (nth 2 d))))))
  16379. (months ; Complete months to TARGET.
  16380. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16381. (- (nth 0 target) (nth 0 base))
  16382. ;; If START's day is greater than
  16383. ;; TARGET's, remove incomplete month.
  16384. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16385. value)
  16386. value))
  16387. (before (funcall add-months base months)))
  16388. (setf n1 (calendar-absolute-from-gregorian before))
  16389. (setf n2
  16390. (calendar-absolute-from-gregorian
  16391. (funcall add-months before value)))))
  16392. (_
  16393. (let* ((d (nth 1 base))
  16394. (m (nth 0 base))
  16395. (y (nth 2 base))
  16396. (years ; Complete years to TARGET.
  16397. (* (/ (- (nth 2 target)
  16398. y
  16399. ;; If START's month and day are
  16400. ;; greater than TARGET's, remove
  16401. ;; incomplete year.
  16402. (if (or (> (nth 0 target) m)
  16403. (and (= (nth 0 target) m)
  16404. (> (nth 1 target) d)))
  16405. 0
  16406. 1))
  16407. value)
  16408. value))
  16409. (before (list m d (+ y years))))
  16410. (setf n1 (calendar-absolute-from-gregorian before))
  16411. (setf n2 (calendar-absolute-from-gregorian
  16412. (list m d (+ (nth 2 before) value)))))))
  16413. ;; Handle PREFER parameter, if any.
  16414. (cond
  16415. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16416. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16417. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16418. (defun org-date-to-gregorian (d)
  16419. "Turn any specification of date D into a Gregorian date for the calendar."
  16420. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16421. ((and (listp d) (= (length d) 3)) d)
  16422. ((stringp d)
  16423. (let ((d (org-parse-time-string d)))
  16424. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16425. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16426. (defun org-parse-time-string (s &optional nodefault)
  16427. "Parse the standard Org time string.
  16428. This should be a lot faster than the normal `parse-time-string'.
  16429. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16430. hour and minute fields will be nil if not given."
  16431. (cond ((string-match org-ts-regexp0 s)
  16432. (list 0
  16433. (when (or (match-beginning 8) (not nodefault))
  16434. (string-to-number (or (match-string 8 s) "0")))
  16435. (when (or (match-beginning 7) (not nodefault))
  16436. (string-to-number (or (match-string 7 s) "0")))
  16437. (string-to-number (match-string 4 s))
  16438. (string-to-number (match-string 3 s))
  16439. (string-to-number (match-string 2 s))
  16440. nil nil nil))
  16441. ((string-match "^<[^>]+>$" s)
  16442. (decode-time (seconds-to-time (org-matcher-time s))))
  16443. (t (error "Not a standard Org time string: %s" s))))
  16444. (defun org-timestamp-up (&optional arg)
  16445. "Increase the date item at the cursor by one.
  16446. If the cursor is on the year, change the year. If it is on the month,
  16447. the day or the time, change that.
  16448. With prefix ARG, change by that many units."
  16449. (interactive "p")
  16450. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16451. (defun org-timestamp-down (&optional arg)
  16452. "Decrease the date item at the cursor by one.
  16453. If the cursor is on the year, change the year. If it is on the month,
  16454. the day or the time, change that.
  16455. With prefix ARG, change by that many units."
  16456. (interactive "p")
  16457. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16458. (defun org-timestamp-up-day (&optional arg)
  16459. "Increase the date in the time stamp by one day.
  16460. With prefix ARG, change that many days."
  16461. (interactive "p")
  16462. (if (and (not (org-at-timestamp-p t))
  16463. (org-at-heading-p))
  16464. (org-todo 'up)
  16465. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16466. (defun org-timestamp-down-day (&optional arg)
  16467. "Decrease the date in the time stamp by one day.
  16468. With prefix ARG, change that many days."
  16469. (interactive "p")
  16470. (if (and (not (org-at-timestamp-p t))
  16471. (org-at-heading-p))
  16472. (org-todo 'down)
  16473. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16474. (defun org-at-timestamp-p (&optional inactive-ok)
  16475. "Non-nil if point is inside a timestamp.
  16476. When optional argument INACTIVE-OK is non-nil, also consider
  16477. inactive timestamps.
  16478. When this function returns a non-nil value, match data is set
  16479. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16480. INACTIVE-OK."
  16481. (interactive)
  16482. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16483. (pos (point))
  16484. (ans (or (looking-at tsr)
  16485. (save-excursion
  16486. (skip-chars-backward "^[<\n\r\t")
  16487. (when (> (point) (point-min)) (backward-char 1))
  16488. (and (looking-at tsr)
  16489. (> (- (match-end 0) pos) -1))))))
  16490. (and ans
  16491. (boundp 'org-ts-what)
  16492. (setq org-ts-what
  16493. (cond
  16494. ((= pos (match-beginning 0)) 'bracket)
  16495. ;; Point is considered to be "on the bracket" whether
  16496. ;; it's really on it or right after it.
  16497. ((= pos (1- (match-end 0))) 'bracket)
  16498. ((= pos (match-end 0)) 'after)
  16499. ((org-pos-in-match-range pos 2) 'year)
  16500. ((org-pos-in-match-range pos 3) 'month)
  16501. ((org-pos-in-match-range pos 7) 'hour)
  16502. ((org-pos-in-match-range pos 8) 'minute)
  16503. ((or (org-pos-in-match-range pos 4)
  16504. (org-pos-in-match-range pos 5)) 'day)
  16505. ((and (> pos (or (match-end 8) (match-end 5)))
  16506. (< pos (match-end 0)))
  16507. (- pos (or (match-end 8) (match-end 5))))
  16508. (t 'day))))
  16509. ans))
  16510. (defun org-toggle-timestamp-type ()
  16511. "Toggle the type (<active> or [inactive]) of a time stamp."
  16512. (interactive)
  16513. (when (org-at-timestamp-p t)
  16514. (let ((beg (match-beginning 0)) (end (match-end 0))
  16515. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16516. (save-excursion
  16517. (goto-char beg)
  16518. (while (re-search-forward "[][<>]" end t)
  16519. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16520. t t)))
  16521. (message "Timestamp is now %sactive"
  16522. (if (equal (char-after beg) ?<) "" "in")))))
  16523. (defun org-at-clock-log-p nil
  16524. "Is the cursor on the clock log line?"
  16525. (save-excursion
  16526. (move-beginning-of-line 1)
  16527. (looking-at org-clock-line-re)))
  16528. (defvar org-clock-history) ; defined in org-clock.el
  16529. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16530. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16531. "Change the date in the time stamp at point.
  16532. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16533. `year', `minute', `second'. If WHAT is not given, the cursor position
  16534. in the timestamp determines what will be changed.
  16535. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16536. (let ((origin (point)) origin-cat
  16537. with-hm inactive
  16538. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16539. org-ts-what
  16540. extra rem
  16541. ts time time0 fixnext clrgx)
  16542. (unless (org-at-timestamp-p t)
  16543. (user-error "Not at a timestamp"))
  16544. (if (and (not what) (eq org-ts-what 'bracket))
  16545. (org-toggle-timestamp-type)
  16546. ;; Point isn't on brackets. Remember the part of the time-stamp
  16547. ;; the point was in. Indeed, size of time-stamps may change,
  16548. ;; but point must be kept in the same category nonetheless.
  16549. (setq origin-cat org-ts-what)
  16550. (when (and (not what) (not (eq org-ts-what 'day))
  16551. org-display-custom-times
  16552. (get-text-property (point) 'display)
  16553. (not (get-text-property (1- (point)) 'display)))
  16554. (setq org-ts-what 'day))
  16555. (setq org-ts-what (or what org-ts-what)
  16556. inactive (= (char-after (match-beginning 0)) ?\[)
  16557. ts (match-string 0))
  16558. (replace-match "")
  16559. (when (string-match
  16560. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16561. ts)
  16562. (setq extra (match-string 1 ts))
  16563. (when suppress-tmp-delay
  16564. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16565. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16566. (setq with-hm t))
  16567. (setq time0 (org-parse-time-string ts))
  16568. (when (and updown
  16569. (eq org-ts-what 'minute)
  16570. (not current-prefix-arg))
  16571. ;; This looks like s-up and s-down. Change by one rounding step.
  16572. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16573. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16574. (setcar (cdr time0) (+ (nth 1 time0)
  16575. (if (> n 0) (- rem) (- dm rem))))))
  16576. (setq time
  16577. (apply #'encode-time
  16578. (or (car time0) 0)
  16579. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16580. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16581. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16582. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16583. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16584. (nthcdr 6 time0)))
  16585. (when (and (member org-ts-what '(hour minute))
  16586. extra
  16587. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16588. (setq extra (org-modify-ts-extra
  16589. extra
  16590. (if (eq org-ts-what 'hour) 2 5)
  16591. n dm)))
  16592. (when (integerp org-ts-what)
  16593. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16594. (when (eq what 'calendar)
  16595. (let ((cal-date (org-get-date-from-calendar)))
  16596. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16597. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16598. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16599. (setcar time0 (or (car time0) 0))
  16600. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16601. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16602. (setq time (apply 'encode-time time0))))
  16603. ;; Insert the new time-stamp, and ensure point stays in the same
  16604. ;; category as before (i.e. not after the last position in that
  16605. ;; category).
  16606. (let ((pos (point)))
  16607. ;; Stay before inserted string. `save-excursion' is of no use.
  16608. (setq org-last-changed-timestamp
  16609. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16610. (goto-char pos))
  16611. (save-match-data
  16612. (looking-at org-ts-regexp3)
  16613. (goto-char
  16614. (pcase origin-cat
  16615. ;; `day' category ends before `hour' if any, or at the end
  16616. ;; of the day name.
  16617. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16618. (`hour (min (match-end 7) origin))
  16619. (`minute (min (1- (match-end 8)) origin))
  16620. ((pred integerp) (min (1- (match-end 0)) origin))
  16621. ;; Point was right after the time-stamp. However, the
  16622. ;; time-stamp length might have changed, so refer to
  16623. ;; (match-end 0) instead.
  16624. (`after (match-end 0))
  16625. ;; `year' and `month' have both fixed size: point couldn't
  16626. ;; have moved into another part.
  16627. (_ origin))))
  16628. ;; Update clock if on a CLOCK line.
  16629. (org-clock-update-time-maybe)
  16630. ;; Maybe adjust the closest clock in `org-clock-history'
  16631. (when org-clock-adjust-closest
  16632. (if (not (and (org-at-clock-log-p)
  16633. (< 1 (length (delq nil (mapcar 'marker-position
  16634. org-clock-history))))))
  16635. (message "No clock to adjust")
  16636. (cond ((save-excursion ; fix previous clock?
  16637. (re-search-backward org-ts-regexp0 nil t)
  16638. (looking-back (concat org-clock-string " \\[")
  16639. (line-beginning-position)))
  16640. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16641. ((save-excursion ; fix next clock?
  16642. (re-search-backward org-ts-regexp0 nil t)
  16643. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16644. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16645. (save-window-excursion
  16646. ;; Find closest clock to point, adjust the previous/next one in history
  16647. (let* ((p (save-excursion (org-back-to-heading t)))
  16648. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16649. (clfixnth
  16650. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16651. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16652. (if (not clfixpos)
  16653. (message "No clock to adjust")
  16654. (save-excursion
  16655. (org-goto-marker-or-bmk clfixpos)
  16656. (org-show-subtree)
  16657. (when (re-search-forward clrgx nil t)
  16658. (goto-char (match-beginning 1))
  16659. (let (org-clock-adjust-closest)
  16660. (org-timestamp-change n org-ts-what updown))
  16661. (message "Clock adjusted in %s for heading: %s"
  16662. (file-name-nondirectory (buffer-file-name))
  16663. (org-get-heading t t)))))))))
  16664. ;; Try to recenter the calendar window, if any.
  16665. (when (and org-calendar-follow-timestamp-change
  16666. (get-buffer-window "*Calendar*" t)
  16667. (memq org-ts-what '(day month year)))
  16668. (org-recenter-calendar (time-to-days time))))))
  16669. (defun org-modify-ts-extra (s pos n dm)
  16670. "Change the different parts of the lead-time and repeat fields in timestamp."
  16671. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16672. ng h m new rem)
  16673. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16674. (cond
  16675. ((or (org-pos-in-match-range pos 2)
  16676. (org-pos-in-match-range pos 3))
  16677. (setq m (string-to-number (match-string 3 s))
  16678. h (string-to-number (match-string 2 s)))
  16679. (if (org-pos-in-match-range pos 2)
  16680. (setq h (+ h n))
  16681. (setq n (* dm (with-no-warnings (signum n))))
  16682. (unless (= 0 (setq rem (% m dm)))
  16683. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16684. (setq m (+ m n)))
  16685. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16686. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16687. (setq h (mod h 24))
  16688. (setq ng 1 new (format "-%02d:%02d" h m)))
  16689. ((org-pos-in-match-range pos 6)
  16690. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16691. ((org-pos-in-match-range pos 5)
  16692. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16693. ((org-pos-in-match-range pos 9)
  16694. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16695. ((org-pos-in-match-range pos 8)
  16696. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16697. (when ng
  16698. (setq s (concat
  16699. (substring s 0 (match-beginning ng))
  16700. new
  16701. (substring s (match-end ng))))))
  16702. s))
  16703. (defun org-recenter-calendar (d)
  16704. "If the calendar is visible, recenter it to date D."
  16705. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16706. (when cwin
  16707. (let ((calendar-move-hook nil))
  16708. (with-selected-window cwin
  16709. (calendar-goto-date
  16710. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16711. (defun org-goto-calendar (&optional arg)
  16712. "Go to the Emacs calendar at the current date.
  16713. If there is a time stamp in the current line, go to that date.
  16714. A prefix ARG can be used to force the current date."
  16715. (interactive "P")
  16716. (let ((tsr org-ts-regexp) diff
  16717. (calendar-move-hook nil)
  16718. (calendar-view-holidays-initially-flag nil)
  16719. (calendar-view-diary-initially-flag nil))
  16720. (when (or (org-at-timestamp-p)
  16721. (save-excursion
  16722. (beginning-of-line 1)
  16723. (looking-at (concat ".*" tsr))))
  16724. (let ((d1 (time-to-days (current-time)))
  16725. (d2 (time-to-days
  16726. (org-time-string-to-time (match-string 1)))))
  16727. (setq diff (- d2 d1))))
  16728. (calendar)
  16729. (calendar-goto-today)
  16730. (when (and diff (not arg)) (calendar-forward-day diff))))
  16731. (defun org-get-date-from-calendar ()
  16732. "Return a list (month day year) of date at point in calendar."
  16733. (with-current-buffer "*Calendar*"
  16734. (save-match-data
  16735. (calendar-cursor-to-date))))
  16736. (defun org-date-from-calendar ()
  16737. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16738. If there is already a time stamp at the cursor position, update it."
  16739. (interactive)
  16740. (if (org-at-timestamp-p t)
  16741. (org-timestamp-change 0 'calendar)
  16742. (let ((cal-date (org-get-date-from-calendar)))
  16743. (org-insert-time-stamp
  16744. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16745. (defcustom org-effort-durations
  16746. `(("min" . 1)
  16747. ("h" . 60)
  16748. ("d" . ,(* 60 8))
  16749. ("w" . ,(* 60 8 5))
  16750. ("m" . ,(* 60 8 5 4))
  16751. ("y" . ,(* 60 8 5 40)))
  16752. "Conversion factor to minutes for an effort modifier.
  16753. Each entry has the form (MODIFIER . MINUTES).
  16754. In an effort string, a number followed by MODIFIER is multiplied
  16755. by the specified number of MINUTES to obtain an effort in
  16756. minutes.
  16757. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16758. effort string \"2hours\" is equivalent to 120 minutes."
  16759. :group 'org-agenda
  16760. :version "25.2"
  16761. :package-version '(Org . "8.3")
  16762. :type '(alist :key-type (string :tag "Modifier")
  16763. :value-type (number :tag "Minutes")))
  16764. (defun org-minutes-to-clocksum-string (m)
  16765. "Format number of minutes as a clocksum string.
  16766. The format is determined by `org-time-clocksum-format',
  16767. `org-time-clocksum-use-fractional' and
  16768. `org-time-clocksum-fractional-format' and
  16769. `org-time-clocksum-use-effort-durations'."
  16770. (let ((clocksum "")
  16771. (m (round m)) ; Don't allow fractions of minutes
  16772. h d w mo y fmt n)
  16773. (setq h (if org-time-clocksum-use-effort-durations
  16774. (cdr (assoc "h" org-effort-durations)) 60)
  16775. d (if org-time-clocksum-use-effort-durations
  16776. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16777. w (if org-time-clocksum-use-effort-durations
  16778. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16779. mo (if org-time-clocksum-use-effort-durations
  16780. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16781. y (if org-time-clocksum-use-effort-durations
  16782. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16783. ;; fractional format
  16784. (if org-time-clocksum-use-fractional
  16785. (cond
  16786. ;; single format string
  16787. ((stringp org-time-clocksum-fractional-format)
  16788. (format org-time-clocksum-fractional-format (/ m (float h))))
  16789. ;; choice of fractional formats for different time units
  16790. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16791. (> (/ (truncate m) (* y d h)) 0))
  16792. (format fmt (/ m (* y d (float h)))))
  16793. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16794. (> (/ (truncate m) (* mo d h)) 0))
  16795. (format fmt (/ m (* mo d (float h)))))
  16796. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16797. (> (/ (truncate m) (* w d h)) 0))
  16798. (format fmt (/ m (* w d (float h)))))
  16799. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16800. (> (/ (truncate m) (* d h)) 0))
  16801. (format fmt (/ m (* d (float h)))))
  16802. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16803. (> (/ (truncate m) h) 0))
  16804. (format fmt (/ m (float h))))
  16805. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16806. (format fmt m))
  16807. ;; fall back to smallest time unit with a format
  16808. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16809. (format fmt (/ m (float h))))
  16810. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16811. (format fmt (/ m (* d (float h)))))
  16812. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16813. (format fmt (/ m (* w d (float h)))))
  16814. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16815. (format fmt (/ m (* mo d (float h)))))
  16816. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16817. (format fmt (/ m (* y d (float h))))))
  16818. ;; standard (non-fractional) format, with single format string
  16819. (if (stringp org-time-clocksum-format)
  16820. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16821. ;; separate formats components
  16822. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16823. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16824. (plist-get org-time-clocksum-format :require-years))
  16825. (setq clocksum (concat clocksum (format fmt n))
  16826. m (- m (* n y d h))))
  16827. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16828. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16829. (plist-get org-time-clocksum-format :require-months))
  16830. (setq clocksum (concat clocksum (format fmt n))
  16831. m (- m (* n mo d h))))
  16832. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16833. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16834. (plist-get org-time-clocksum-format :require-weeks))
  16835. (setq clocksum (concat clocksum (format fmt n))
  16836. m (- m (* n w d h))))
  16837. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16838. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16839. (plist-get org-time-clocksum-format :require-days))
  16840. (setq clocksum (concat clocksum (format fmt n))
  16841. m (- m (* n d h))))
  16842. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16843. (or (> (setq n (/ (truncate m) h)) 0)
  16844. (plist-get org-time-clocksum-format :require-hours))
  16845. (setq clocksum (concat clocksum (format fmt n))
  16846. m (- m (* n h))))
  16847. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16848. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16849. (setq clocksum (concat clocksum (format fmt m))))
  16850. ;; return formatted time duration
  16851. clocksum))))
  16852. (defun org-hours-to-clocksum-string (n)
  16853. (org-minutes-to-clocksum-string (* n 60)))
  16854. (defun org-hh:mm-string-to-minutes (s)
  16855. "Convert a string H:MM to a number of minutes.
  16856. If the string is just a number, interpret it as minutes.
  16857. In fact, the first hh:mm or number in the string will be taken,
  16858. there can be extra stuff in the string.
  16859. If no number is found, the return value is 0."
  16860. (cond
  16861. ((integerp s) s)
  16862. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16863. (+ (* (string-to-number (match-string 1 s)) 60)
  16864. (string-to-number (match-string 2 s))))
  16865. ((string-match "\\([0-9]+\\)" s)
  16866. (string-to-number (match-string 1 s)))
  16867. (t 0)))
  16868. (defcustom org-image-actual-width t
  16869. "Should we use the actual width of images when inlining them?
  16870. When set to t, always use the image width.
  16871. When set to a number, use imagemagick (when available) to set
  16872. the image's width to this value.
  16873. When set to a number in a list, try to get the width from any
  16874. #+ATTR.* keyword if it matches a width specification like
  16875. #+ATTR_HTML: :width 300px
  16876. and fall back on that number if none is found.
  16877. When set to nil, try to get the width from an #+ATTR.* keyword
  16878. and fall back on the original width if none is found.
  16879. This requires Emacs >= 24.1, build with imagemagick support."
  16880. :group 'org-appearance
  16881. :version "24.4"
  16882. :package-version '(Org . "8.0")
  16883. :type '(choice
  16884. (const :tag "Use the image width" t)
  16885. (integer :tag "Use a number of pixels")
  16886. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16887. (const :tag "Use #+ATTR* or don't resize" nil)))
  16888. (defcustom org-agenda-inhibit-startup nil
  16889. "Inhibit startup when preparing agenda buffers.
  16890. When this variable is t, the initialization of the Org agenda
  16891. buffers is inhibited: e.g. the visibility state is not set, the
  16892. tables are not re-aligned, etc."
  16893. :type 'boolean
  16894. :version "24.3"
  16895. :group 'org-agenda)
  16896. (defcustom org-agenda-ignore-properties nil
  16897. "Avoid updating text properties when building the agenda.
  16898. Properties are used to prepare buffers for effort estimates,
  16899. appointments, statistics and subtree-local categories.
  16900. If you don't use these in the agenda, you can add them to this
  16901. list and agenda building will be a bit faster.
  16902. The value is a list, with zero or more of the symbols `effort', `appt',
  16903. `stats' or `category'."
  16904. :type '(set :greedy t
  16905. (const effort)
  16906. (const appt)
  16907. (const stats)
  16908. (const category))
  16909. :version "25.2"
  16910. :package-version '(Org . "8.3")
  16911. :group 'org-agenda)
  16912. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16913. "Convert a duration string S to minutes.
  16914. A bare number is interpreted as minutes, modifiers can be set by
  16915. customizing `org-effort-durations' (which see).
  16916. Entries containing a colon are interpreted as H:MM by
  16917. `org-hh:mm-string-to-minutes'."
  16918. (let ((result 0)
  16919. (re (concat "\\([0-9.]+\\) *\\("
  16920. (regexp-opt (mapcar 'car org-effort-durations))
  16921. "\\)")))
  16922. (while (string-match re s)
  16923. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16924. (string-to-number (match-string 1 s))))
  16925. (setq s (replace-match "" nil t s)))
  16926. (setq result (floor result))
  16927. (cl-incf result (org-hh:mm-string-to-minutes s))
  16928. (if output-to-string (number-to-string result) result)))
  16929. ;;;; Files
  16930. (defun org-save-all-org-buffers ()
  16931. "Save all Org buffers without user confirmation."
  16932. (interactive)
  16933. (message "Saving all Org buffers...")
  16934. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16935. (when (featurep 'org-id) (org-id-locations-save))
  16936. (message "Saving all Org buffers... done"))
  16937. (defun org-revert-all-org-buffers ()
  16938. "Revert all Org buffers.
  16939. Prompt for confirmation when there are unsaved changes.
  16940. Be sure you know what you are doing before letting this function
  16941. overwrite your changes.
  16942. This function is useful in a setup where one tracks org files
  16943. with a version control system, to revert on one machine after pulling
  16944. changes from another. I believe the procedure must be like this:
  16945. 1. M-x org-save-all-org-buffers
  16946. 2. Pull changes from the other machine, resolve conflicts
  16947. 3. M-x org-revert-all-org-buffers"
  16948. (interactive)
  16949. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16950. (user-error "Abort"))
  16951. (save-excursion
  16952. (save-window-excursion
  16953. (dolist (b (buffer-list))
  16954. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16955. (with-current-buffer b buffer-file-name))
  16956. (pop-to-buffer-same-window b)
  16957. (revert-buffer t 'no-confirm)))
  16958. (when (and (featurep 'org-id) org-id-track-globally)
  16959. (org-id-locations-load)))))
  16960. ;;;; Agenda files
  16961. ;;;###autoload
  16962. (defun org-switchb (&optional arg)
  16963. "Switch between Org buffers.
  16964. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16965. With `\\[universal-argument] \\[universal-argument]' \
  16966. prefix, restrict available buffers to agenda files."
  16967. (interactive "P")
  16968. (let ((blist (org-buffer-list
  16969. (cond ((equal arg '(4)) 'files)
  16970. ((equal arg '(16)) 'agenda)))))
  16971. (pop-to-buffer-same-window
  16972. (completing-read "Org buffer: "
  16973. (mapcar #'list (mapcar #'buffer-name blist))
  16974. nil t))))
  16975. (defun org-buffer-list (&optional predicate exclude-tmp)
  16976. "Return a list of Org buffers.
  16977. PREDICATE can be `export', `files' or `agenda'.
  16978. export restrict the list to Export buffers.
  16979. files restrict the list to buffers visiting Org files.
  16980. agenda restrict the list to buffers visiting agenda files.
  16981. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16982. (let* ((bfn nil)
  16983. (agenda-files (and (eq predicate 'agenda)
  16984. (mapcar 'file-truename (org-agenda-files t))))
  16985. (filter
  16986. (cond
  16987. ((eq predicate 'files)
  16988. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16989. ((eq predicate 'export)
  16990. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16991. ((eq predicate 'agenda)
  16992. (lambda (b)
  16993. (with-current-buffer b
  16994. (and (derived-mode-p 'org-mode)
  16995. (setq bfn (buffer-file-name b))
  16996. (member (file-truename bfn) agenda-files)))))
  16997. (t (lambda (b) (with-current-buffer b
  16998. (or (derived-mode-p 'org-mode)
  16999. (string-match "\\*Org .*Export"
  17000. (buffer-name b)))))))))
  17001. (delq nil
  17002. (mapcar
  17003. (lambda(b)
  17004. (if (and (funcall filter b)
  17005. (or (not exclude-tmp)
  17006. (not (string-match "tmp" (buffer-name b)))))
  17007. b
  17008. nil))
  17009. (buffer-list)))))
  17010. (defun org-agenda-files (&optional unrestricted archives)
  17011. "Get the list of agenda files.
  17012. Optional UNRESTRICTED means return the full list even if a restriction
  17013. is currently in place.
  17014. When ARCHIVES is t, include all archive files that are really being
  17015. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  17016. `org-agenda-archives-mode' is t."
  17017. (let ((files
  17018. (cond
  17019. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  17020. ((stringp org-agenda-files) (org-read-agenda-file-list))
  17021. ((listp org-agenda-files) org-agenda-files)
  17022. (t (error "Invalid value of `org-agenda-files'")))))
  17023. (setq files (apply 'append
  17024. (mapcar (lambda (f)
  17025. (if (file-directory-p f)
  17026. (directory-files
  17027. f t org-agenda-file-regexp)
  17028. (list f)))
  17029. files)))
  17030. (when org-agenda-skip-unavailable-files
  17031. (setq files (delq nil
  17032. (mapcar (function
  17033. (lambda (file)
  17034. (and (file-readable-p file) file)))
  17035. files))))
  17036. (when (or (eq archives t)
  17037. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17038. (setq files (org-add-archive-files files)))
  17039. files))
  17040. (defun org-agenda-file-p (&optional file)
  17041. "Return non-nil, if FILE is an agenda file.
  17042. If FILE is omitted, use the file associated with the current
  17043. buffer."
  17044. (let ((fname (or file (buffer-file-name))))
  17045. (and fname
  17046. (member (file-truename fname)
  17047. (mapcar #'file-truename (org-agenda-files t))))))
  17048. (defun org-edit-agenda-file-list ()
  17049. "Edit the list of agenda files.
  17050. Depending on setup, this either uses customize to edit the variable
  17051. `org-agenda-files', or it visits the file that is holding the list. In the
  17052. latter case, the buffer is set up in a way that saving it automatically kills
  17053. the buffer and restores the previous window configuration."
  17054. (interactive)
  17055. (if (stringp org-agenda-files)
  17056. (let ((cw (current-window-configuration)))
  17057. (find-file org-agenda-files)
  17058. (setq-local org-window-configuration cw)
  17059. (add-hook 'after-save-hook
  17060. (lambda ()
  17061. (set-window-configuration
  17062. (prog1 org-window-configuration
  17063. (kill-buffer (current-buffer))))
  17064. (org-install-agenda-files-menu)
  17065. (message "New agenda file list installed"))
  17066. nil 'local)
  17067. (message "%s" (substitute-command-keys
  17068. "Edit list and finish with \\[save-buffer]")))
  17069. (customize-variable 'org-agenda-files)))
  17070. (defun org-store-new-agenda-file-list (list)
  17071. "Set new value for the agenda file list and save it correctly."
  17072. (if (stringp org-agenda-files)
  17073. (let ((fe (org-read-agenda-file-list t)) b u)
  17074. (while (setq b (find-buffer-visiting org-agenda-files))
  17075. (kill-buffer b))
  17076. (with-temp-file org-agenda-files
  17077. (insert
  17078. (mapconcat
  17079. (lambda (f) ;; Keep un-expanded entries.
  17080. (if (setq u (assoc f fe))
  17081. (cdr u)
  17082. f))
  17083. list "\n")
  17084. "\n")))
  17085. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17086. (org-insert-mode-line-in-empty-file nil))
  17087. (setq org-agenda-files list)
  17088. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17089. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17090. "Read the list of agenda files from a file.
  17091. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17092. filenames, used by `org-store-new-agenda-file-list' to write back
  17093. un-expanded file names."
  17094. (when (file-directory-p org-agenda-files)
  17095. (error "`org-agenda-files' cannot be a single directory"))
  17096. (when (stringp org-agenda-files)
  17097. (with-temp-buffer
  17098. (insert-file-contents org-agenda-files)
  17099. (mapcar
  17100. (lambda (f)
  17101. (let ((e (expand-file-name (substitute-in-file-name f)
  17102. org-directory)))
  17103. (if pair-with-expansion
  17104. (cons e f)
  17105. e)))
  17106. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17107. ;;;###autoload
  17108. (defun org-cycle-agenda-files ()
  17109. "Cycle through the files in `org-agenda-files'.
  17110. If the current buffer visits an agenda file, find the next one in the list.
  17111. If the current buffer does not, find the first agenda file."
  17112. (interactive)
  17113. (let* ((fs (or (org-agenda-files t)
  17114. (user-error "No agenda files")))
  17115. (files (copy-sequence fs))
  17116. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17117. file)
  17118. (when tcf
  17119. (while (and (setq file (pop files))
  17120. (not (equal (file-truename file) tcf)))))
  17121. (find-file (car (or files fs)))
  17122. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17123. (defun org-agenda-file-to-front (&optional to-end)
  17124. "Move/add the current file to the top of the agenda file list.
  17125. If the file is not present in the list, it is added to the front. If it is
  17126. present, it is moved there. With optional argument TO-END, add/move to the
  17127. end of the list."
  17128. (interactive "P")
  17129. (let ((org-agenda-skip-unavailable-files nil)
  17130. (file-alist (mapcar (lambda (x)
  17131. (cons (file-truename x) x))
  17132. (org-agenda-files t)))
  17133. (ctf (file-truename
  17134. (or buffer-file-name
  17135. (user-error "Please save the current buffer to a file"))))
  17136. x had)
  17137. (setq x (assoc ctf file-alist) had x)
  17138. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17139. (if to-end
  17140. (setq file-alist (append (delq x file-alist) (list x)))
  17141. (setq file-alist (cons x (delq x file-alist))))
  17142. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17143. (org-install-agenda-files-menu)
  17144. (message "File %s to %s of agenda file list"
  17145. (if had "moved" "added") (if to-end "end" "front"))))
  17146. (defun org-remove-file (&optional file)
  17147. "Remove current file from the list of files in variable `org-agenda-files'.
  17148. These are the files which are being checked for agenda entries.
  17149. Optional argument FILE means use this file instead of the current."
  17150. (interactive)
  17151. (let* ((org-agenda-skip-unavailable-files nil)
  17152. (file (or file buffer-file-name
  17153. (user-error "Current buffer does not visit a file")))
  17154. (true-file (file-truename file))
  17155. (afile (abbreviate-file-name file))
  17156. (files (delq nil (mapcar
  17157. (lambda (x)
  17158. (unless (equal true-file
  17159. (file-truename x))
  17160. x))
  17161. (org-agenda-files t)))))
  17162. (if (not (= (length files) (length (org-agenda-files t))))
  17163. (progn
  17164. (org-store-new-agenda-file-list files)
  17165. (org-install-agenda-files-menu)
  17166. (message "Removed from Org Agenda list: %s" afile))
  17167. (message "File was not in list: %s (not removed)" afile))))
  17168. (defun org-file-menu-entry (file)
  17169. (vector file (list 'find-file file) t))
  17170. (defun org-check-agenda-file (file)
  17171. "Make sure FILE exists. If not, ask user what to do."
  17172. (unless (file-exists-p file)
  17173. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17174. (abbreviate-file-name file))
  17175. (let ((r (downcase (read-char-exclusive))))
  17176. (cond
  17177. ((equal r ?r)
  17178. (org-remove-file file)
  17179. (throw 'nextfile t))
  17180. (t (user-error "Abort"))))))
  17181. (defun org-get-agenda-file-buffer (file)
  17182. "Get an agenda buffer visiting FILE.
  17183. If the buffer needs to be created, add it to the list of buffers
  17184. which might be released later."
  17185. (let ((buf (org-find-base-buffer-visiting file)))
  17186. (if buf
  17187. buf ; just return it
  17188. ;; Make a new buffer and remember it
  17189. (setq buf (find-file-noselect file))
  17190. (when buf (push buf org-agenda-new-buffers))
  17191. buf)))
  17192. (defun org-release-buffers (blist)
  17193. "Release all buffers in list, asking the user for confirmation when needed.
  17194. When a buffer is unmodified, it is just killed. When modified, it is saved
  17195. \(if the user agrees) and then killed."
  17196. (let (file)
  17197. (dolist (buf blist)
  17198. (setq file (buffer-file-name buf))
  17199. (when (and (buffer-modified-p buf)
  17200. file
  17201. (y-or-n-p (format "Save file %s? " file)))
  17202. (with-current-buffer buf (save-buffer)))
  17203. (kill-buffer buf))))
  17204. (defun org-agenda-prepare-buffers (files)
  17205. "Create buffers for all agenda files, protect archived trees and comments."
  17206. (interactive)
  17207. (let ((pa '(:org-archived t))
  17208. (pc '(:org-comment t))
  17209. (pall '(:org-archived t :org-comment t))
  17210. (inhibit-read-only t)
  17211. (org-inhibit-startup org-agenda-inhibit-startup)
  17212. (rea (concat ":" org-archive-tag ":"))
  17213. re pos)
  17214. (setq org-tag-alist-for-agenda nil
  17215. org-tag-groups-alist-for-agenda nil)
  17216. (save-excursion
  17217. (save-restriction
  17218. (dolist (file files)
  17219. (catch 'nextfile
  17220. (if (bufferp file)
  17221. (set-buffer file)
  17222. (org-check-agenda-file file)
  17223. (set-buffer (org-get-agenda-file-buffer file)))
  17224. (widen)
  17225. (org-set-regexps-and-options 'tags-only)
  17226. (setq pos (point))
  17227. (or (memq 'category org-agenda-ignore-properties)
  17228. (org-refresh-category-properties))
  17229. (or (memq 'stats org-agenda-ignore-properties)
  17230. (org-refresh-stats-properties))
  17231. (or (memq 'effort org-agenda-ignore-properties)
  17232. (org-refresh-effort-properties))
  17233. (or (memq 'appt org-agenda-ignore-properties)
  17234. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17235. (setq org-todo-keywords-for-agenda
  17236. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17237. (setq org-done-keywords-for-agenda
  17238. (append org-done-keywords-for-agenda org-done-keywords))
  17239. (setq org-todo-keyword-alist-for-agenda
  17240. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17241. (setq org-tag-alist-for-agenda
  17242. (org-uniquify
  17243. (append org-tag-alist-for-agenda
  17244. org-current-tag-alist)))
  17245. ;; Merge current file's tag groups into global
  17246. ;; `org-tag-groups-alist-for-agenda'.
  17247. (when org-group-tags
  17248. (dolist (alist org-tag-groups-alist)
  17249. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17250. (if old
  17251. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17252. (push alist org-tag-groups-alist-for-agenda)))))
  17253. (org-with-silent-modifications
  17254. (save-excursion
  17255. (remove-text-properties (point-min) (point-max) pall)
  17256. (when org-agenda-skip-archived-trees
  17257. (goto-char (point-min))
  17258. (while (re-search-forward rea nil t)
  17259. (when (org-at-heading-p t)
  17260. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17261. (goto-char (point-min))
  17262. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17263. (while (re-search-forward re nil t)
  17264. (when (save-match-data (org-in-commented-heading-p t))
  17265. (add-text-properties
  17266. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17267. (goto-char pos)))))
  17268. (setq org-todo-keywords-for-agenda
  17269. (org-uniquify org-todo-keywords-for-agenda))
  17270. (setq org-todo-keyword-alist-for-agenda
  17271. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17272. ;;;; CDLaTeX minor mode
  17273. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17274. "Keymap for the minor `org-cdlatex-mode'.")
  17275. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17276. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17277. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17278. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17279. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17280. (defvar org-cdlatex-texmathp-advice-is-done nil
  17281. "Flag remembering if we have applied the advice to texmathp already.")
  17282. (define-minor-mode org-cdlatex-mode
  17283. "Toggle the minor `org-cdlatex-mode'.
  17284. This mode supports entering LaTeX environment and math in LaTeX fragments
  17285. in Org mode.
  17286. \\{org-cdlatex-mode-map}"
  17287. nil " OCDL" nil
  17288. (when org-cdlatex-mode
  17289. (require 'cdlatex)
  17290. (run-hooks 'cdlatex-mode-hook)
  17291. (cdlatex-compute-tables))
  17292. (unless org-cdlatex-texmathp-advice-is-done
  17293. (setq org-cdlatex-texmathp-advice-is-done t)
  17294. (defadvice texmathp (around org-math-always-on activate)
  17295. "Always return t in Org buffers.
  17296. This is because we want to insert math symbols without dollars even outside
  17297. the LaTeX math segments. If Org mode thinks that point is actually inside
  17298. an embedded LaTeX fragment, let `texmathp' do its job.
  17299. `\\[org-cdlatex-mode-map]'"
  17300. (interactive)
  17301. (let (p)
  17302. (cond
  17303. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17304. ((eq this-command 'cdlatex-math-symbol)
  17305. (setq ad-return-value t
  17306. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17307. (t
  17308. (let ((p (org-inside-LaTeX-fragment-p)))
  17309. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17310. (setq ad-return-value t
  17311. texmathp-why '("Org mode embedded math" . 0))
  17312. (when p ad-do-it)))))))))
  17313. (defun turn-on-org-cdlatex ()
  17314. "Unconditionally turn on `org-cdlatex-mode'."
  17315. (org-cdlatex-mode 1))
  17316. (defun org-try-cdlatex-tab ()
  17317. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17318. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17319. - inside a LaTeX fragment, or
  17320. - after the first word in a line, where an abbreviation expansion could
  17321. insert a LaTeX environment."
  17322. (when org-cdlatex-mode
  17323. (cond
  17324. ;; Before any word on the line: No expansion possible.
  17325. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17326. ;; Just after first word on the line: Expand it. Make sure it
  17327. ;; cannot happen on headlines, though.
  17328. ((save-excursion
  17329. (skip-chars-backward "a-zA-Z0-9*")
  17330. (skip-chars-backward " \t")
  17331. (and (bolp) (not (org-at-heading-p))))
  17332. (cdlatex-tab) t)
  17333. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17334. (defun org-cdlatex-underscore-caret (&optional _arg)
  17335. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17336. Revert to the normal definition outside of these fragments."
  17337. (interactive "P")
  17338. (if (org-inside-LaTeX-fragment-p)
  17339. (call-interactively 'cdlatex-sub-superscript)
  17340. (let (org-cdlatex-mode)
  17341. (call-interactively (key-binding (vector last-input-event))))))
  17342. (defun org-cdlatex-math-modify (&optional _arg)
  17343. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17344. Revert to the normal definition outside of these fragments."
  17345. (interactive "P")
  17346. (if (org-inside-LaTeX-fragment-p)
  17347. (call-interactively 'cdlatex-math-modify)
  17348. (let (org-cdlatex-mode)
  17349. (call-interactively (key-binding (vector last-input-event))))))
  17350. (defun org-cdlatex-environment-indent (&optional environment item)
  17351. "Execute `cdlatex-environment' and indent the inserted environment.
  17352. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17353. The inserted environment is indented to current indentation
  17354. unless point is at the beginning of the line, in which the
  17355. environment remains unintended."
  17356. (interactive)
  17357. ;; cdlatex-environment always return nil. Therefore, capture output
  17358. ;; first and determine if an environment was selected.
  17359. (let* ((beg (point-marker))
  17360. (end (copy-marker (point) t))
  17361. (inserted (progn
  17362. (ignore-errors (cdlatex-environment environment item))
  17363. (< beg end)))
  17364. ;; Figure out how many lines to move forward after the
  17365. ;; environment has been inserted.
  17366. (lines (when inserted
  17367. (save-excursion
  17368. (- (cl-loop while (< beg (point))
  17369. with x = 0
  17370. do (forward-line -1)
  17371. (cl-incf x)
  17372. finally return x)
  17373. (if (progn (goto-char beg)
  17374. (and (progn (skip-chars-forward " \t") (eolp))
  17375. (progn (skip-chars-backward " \t") (bolp))))
  17376. 1 0)))))
  17377. (env (org-trim (delete-and-extract-region beg end))))
  17378. (when inserted
  17379. ;; Get indentation of next line unless at column 0.
  17380. (let ((ind (if (bolp) 0
  17381. (save-excursion
  17382. (org-return-indent)
  17383. (prog1 (org-get-indentation)
  17384. (when (progn (skip-chars-forward " \t") (eolp))
  17385. (delete-region beg (point)))))))
  17386. (bol (progn (skip-chars-backward " \t") (bolp))))
  17387. ;; Insert a newline before environment unless at column zero
  17388. ;; to "escape" the current line. Insert a newline if
  17389. ;; something is one the same line as \end{ENVIRONMENT}.
  17390. (insert
  17391. (concat (unless bol "\n") env
  17392. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17393. (unless (zerop ind)
  17394. (save-excursion
  17395. (goto-char beg)
  17396. (while (< (point) end)
  17397. (unless (eolp) (indent-line-to ind))
  17398. (forward-line))))
  17399. (goto-char beg)
  17400. (forward-line lines)
  17401. (indent-line-to ind)))
  17402. (set-marker beg nil)
  17403. (set-marker end nil)))
  17404. ;;;; LaTeX fragments
  17405. (defun org-inside-LaTeX-fragment-p ()
  17406. "Test if point is inside a LaTeX fragment.
  17407. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17408. sequence appearing also before point.
  17409. Even though the matchers for math are configurable, this function assumes
  17410. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17411. delimiters are skipped when they have been removed by customization.
  17412. The return value is nil, or a cons cell with the delimiter and the
  17413. position of this delimiter.
  17414. This function does a reasonably good job, but can locally be fooled by
  17415. for example currency specifications. For example it will assume being in
  17416. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17417. fragments that are properly closed, but during editing, we have to live
  17418. with the uncertainty caused by missing closing delimiters. This function
  17419. looks only before point, not after."
  17420. (catch 'exit
  17421. (let ((pos (point))
  17422. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17423. (lim (progn
  17424. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17425. (point)))
  17426. dd-on str (start 0) m re)
  17427. (goto-char pos)
  17428. (when dodollar
  17429. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17430. re (nth 1 (assoc "$" org-latex-regexps)))
  17431. (while (string-match re str start)
  17432. (cond
  17433. ((= (match-end 0) (length str))
  17434. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17435. ((= (match-end 0) (- (length str) 5))
  17436. (throw 'exit nil))
  17437. (t (setq start (match-end 0))))))
  17438. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17439. (goto-char pos)
  17440. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17441. (and (match-beginning 2) (throw 'exit nil))
  17442. ;; count $$
  17443. (while (re-search-backward "\\$\\$" lim t)
  17444. (setq dd-on (not dd-on)))
  17445. (goto-char pos)
  17446. (when dd-on (cons "$$" m))))))
  17447. (defun org-inside-latex-macro-p ()
  17448. "Is point inside a LaTeX macro or its arguments?"
  17449. (save-match-data
  17450. (org-in-regexp
  17451. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17452. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17453. "Build an overlay between BEG and END using IMAGE file.
  17454. Argument IMAGETYPE is the extension of the displayed image,
  17455. as a string. It defaults to \"png\"."
  17456. (let ((ov (make-overlay beg end))
  17457. (imagetype (or (intern imagetype) 'png)))
  17458. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17459. (overlay-put ov 'evaporate t)
  17460. (overlay-put ov
  17461. 'modification-hooks
  17462. (list (lambda (o _flag _beg _end &optional _l)
  17463. (delete-overlay o))))
  17464. (overlay-put ov
  17465. 'display
  17466. (list 'image :type imagetype :file image :ascent 'center))))
  17467. (defun org--list-latex-overlays (&optional beg end)
  17468. "List all Org LaTeX overlays in current buffer.
  17469. Limit to overlays between BEG and END when those are provided."
  17470. (cl-remove-if-not
  17471. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17472. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17473. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17474. "Remove all overlays with LaTeX fragment images in current buffer.
  17475. When optional arguments BEG and END are non-nil, remove all
  17476. overlays between them instead. Return a non-nil value when some
  17477. overlays were removed, nil otherwise."
  17478. (let ((overlays (org--list-latex-overlays beg end)))
  17479. (mapc #'delete-overlay overlays)
  17480. overlays))
  17481. (defun org-toggle-latex-fragment (&optional arg)
  17482. "Preview the LaTeX fragment at point, or all locally or globally.
  17483. If the cursor is on a LaTeX fragment, create the image and overlay
  17484. it over the source code, if there is none. Remove it otherwise.
  17485. If there is no fragment at point, display all fragments in the
  17486. current section.
  17487. With prefix ARG, preview or clear image for all fragments in the
  17488. current subtree or in the whole buffer when used before the first
  17489. headline. With a prefix ARG `\\[universal-argument] \
  17490. \\[universal-argument]' preview or clear images
  17491. for all fragments in the buffer."
  17492. (interactive "P")
  17493. (when (display-graphic-p)
  17494. (catch 'exit
  17495. (save-excursion
  17496. (let (beg end msg)
  17497. (cond
  17498. ((or (equal arg '(16))
  17499. (and (equal arg '(4))
  17500. (org-with-limited-levels (org-before-first-heading-p))))
  17501. (if (org-remove-latex-fragment-image-overlays)
  17502. (progn (message "LaTeX fragments images removed from buffer")
  17503. (throw 'exit nil))
  17504. (setq msg "Creating images for buffer...")))
  17505. ((equal arg '(4))
  17506. (org-with-limited-levels (org-back-to-heading t))
  17507. (setq beg (point))
  17508. (setq end (progn (org-end-of-subtree t) (point)))
  17509. (if (org-remove-latex-fragment-image-overlays beg end)
  17510. (progn
  17511. (message "LaTeX fragment images removed from subtree")
  17512. (throw 'exit nil))
  17513. (setq msg "Creating images for subtree...")))
  17514. ((let ((datum (org-element-context)))
  17515. (when (memq (org-element-type datum)
  17516. '(latex-environment latex-fragment))
  17517. (setq beg (org-element-property :begin datum))
  17518. (setq end (org-element-property :end datum))
  17519. (if (org-remove-latex-fragment-image-overlays beg end)
  17520. (progn (message "LaTeX fragment image removed")
  17521. (throw 'exit nil))
  17522. (setq msg "Creating image...")))))
  17523. (t
  17524. (org-with-limited-levels
  17525. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17526. (outline-previous-heading)
  17527. (point)))
  17528. (setq end (progn (outline-next-heading) (point)))
  17529. (if (org-remove-latex-fragment-image-overlays beg end)
  17530. (progn
  17531. (message "LaTeX fragment images removed from section")
  17532. (throw 'exit nil))
  17533. (setq msg "Creating images for section...")))))
  17534. (let ((file (buffer-file-name (buffer-base-buffer))))
  17535. (org-format-latex
  17536. (concat org-preview-latex-image-directory "org-ltximg")
  17537. beg end
  17538. ;; Emacs cannot overlay images from remote hosts. Create
  17539. ;; it in `temporary-file-directory' instead.
  17540. (if (or (not file) (file-remote-p file))
  17541. temporary-file-directory
  17542. default-directory)
  17543. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17544. (message (concat msg "done")))))))
  17545. (defun org-format-latex
  17546. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17547. "Replace LaTeX fragments with links to an image.
  17548. The function takes care of creating the replacement image.
  17549. Only consider fragments between BEG and END when those are
  17550. provided.
  17551. When optional argument OVERLAYS is non-nil, display the image on
  17552. top of the fragment instead of replacing it.
  17553. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17554. Some of the options can be changed using the variable
  17555. `org-format-latex-options', which see."
  17556. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17557. (unless (eq processing-type 'verbatim)
  17558. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17559. (cnt 0)
  17560. checkdir-flag)
  17561. (goto-char (or beg (point-min)))
  17562. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17563. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17564. (overlay-recenter (or end (point-max))))
  17565. (while (re-search-forward math-regexp end t)
  17566. (unless (and overlays
  17567. (eq (get-char-property (point) 'org-overlay-type)
  17568. 'org-latex-overlay))
  17569. (let* ((context (org-element-context))
  17570. (type (org-element-type context)))
  17571. (when (memq type '(latex-environment latex-fragment))
  17572. (let ((block-type (eq type 'latex-environment))
  17573. (value (org-element-property :value context))
  17574. (beg (org-element-property :begin context))
  17575. (end (save-excursion
  17576. (goto-char (org-element-property :end context))
  17577. (skip-chars-backward " \r\t\n")
  17578. (point))))
  17579. (cond
  17580. ((eq processing-type 'mathjax)
  17581. ;; Prepare for MathJax processing.
  17582. (if (not (string-match "\\`\\$\\$?" value))
  17583. (goto-char end)
  17584. (delete-region beg end)
  17585. (if (string= (match-string 0 value) "$$")
  17586. (insert "\\[" (substring value 2 -2) "\\]")
  17587. (insert "\\(" (substring value 1 -1) "\\)"))))
  17588. ((assq processing-type org-preview-latex-process-alist)
  17589. ;; Process to an image.
  17590. (cl-incf cnt)
  17591. (goto-char beg)
  17592. (let* ((processing-info
  17593. (cdr (assq processing-type org-preview-latex-process-alist)))
  17594. (face (face-at-point))
  17595. ;; Get the colors from the face at point.
  17596. (fg
  17597. (let ((color (plist-get org-format-latex-options
  17598. :foreground)))
  17599. (if (and forbuffer (eq color 'auto))
  17600. (face-attribute face :foreground nil 'default)
  17601. color)))
  17602. (bg
  17603. (let ((color (plist-get org-format-latex-options
  17604. :background)))
  17605. (if (and forbuffer (eq color 'auto))
  17606. (face-attribute face :background nil 'default)
  17607. color)))
  17608. (hash (sha1 (prin1-to-string
  17609. (list org-format-latex-header
  17610. org-latex-default-packages-alist
  17611. org-latex-packages-alist
  17612. org-format-latex-options
  17613. forbuffer value fg bg))))
  17614. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17615. (absprefix (expand-file-name prefix dir))
  17616. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17617. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17618. (sep (and block-type "\n\n"))
  17619. (link (concat sep "[[file:" linkfile "]]" sep))
  17620. (options
  17621. (org-combine-plists
  17622. org-format-latex-options
  17623. `(:foreground ,fg :background ,bg))))
  17624. (when msg (message msg cnt))
  17625. (unless checkdir-flag ; Ensure the directory exists.
  17626. (setq checkdir-flag t)
  17627. (let ((todir (file-name-directory absprefix)))
  17628. (unless (file-directory-p todir)
  17629. (make-directory todir t))))
  17630. (unless (file-exists-p movefile)
  17631. (org-create-formula-image
  17632. value movefile options forbuffer processing-type))
  17633. (if overlays
  17634. (progn
  17635. (dolist (o (overlays-in beg end))
  17636. (when (eq (overlay-get o 'org-overlay-type)
  17637. 'org-latex-overlay)
  17638. (delete-overlay o)))
  17639. (org--format-latex-make-overlay beg end movefile imagetype)
  17640. (goto-char end))
  17641. (delete-region beg end)
  17642. (insert
  17643. (org-add-props link
  17644. (list 'org-latex-src
  17645. (replace-regexp-in-string "\"" "" value)
  17646. 'org-latex-src-embed-type
  17647. (if block-type 'paragraph 'character)))))))
  17648. ((eq processing-type 'mathml)
  17649. ;; Process to MathML.
  17650. (unless (org-format-latex-mathml-available-p)
  17651. (user-error "LaTeX to MathML converter not configured"))
  17652. (cl-incf cnt)
  17653. (when msg (message msg cnt))
  17654. (goto-char beg)
  17655. (delete-region beg end)
  17656. (insert (org-format-latex-as-mathml
  17657. value block-type prefix dir)))
  17658. (t
  17659. (error "Unknown conversion process %s for LaTeX fragments"
  17660. processing-type)))))))))))
  17661. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17662. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17663. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17664. sucessful, return the portion between \"<math...> </math>\"
  17665. elements otherwise return nil. When MATHML-FILE is specified,
  17666. write the results in to that file. When invoked as an
  17667. interactive command, prompt for LATEX-FRAG, with initial value
  17668. set to the current active region and echo the results for user
  17669. inspection."
  17670. (interactive (list (let ((frag (when (org-region-active-p)
  17671. (buffer-substring-no-properties
  17672. (region-beginning) (region-end)))))
  17673. (read-string "LaTeX Fragment: " frag nil frag))))
  17674. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17675. (let* ((tmp-in-file
  17676. (let ((file (file-relative-name
  17677. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17678. (write-region latex-frag nil file)
  17679. file))
  17680. (tmp-out-file (file-relative-name
  17681. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17682. (cmd (format-spec
  17683. org-latex-to-mathml-convert-command
  17684. `((?j . ,(and org-latex-to-mathml-jar-file
  17685. (shell-quote-argument
  17686. (expand-file-name
  17687. org-latex-to-mathml-jar-file))))
  17688. (?I . ,(shell-quote-argument tmp-in-file))
  17689. (?i . ,latex-frag)
  17690. (?o . ,(shell-quote-argument tmp-out-file)))))
  17691. mathml shell-command-output)
  17692. (when (called-interactively-p 'any)
  17693. (unless (org-format-latex-mathml-available-p)
  17694. (user-error "LaTeX to MathML converter not configured")))
  17695. (message "Running %s" cmd)
  17696. (setq shell-command-output (shell-command-to-string cmd))
  17697. (setq mathml
  17698. (when (file-readable-p tmp-out-file)
  17699. (with-current-buffer (find-file-noselect tmp-out-file t)
  17700. (goto-char (point-min))
  17701. (when (re-search-forward
  17702. (concat
  17703. (regexp-quote
  17704. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17705. "[^>]*?>"
  17706. "\\(.\\|\n\\)*"
  17707. "</math>")
  17708. nil t)
  17709. (prog1 (match-string 0) (kill-buffer))))))
  17710. (cond
  17711. (mathml
  17712. (setq mathml
  17713. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17714. (when mathml-file
  17715. (write-region mathml nil mathml-file))
  17716. (when (called-interactively-p 'any)
  17717. (message mathml)))
  17718. ((message "LaTeX to MathML conversion failed")
  17719. (message shell-command-output)))
  17720. (delete-file tmp-in-file)
  17721. (when (file-exists-p tmp-out-file)
  17722. (delete-file tmp-out-file))
  17723. mathml))
  17724. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17725. prefix &optional dir)
  17726. "Use `org-create-math-formula' but check local cache first."
  17727. (let* ((absprefix (expand-file-name prefix dir))
  17728. (print-length nil) (print-level nil)
  17729. (formula-id (concat
  17730. "formula-"
  17731. (sha1
  17732. (prin1-to-string
  17733. (list latex-frag
  17734. org-latex-to-mathml-convert-command)))))
  17735. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17736. (formula-cache-dir (file-name-directory formula-cache)))
  17737. (unless (file-directory-p formula-cache-dir)
  17738. (make-directory formula-cache-dir t))
  17739. (unless (file-exists-p formula-cache)
  17740. (org-create-math-formula latex-frag formula-cache))
  17741. (if (file-exists-p formula-cache)
  17742. ;; Successful conversion. Return the link to MathML file.
  17743. (org-add-props
  17744. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17745. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17746. 'org-latex-src-embed-type (if latex-frag-type
  17747. 'paragraph 'character)))
  17748. ;; Failed conversion. Return the LaTeX fragment verbatim
  17749. latex-frag)))
  17750. (declare-function org-export-get-backend "ox" (name))
  17751. (declare-function org-export--get-global-options "ox" (&optional backend))
  17752. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17753. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17754. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17755. (defun org-create-formula--latex-header ()
  17756. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17757. (let ((info (org-combine-plists (org-export--get-global-options
  17758. (org-export-get-backend 'latex))
  17759. (org-export--get-inbuffer-options
  17760. (org-export-get-backend 'latex)))))
  17761. (org-latex-guess-babel-language
  17762. (org-latex-guess-inputenc
  17763. (org-splice-latex-header
  17764. org-format-latex-header
  17765. org-latex-default-packages-alist
  17766. org-latex-packages-alist t
  17767. (plist-get info :latex-header)))
  17768. info)))
  17769. (defun org--get-display-dpi ()
  17770. "Get the DPI of the display.
  17771. Assumes that the display has the same pixel width in the
  17772. horizontal and vertical directions."
  17773. (if (display-graphic-p)
  17774. (round (/ (display-pixel-height)
  17775. (/ (display-mm-height) 25.4)))
  17776. (error "Attempt to calculate the dpi of a non-graphic display")))
  17777. (defun org-create-formula-image
  17778. (string tofile options buffer &optional processing-type)
  17779. "Create an image from LaTeX source using external processes.
  17780. The LaTeX STRING is saved to a temporary LaTeX file, then
  17781. converted to an image file by process PROCESSING-TYPE defined in
  17782. `org-preview-latex-process-alist'. A nil value defaults to
  17783. `org-preview-latex-default-process'.
  17784. The generated image file is eventually moved to TOFILE.
  17785. The OPTIONS argument controls the size, foreground color and
  17786. background color of the generated image.
  17787. When BUFFER non-nil, this function is used for LaTeX previewing.
  17788. Otherwise, it is used to deal with LaTeX snippets showed in
  17789. a HTML file."
  17790. (let* ((processing-type (or processing-type
  17791. org-preview-latex-default-process))
  17792. (processing-info
  17793. (cdr (assq processing-type org-preview-latex-process-alist)))
  17794. (programs (plist-get processing-info :programs))
  17795. (error-message (or (plist-get processing-info :message) ""))
  17796. (use-xcolor (plist-get processing-info :use-xcolor))
  17797. (image-input-type (plist-get processing-info :image-input-type))
  17798. (image-output-type (plist-get processing-info :image-output-type))
  17799. (post-clean (or (plist-get processing-info :post-clean)
  17800. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17801. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17802. (latex-header (or (plist-get processing-info :latex-header)
  17803. (org-create-formula--latex-header)))
  17804. (latex-compiler (plist-get processing-info :latex-compiler))
  17805. (image-converter (plist-get processing-info :image-converter))
  17806. (tmpdir temporary-file-directory)
  17807. (texfilebase (make-temp-name
  17808. (expand-file-name "orgtex" tmpdir)))
  17809. (texfile (concat texfilebase ".tex"))
  17810. (font-height (face-attribute 'default :height nil))
  17811. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17812. '(1.0 . 1.0)))
  17813. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17814. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17815. (dpi (* scale (floor (if buffer font-height 140.0))))
  17816. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17817. "Black"))
  17818. (bg (or (plist-get options (if buffer :background :html-background))
  17819. "Transparent"))
  17820. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17821. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17822. (dolist (program programs)
  17823. (org-check-external-command program error-message))
  17824. (if use-xcolor
  17825. (progn (if (eq fg 'default)
  17826. (setq fg (org-latex-color :foreground))
  17827. (setq fg (org-latex-color-format fg)))
  17828. (if (eq bg 'default)
  17829. (setq bg (org-latex-color :background))
  17830. (setq bg (org-latex-color-format
  17831. (if (string= bg "Transparent") "white" bg))))
  17832. (with-temp-file texfile
  17833. (insert latex-header)
  17834. (insert "\n\\begin{document}\n"
  17835. "\\definecolor{fg}{rgb}{" fg "}\n"
  17836. "\\definecolor{bg}{rgb}{" bg "}\n"
  17837. "\n\\pagecolor{bg}\n"
  17838. "\n{\\color{fg}\n"
  17839. string
  17840. "\n}\n"
  17841. "\n\\end{document}\n")))
  17842. (if (eq fg 'default)
  17843. (setq fg (org-dvipng-color :foreground))
  17844. (unless (string= fg "Transparent")
  17845. (setq fg (org-dvipng-color-format fg))))
  17846. (if (eq bg 'default)
  17847. (setq bg (org-dvipng-color :background))
  17848. (unless (string= bg "Transparent")
  17849. (setq bg (org-dvipng-color-format bg))))
  17850. (with-temp-file texfile
  17851. (insert latex-header)
  17852. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17853. (let* ((err-msg (format "Please adjust '%s' part of \
  17854. `org-preview-latex-process-alist'."
  17855. processing-type))
  17856. (image-input-file
  17857. (org-compile-file
  17858. texfile latex-compiler image-input-type err-msg log-buf))
  17859. (image-output-file
  17860. (org-compile-file
  17861. image-input-file image-converter image-output-type err-msg log-buf
  17862. `((?F . ,(shell-quote-argument fg))
  17863. (?B . ,(shell-quote-argument bg))
  17864. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17865. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17866. (copy-file image-output-file tofile 'replace)
  17867. (dolist (e post-clean)
  17868. (when (file-exists-p (concat texfilebase e))
  17869. (delete-file (concat texfilebase e))))
  17870. image-output-file)))
  17871. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17872. "Fill a LaTeX header template TPL.
  17873. In the template, the following place holders will be recognized:
  17874. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17875. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17876. [PACKAGES] \\usepackage statements for PKG
  17877. [NO-PACKAGES] do not include PKG
  17878. [EXTRA] the string EXTRA
  17879. [NO-EXTRA] do not include EXTRA
  17880. For backward compatibility, if both the positive and the negative place
  17881. holder is missing, the positive one (without the \"NO-\") will be
  17882. assumed to be present at the end of the template.
  17883. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17884. EXTRA is a string.
  17885. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17886. (let (rpl (end ""))
  17887. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17888. (setq rpl (if (or (match-end 1) (not def-pkg))
  17889. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17890. tpl (replace-match rpl t t tpl))
  17891. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17892. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17893. (setq rpl (if (or (match-end 1) (not pkg))
  17894. "" (org-latex-packages-to-string pkg snippets-p t))
  17895. tpl (replace-match rpl t t tpl))
  17896. (when pkg (setq end
  17897. (concat end "\n"
  17898. (org-latex-packages-to-string pkg snippets-p)))))
  17899. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17900. (setq rpl (if (or (match-end 1) (not extra))
  17901. "" (concat extra "\n"))
  17902. tpl (replace-match rpl t t tpl))
  17903. (when (and extra (string-match "\\S-" extra))
  17904. (setq end (concat end "\n" extra))))
  17905. (if (string-match "\\S-" end)
  17906. (concat tpl "\n" end)
  17907. tpl)))
  17908. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17909. "Turn an alist of packages into a string with the \\usepackage macros."
  17910. (setq pkg (mapconcat (lambda(p)
  17911. (cond
  17912. ((stringp p) p)
  17913. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17914. (format "%% Package %s omitted" (cadr p)))
  17915. ((equal "" (car p))
  17916. (format "\\usepackage{%s}" (cadr p)))
  17917. (t
  17918. (format "\\usepackage[%s]{%s}"
  17919. (car p) (cadr p)))))
  17920. pkg
  17921. "\n"))
  17922. (if newline (concat pkg "\n") pkg))
  17923. (defun org-dvipng-color (attr)
  17924. "Return a RGB color specification for dvipng."
  17925. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17926. (defun org-dvipng-color-format (color-name)
  17927. "Convert COLOR-NAME to a RGB color value for dvipng."
  17928. (apply #'format "rgb %s %s %s"
  17929. (mapcar 'org-normalize-color
  17930. (color-values color-name))))
  17931. (defun org-latex-color (attr)
  17932. "Return a RGB color for the LaTeX color package."
  17933. (org-latex-color-format (face-attribute 'default attr nil)))
  17934. (defun org-latex-color-format (color-name)
  17935. "Convert COLOR-NAME to a RGB color value."
  17936. (apply #'format "%s,%s,%s"
  17937. (mapcar 'org-normalize-color
  17938. (color-values color-name))))
  17939. (defun org-normalize-color (value)
  17940. "Return string to be used as color value for an RGB component."
  17941. (format "%g" (/ value 65535.0)))
  17942. ;; Image display
  17943. (defvar-local org-inline-image-overlays nil)
  17944. (defun org-toggle-inline-images (&optional include-linked)
  17945. "Toggle the display of inline images.
  17946. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17947. (interactive "P")
  17948. (if org-inline-image-overlays
  17949. (progn
  17950. (org-remove-inline-images)
  17951. (when (called-interactively-p 'interactive)
  17952. (message "Inline image display turned off")))
  17953. (org-display-inline-images include-linked)
  17954. (when (called-interactively-p 'interactive)
  17955. (message (if org-inline-image-overlays
  17956. (format "%d images displayed inline"
  17957. (length org-inline-image-overlays))
  17958. "No images to display inline")))))
  17959. (defun org-redisplay-inline-images ()
  17960. "Refresh the display of inline images."
  17961. (interactive)
  17962. (if (not org-inline-image-overlays)
  17963. (org-toggle-inline-images)
  17964. (org-toggle-inline-images)
  17965. (org-toggle-inline-images)))
  17966. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17967. "Display inline images.
  17968. An inline image is a link which follows either of these
  17969. conventions:
  17970. 1. Its path is a file with an extension matching return value
  17971. from `image-file-name-regexp' and it has no contents.
  17972. 2. Its description consists in a single link of the previous
  17973. type.
  17974. When optional argument INCLUDE-LINKED is non-nil, also links with
  17975. a text description part will be inlined. This can be nice for
  17976. a quick look at those images, but it does not reflect what
  17977. exported files will look like.
  17978. When optional argument REFRESH is non-nil, refresh existing
  17979. images between BEG and END. This will create new image displays
  17980. only if necessary. BEG and END default to the buffer
  17981. boundaries."
  17982. (interactive "P")
  17983. (when (display-graphic-p)
  17984. (unless refresh
  17985. (org-remove-inline-images)
  17986. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17987. (org-with-wide-buffer
  17988. (goto-char (or beg (point-min)))
  17989. (let ((case-fold-search t)
  17990. (file-extension-re (image-file-name-regexp)))
  17991. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17992. (let ((link (save-match-data (org-element-context))))
  17993. ;; Check if we're at an inline image.
  17994. (when (and (equal (org-element-property :type link) "file")
  17995. (or include-linked
  17996. (not (org-element-property :contents-begin link)))
  17997. (let ((parent (org-element-property :parent link)))
  17998. (or (not (eq (org-element-type parent) 'link))
  17999. (not (cdr (org-element-contents parent)))))
  18000. (string-match-p file-extension-re
  18001. (org-element-property :path link)))
  18002. (let ((file (expand-file-name
  18003. (org-link-unescape
  18004. (org-element-property :path link)))))
  18005. (when (file-exists-p file)
  18006. (let ((width
  18007. ;; Apply `org-image-actual-width' specifications.
  18008. (cond
  18009. ((not (image-type-available-p 'imagemagick)) nil)
  18010. ((eq org-image-actual-width t) nil)
  18011. ((listp org-image-actual-width)
  18012. (or
  18013. ;; First try to find a width among
  18014. ;; attributes associated to the paragraph
  18015. ;; containing link.
  18016. (let ((paragraph
  18017. (let ((e link))
  18018. (while (and (setq e (org-element-property
  18019. :parent e))
  18020. (not (eq (org-element-type e)
  18021. 'paragraph))))
  18022. e)))
  18023. (when paragraph
  18024. (save-excursion
  18025. (goto-char (org-element-property :begin paragraph))
  18026. (when
  18027. (re-search-forward
  18028. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18029. (org-element-property
  18030. :post-affiliated paragraph)
  18031. t)
  18032. (string-to-number (match-string 1))))))
  18033. ;; Otherwise, fall-back to provided number.
  18034. (car org-image-actual-width)))
  18035. ((numberp org-image-actual-width)
  18036. org-image-actual-width)))
  18037. (old (get-char-property-and-overlay
  18038. (org-element-property :begin link)
  18039. 'org-image-overlay)))
  18040. (if (and (car-safe old) refresh)
  18041. (image-refresh (overlay-get (cdr old) 'display))
  18042. (let ((image (create-image file
  18043. (and width 'imagemagick)
  18044. nil
  18045. :width width)))
  18046. (when image
  18047. (let* ((link
  18048. ;; If inline image is the description
  18049. ;; of another link, be sure to
  18050. ;; consider the latter as the one to
  18051. ;; apply the overlay on.
  18052. (let ((parent
  18053. (org-element-property :parent link)))
  18054. (if (eq (org-element-type parent) 'link)
  18055. parent
  18056. link)))
  18057. (ov (make-overlay
  18058. (org-element-property :begin link)
  18059. (progn
  18060. (goto-char
  18061. (org-element-property :end link))
  18062. (skip-chars-backward " \t")
  18063. (point)))))
  18064. (overlay-put ov 'display image)
  18065. (overlay-put ov 'face 'default)
  18066. (overlay-put ov 'org-image-overlay t)
  18067. (overlay-put
  18068. ov 'modification-hooks
  18069. (list 'org-display-inline-remove-overlay))
  18070. (push ov org-inline-image-overlays)))))))))))))))
  18071. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18072. "Remove inline-display overlay if a corresponding region is modified."
  18073. (let ((inhibit-modification-hooks t))
  18074. (when (and ov after)
  18075. (delete ov org-inline-image-overlays)
  18076. (delete-overlay ov))))
  18077. (defun org-remove-inline-images ()
  18078. "Remove inline display of images."
  18079. (interactive)
  18080. (mapc #'delete-overlay org-inline-image-overlays)
  18081. (setq org-inline-image-overlays nil))
  18082. ;;;; Key bindings
  18083. ;; Outline functions from `outline-mode-prefix-map'
  18084. ;; that can be remapped in Org:
  18085. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18086. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18087. (define-key org-mode-map [remap outline-forward-same-level]
  18088. 'org-forward-heading-same-level)
  18089. (define-key org-mode-map [remap outline-backward-same-level]
  18090. 'org-backward-heading-same-level)
  18091. (define-key org-mode-map [remap outline-show-branches]
  18092. 'org-kill-note-or-show-branches)
  18093. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18094. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18095. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18096. (define-key org-mode-map [remap outline-next-visible-heading]
  18097. 'org-next-visible-heading)
  18098. (define-key org-mode-map [remap outline-previous-visible-heading]
  18099. 'org-previous-visible-heading)
  18100. (define-key org-mode-map [remap show-children] 'org-show-children)
  18101. ;; Outline functions from `outline-mode-prefix-map' that can not
  18102. ;; be remapped in Org:
  18103. ;; - the column "key binding" shows whether the Outline function is still
  18104. ;; available in Org mode on the same key that it has been bound to in
  18105. ;; Outline mode:
  18106. ;; - "overridden": key used for a different functionality in Org mode
  18107. ;; - else: key still bound to the same Outline function in Org mode
  18108. ;; | Outline function | key binding | Org replacement |
  18109. ;; |------------------------------------+-------------+--------------------------|
  18110. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18111. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18112. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18113. ;; | `show-entry' | overridden | no replacement |
  18114. ;; | `show-branches' | `C-c C-k' | still same function |
  18115. ;; | `show-subtree' | overridden | visibility cycling |
  18116. ;; | `show-all' | overridden | no replacement |
  18117. ;; | `hide-subtree' | overridden | visibility cycling |
  18118. ;; | `hide-body' | overridden | no replacement |
  18119. ;; | `hide-entry' | overridden | visibility cycling |
  18120. ;; | `hide-leaves' | overridden | no replacement |
  18121. ;; | `hide-sublevels' | overridden | no replacement |
  18122. ;; | `hide-other' | overridden | no replacement |
  18123. ;; Make `C-c C-x' a prefix key
  18124. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18125. ;; TAB key with modifiers
  18126. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18127. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18128. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18129. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18130. ;; The following line is necessary under Suse GNU/Linux
  18131. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18132. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18133. (define-key org-mode-map [backtab] 'org-shifttab)
  18134. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18135. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18136. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18137. ;; Cursor keys with modifiers
  18138. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18139. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18140. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18141. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18142. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18143. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18144. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18145. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18146. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18147. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18148. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18149. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18150. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18151. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18152. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18153. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18154. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18155. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18156. ;; Babel keys
  18157. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18158. (dolist (pair org-babel-key-bindings)
  18159. (define-key org-babel-map (car pair) (cdr pair)))
  18160. ;;; Extra keys for tty access.
  18161. ;; We only set them when really needed because otherwise the
  18162. ;; menus don't show the simple keys
  18163. (when (or org-use-extra-keys (not window-system))
  18164. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18165. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18166. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18167. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18168. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18169. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18170. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18171. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18172. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18173. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18174. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18175. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18176. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18177. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18178. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18179. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18180. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18181. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18182. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18183. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18184. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18185. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18186. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18187. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18188. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18189. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18190. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18191. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18192. ;; All the other keys
  18193. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18194. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18195. (if (boundp 'narrow-map)
  18196. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18197. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18198. (if (boundp 'narrow-map)
  18199. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18200. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18201. (if (boundp 'narrow-map)
  18202. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18203. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18204. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18205. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18206. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18207. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18208. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18209. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18210. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18211. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18212. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18213. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18214. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18215. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18216. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18217. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18218. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18219. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18220. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18221. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18222. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18223. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18224. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18225. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18226. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18227. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18228. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18229. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18230. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18231. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18232. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18233. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18234. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18235. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18236. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18237. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18238. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18239. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18240. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18241. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18242. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18243. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18244. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18245. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18246. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18247. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18248. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18249. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18250. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18251. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18252. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18253. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18254. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18255. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18256. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18257. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18258. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18259. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18260. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18261. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18262. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18263. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18264. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18265. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18266. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18267. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18268. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18269. (org-defkey org-mode-map "\C-m" 'org-return)
  18270. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18271. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18272. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18273. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18274. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18275. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18276. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18277. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18278. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18279. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18280. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18281. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18282. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18283. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18284. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18285. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18286. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18287. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18288. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18289. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18290. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18291. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18292. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18293. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18294. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18295. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18296. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18297. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18298. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18299. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18300. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18301. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18302. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18303. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18304. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18305. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18306. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18307. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18308. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18309. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18310. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18311. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18312. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18313. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18314. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18315. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18316. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18317. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18318. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18319. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18320. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18321. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18322. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18323. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18324. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18325. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18326. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18327. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18328. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18329. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18330. (defconst org-speed-commands-default
  18331. '(
  18332. ("Outline Navigation")
  18333. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18334. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18335. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18336. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18337. ("F" . org-next-block)
  18338. ("B" . org-previous-block)
  18339. ("u" . (org-speed-move-safe 'outline-up-heading))
  18340. ("j" . org-goto)
  18341. ("g" . (org-refile t))
  18342. ("Outline Visibility")
  18343. ("c" . org-cycle)
  18344. ("C" . org-shifttab)
  18345. (" " . org-display-outline-path)
  18346. ("s" . org-narrow-to-subtree)
  18347. ("=" . org-columns)
  18348. ("Outline Structure Editing")
  18349. ("U" . org-metaup)
  18350. ("D" . org-metadown)
  18351. ("r" . org-metaright)
  18352. ("l" . org-metaleft)
  18353. ("R" . org-shiftmetaright)
  18354. ("L" . org-shiftmetaleft)
  18355. ("i" . (progn (forward-char 1) (call-interactively
  18356. 'org-insert-heading-respect-content)))
  18357. ("^" . org-sort)
  18358. ("w" . org-refile)
  18359. ("a" . org-archive-subtree-default-with-confirmation)
  18360. ("@" . org-mark-subtree)
  18361. ("#" . org-toggle-comment)
  18362. ("Clock Commands")
  18363. ("I" . org-clock-in)
  18364. ("O" . org-clock-out)
  18365. ("Meta Data Editing")
  18366. ("t" . org-todo)
  18367. ("," . (org-priority))
  18368. ("0" . (org-priority ?\ ))
  18369. ("1" . (org-priority ?A))
  18370. ("2" . (org-priority ?B))
  18371. ("3" . (org-priority ?C))
  18372. (":" . org-set-tags-command)
  18373. ("e" . org-set-effort)
  18374. ("E" . org-inc-effort)
  18375. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18376. (org-entry-put (point) "APPT_WARNTIME" m)))
  18377. ("Agenda Views etc")
  18378. ("v" . org-agenda)
  18379. ("/" . org-sparse-tree)
  18380. ("Misc")
  18381. ("o" . org-open-at-point)
  18382. ("?" . org-speed-command-help)
  18383. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18384. (">" . (org-agenda-remove-restriction-lock))
  18385. )
  18386. "The default speed commands.")
  18387. (defun org-print-speed-command (e)
  18388. (if (> (length (car e)) 1)
  18389. (progn
  18390. (princ "\n")
  18391. (princ (car e))
  18392. (princ "\n")
  18393. (princ (make-string (length (car e)) ?-))
  18394. (princ "\n"))
  18395. (princ (car e))
  18396. (princ " ")
  18397. (if (symbolp (cdr e))
  18398. (princ (symbol-name (cdr e)))
  18399. (prin1 (cdr e)))
  18400. (princ "\n")))
  18401. (defun org-speed-command-help ()
  18402. "Show the available speed commands."
  18403. (interactive)
  18404. (if (not org-use-speed-commands)
  18405. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18406. (with-output-to-temp-buffer "*Help*"
  18407. (princ "User-defined Speed commands\n===========================\n")
  18408. (mapc #'org-print-speed-command org-speed-commands-user)
  18409. (princ "\n")
  18410. (princ "Built-in Speed commands\n=======================\n")
  18411. (mapc #'org-print-speed-command org-speed-commands-default))
  18412. (with-current-buffer "*Help*"
  18413. (setq truncate-lines t))))
  18414. (defun org-speed-move-safe (cmd)
  18415. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18416. If not, return to the original position and throw an error."
  18417. (interactive)
  18418. (let ((pos (point)))
  18419. (call-interactively cmd)
  18420. (unless (and (bolp) (org-at-heading-p))
  18421. (goto-char pos)
  18422. (error "Boundary reached while executing %s" cmd))))
  18423. (defvar org-self-insert-command-undo-counter 0)
  18424. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18425. (defvar org-speed-command nil)
  18426. (defun org-speed-command-activate (keys)
  18427. "Hook for activating single-letter speed commands.
  18428. `org-speed-commands-default' specifies a minimal command set.
  18429. Use `org-speed-commands-user' for further customization."
  18430. (when (or (and (bolp) (looking-at org-outline-regexp))
  18431. (and (functionp org-use-speed-commands)
  18432. (funcall org-use-speed-commands)))
  18433. (cdr (assoc keys (append org-speed-commands-user
  18434. org-speed-commands-default)))))
  18435. (defun org-babel-speed-command-activate (keys)
  18436. "Hook for activating single-letter code block commands."
  18437. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18438. (cdr (assoc keys org-babel-key-bindings))))
  18439. (defcustom org-speed-command-hook
  18440. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18441. "Hook for activating speed commands at strategic locations.
  18442. Hook functions are called in sequence until a valid handler is
  18443. found.
  18444. Each hook takes a single argument, a user-pressed command key
  18445. which is also a `self-insert-command' from the global map.
  18446. Within the hook, examine the cursor position and the command key
  18447. and return nil or a valid handler as appropriate. Handler could
  18448. be one of an interactive command, a function, or a form.
  18449. Set `org-use-speed-commands' to non-nil value to enable this
  18450. hook. The default setting is `org-speed-command-activate'."
  18451. :group 'org-structure
  18452. :version "24.1"
  18453. :type 'hook)
  18454. (defun org-self-insert-command (N)
  18455. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18456. If the cursor is in a table looking at whitespace, the whitespace is
  18457. overwritten, and the table is not marked as requiring realignment."
  18458. (interactive "p")
  18459. (org-check-before-invisible-edit 'insert)
  18460. (cond
  18461. ((and org-use-speed-commands
  18462. (let ((kv (this-command-keys-vector)))
  18463. (setq org-speed-command
  18464. (run-hook-with-args-until-success
  18465. 'org-speed-command-hook
  18466. (make-string 1 (aref kv (1- (length kv))))))))
  18467. (cond
  18468. ((commandp org-speed-command)
  18469. (setq this-command org-speed-command)
  18470. (call-interactively org-speed-command))
  18471. ((functionp org-speed-command)
  18472. (funcall org-speed-command))
  18473. ((and org-speed-command (listp org-speed-command))
  18474. (eval org-speed-command))
  18475. (t (let (org-use-speed-commands)
  18476. (call-interactively 'org-self-insert-command)))))
  18477. ((and
  18478. (org-at-table-p)
  18479. (progn
  18480. ;; Check if we blank the field, and if that triggers align.
  18481. (and (featurep 'org-table) org-table-auto-blank-field
  18482. (memq last-command
  18483. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18484. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18485. ;; Got extra space, this field does not determine
  18486. ;; column width.
  18487. (let (org-table-may-need-update) (org-table-blank-field))
  18488. ;; No extra space, this field may determine column
  18489. ;; width.
  18490. (org-table-blank-field)))
  18491. t)
  18492. (eq N 1)
  18493. (looking-at "[^|\n]* \\( \\)|"))
  18494. ;; There is room for insertion without re-aligning the table.
  18495. (delete-region (match-beginning 1) (match-end 1))
  18496. (self-insert-command N))
  18497. (t
  18498. (setq org-table-may-need-update t)
  18499. (self-insert-command N)
  18500. (org-fix-tags-on-the-fly)
  18501. (when org-self-insert-cluster-for-undo
  18502. (if (not (eq last-command 'org-self-insert-command))
  18503. (setq org-self-insert-command-undo-counter 1)
  18504. (if (>= org-self-insert-command-undo-counter 20)
  18505. (setq org-self-insert-command-undo-counter 1)
  18506. (and (> org-self-insert-command-undo-counter 0)
  18507. buffer-undo-list (listp buffer-undo-list)
  18508. (not (cadr buffer-undo-list)) ; remove nil entry
  18509. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18510. (setq org-self-insert-command-undo-counter
  18511. (1+ org-self-insert-command-undo-counter))))))))
  18512. (defun org-check-before-invisible-edit (kind)
  18513. "Check is editing if kind KIND would be dangerous with invisible text around.
  18514. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18515. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18516. (when (and org-catch-invisible-edits
  18517. (or (not (boundp 'visible-mode)) (not visible-mode))
  18518. (or (get-char-property (point) 'invisible)
  18519. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18520. ;; OK, we need to take a closer look
  18521. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18522. (invisible-before-point (unless (bobp) (get-char-property
  18523. (1- (point)) 'invisible)))
  18524. (border-and-ok-direction
  18525. (or
  18526. ;; Check if we are acting predictably before invisible text
  18527. (and invisible-at-point (not invisible-before-point)
  18528. (memq kind '(insert delete-backward)))
  18529. ;; Check if we are acting predictably after invisible text
  18530. ;; This works not well, and I have turned it off. It seems
  18531. ;; better to always show and stop after invisible text.
  18532. ;; (and (not invisible-at-point) invisible-before-point
  18533. ;; (memq kind '(insert delete)))
  18534. )))
  18535. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18536. (memq invisible-before-point '(outline org-hide-block t)))
  18537. (when (eq org-catch-invisible-edits 'error)
  18538. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18539. (if (and org-custom-properties-overlays
  18540. (y-or-n-p "Display invisible properties in this buffer? "))
  18541. (org-toggle-custom-properties-visibility)
  18542. ;; Make the area visible
  18543. (save-excursion
  18544. (when invisible-before-point
  18545. (goto-char (previous-single-char-property-change
  18546. (point) 'invisible)))
  18547. (outline-show-subtree))
  18548. (cond
  18549. ((eq org-catch-invisible-edits 'show)
  18550. ;; That's it, we do the edit after showing
  18551. (message
  18552. "Unfolding invisible region around point before editing")
  18553. (sit-for 1))
  18554. ((and (eq org-catch-invisible-edits 'smart)
  18555. border-and-ok-direction)
  18556. (message "Unfolding invisible region around point before editing"))
  18557. (t
  18558. ;; Don't do the edit, make the user repeat it in full visibility
  18559. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18560. (defun org-fix-tags-on-the-fly ()
  18561. "Align tags in headline at point.
  18562. Unlike to `org-set-tags', it ignores region and sorting."
  18563. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18564. (org-at-heading-p))
  18565. (let ((org-ignore-region t)
  18566. (org-tags-sort-function nil))
  18567. (org-set-tags nil t))))
  18568. (defun org-delete-backward-char (N)
  18569. "Like `delete-backward-char', insert whitespace at field end in tables.
  18570. When deleting backwards, in tables this function will insert whitespace in
  18571. front of the next \"|\" separator, to keep the table aligned. The table will
  18572. still be marked for re-alignment if the field did fill the entire column,
  18573. because, in this case the deletion might narrow the column."
  18574. (interactive "p")
  18575. (save-match-data
  18576. (org-check-before-invisible-edit 'delete-backward)
  18577. (if (and (org-at-table-p)
  18578. (eq N 1)
  18579. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18580. (looking-at ".*?|"))
  18581. (let ((pos (point))
  18582. (noalign (looking-at "[^|\n\r]* |"))
  18583. (c org-table-may-need-update))
  18584. (backward-delete-char N)
  18585. (unless overwrite-mode
  18586. (skip-chars-forward "^|")
  18587. (insert " ")
  18588. (goto-char (1- pos)))
  18589. ;; noalign: if there were two spaces at the end, this field
  18590. ;; does not determine the width of the column.
  18591. (when noalign (setq org-table-may-need-update c)))
  18592. (backward-delete-char N)
  18593. (org-fix-tags-on-the-fly))))
  18594. (defun org-delete-char (N)
  18595. "Like `delete-char', but insert whitespace at field end in tables.
  18596. When deleting characters, in tables this function will insert whitespace in
  18597. front of the next \"|\" separator, to keep the table aligned. The table will
  18598. still be marked for re-alignment if the field did fill the entire column,
  18599. because, in this case the deletion might narrow the column."
  18600. (interactive "p")
  18601. (save-match-data
  18602. (org-check-before-invisible-edit 'delete)
  18603. (if (and (org-at-table-p)
  18604. (not (bolp))
  18605. (not (= (char-after) ?|))
  18606. (eq N 1))
  18607. (if (looking-at ".*?|")
  18608. (let ((pos (point))
  18609. (noalign (looking-at "[^|\n\r]* |"))
  18610. (c org-table-may-need-update))
  18611. (replace-match
  18612. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18613. (goto-char pos)
  18614. ;; noalign: if there were two spaces at the end, this field
  18615. ;; does not determine the width of the column.
  18616. (when noalign (setq org-table-may-need-update c)))
  18617. (delete-char N))
  18618. (delete-char N)
  18619. (org-fix-tags-on-the-fly))))
  18620. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18621. (put 'org-self-insert-command 'delete-selection
  18622. (lambda ()
  18623. (not (run-hook-with-args-until-success
  18624. 'self-insert-uses-region-functions))))
  18625. (put 'orgtbl-self-insert-command 'delete-selection
  18626. (lambda ()
  18627. (not (run-hook-with-args-until-success
  18628. 'self-insert-uses-region-functions))))
  18629. (put 'org-delete-char 'delete-selection 'supersede)
  18630. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18631. (put 'org-yank 'delete-selection 'yank)
  18632. ;; Make `flyspell-mode' delay after some commands
  18633. (put 'org-self-insert-command 'flyspell-delayed t)
  18634. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18635. (put 'org-delete-char 'flyspell-delayed t)
  18636. (put 'org-delete-backward-char 'flyspell-delayed t)
  18637. ;; Make pabbrev-mode expand after Org mode commands
  18638. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18639. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18640. (defun org-remap (map &rest commands)
  18641. "In MAP, remap the functions given in COMMANDS.
  18642. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18643. (let (new old)
  18644. (while commands
  18645. (setq old (pop commands) new (pop commands))
  18646. (org-defkey map (vector 'remap old) new))))
  18647. (defun org-transpose-words ()
  18648. "Transpose words for Org.
  18649. This uses the `org-mode-transpose-word-syntax-table' syntax
  18650. table, which interprets characters in `org-emphasis-alist' as
  18651. word constituents."
  18652. (interactive)
  18653. (with-syntax-table org-mode-transpose-word-syntax-table
  18654. (call-interactively 'transpose-words)))
  18655. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18656. (when (eq org-enable-table-editor 'optimized)
  18657. ;; If the user wants maximum table support, we need to hijack
  18658. ;; some standard editing functions
  18659. (org-remap org-mode-map
  18660. 'self-insert-command 'org-self-insert-command
  18661. 'delete-char 'org-delete-char
  18662. 'delete-backward-char 'org-delete-backward-char)
  18663. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18664. (defvar org-ctrl-c-ctrl-c-hook nil
  18665. "Hook for functions attaching themselves to `C-c C-c'.
  18666. This can be used to add additional functionality to the C-c C-c
  18667. key which executes context-dependent commands. This hook is run
  18668. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18669. run after the last test.
  18670. Each function will be called with no arguments. The function
  18671. must check if the context is appropriate for it to act. If yes,
  18672. it should do its thing and then return a non-nil value. If the
  18673. context is wrong, just do nothing and return nil.")
  18674. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18675. "Hook for functions attaching themselves to `C-c C-c'.
  18676. This can be used to add additional functionality to the C-c C-c
  18677. key which executes context-dependent commands. This hook is run
  18678. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18679. before the first test.
  18680. Each function will be called with no arguments. The function
  18681. must check if the context is appropriate for it to act. If yes,
  18682. it should do its thing and then return a non-nil value. If the
  18683. context is wrong, just do nothing and return nil.")
  18684. (defvar org-tab-first-hook nil
  18685. "Hook for functions to attach themselves to TAB.
  18686. See `org-ctrl-c-ctrl-c-hook' for more information.
  18687. This hook runs as the first action when TAB is pressed, even before
  18688. `org-cycle' messes around with the `outline-regexp' to cater for
  18689. inline tasks and plain list item folding.
  18690. If any function in this hook returns t, any other actions that
  18691. would have been caused by TAB (such as table field motion or visibility
  18692. cycling) will not occur.")
  18693. (defvar org-tab-after-check-for-table-hook nil
  18694. "Hook for functions to attach themselves to TAB.
  18695. See `org-ctrl-c-ctrl-c-hook' for more information.
  18696. This hook runs after it has been established that the cursor is not in a
  18697. table, but before checking if the cursor is in a headline or if global cycling
  18698. should be done.
  18699. If any function in this hook returns t, not other actions like visibility
  18700. cycling will be done.")
  18701. (defvar org-tab-after-check-for-cycling-hook nil
  18702. "Hook for functions to attach themselves to TAB.
  18703. See `org-ctrl-c-ctrl-c-hook' for more information.
  18704. This hook runs after it has been established that not table field motion and
  18705. not visibility should be done because of current context. This is probably
  18706. the place where a package like yasnippets can hook in.")
  18707. (defvar org-tab-before-tab-emulation-hook nil
  18708. "Hook for functions to attach themselves to TAB.
  18709. See `org-ctrl-c-ctrl-c-hook' for more information.
  18710. This hook runs after every other options for TAB have been exhausted, but
  18711. before indentation and \t insertion takes place.")
  18712. (defvar org-metaleft-hook nil
  18713. "Hook for functions attaching themselves to `M-left'.
  18714. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18715. (defvar org-metaright-hook nil
  18716. "Hook for functions attaching themselves to `M-right'.
  18717. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18718. (defvar org-metaup-hook nil
  18719. "Hook for functions attaching themselves to `M-up'.
  18720. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18721. (defvar org-metadown-hook nil
  18722. "Hook for functions attaching themselves to `M-down'.
  18723. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18724. (defvar org-shiftmetaleft-hook nil
  18725. "Hook for functions attaching themselves to `M-S-left'.
  18726. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18727. (defvar org-shiftmetaright-hook nil
  18728. "Hook for functions attaching themselves to `M-S-right'.
  18729. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18730. (defvar org-shiftmetaup-hook nil
  18731. "Hook for functions attaching themselves to `M-S-up'.
  18732. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18733. (defvar org-shiftmetadown-hook nil
  18734. "Hook for functions attaching themselves to `M-S-down'.
  18735. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18736. (defvar org-metareturn-hook nil
  18737. "Hook for functions attaching themselves to `M-RET'.
  18738. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18739. (defvar org-shiftup-hook nil
  18740. "Hook for functions attaching themselves to `S-up'.
  18741. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18742. (defvar org-shiftup-final-hook nil
  18743. "Hook for functions attaching themselves to `S-up'.
  18744. This one runs after all other options except shift-select have been excluded.
  18745. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18746. (defvar org-shiftdown-hook nil
  18747. "Hook for functions attaching themselves to `S-down'.
  18748. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18749. (defvar org-shiftdown-final-hook nil
  18750. "Hook for functions attaching themselves to `S-down'.
  18751. This one runs after all other options except shift-select have been excluded.
  18752. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18753. (defvar org-shiftleft-hook nil
  18754. "Hook for functions attaching themselves to `S-left'.
  18755. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18756. (defvar org-shiftleft-final-hook nil
  18757. "Hook for functions attaching themselves to `S-left'.
  18758. This one runs after all other options except shift-select have been excluded.
  18759. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18760. (defvar org-shiftright-hook nil
  18761. "Hook for functions attaching themselves to `S-right'.
  18762. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18763. (defvar org-shiftright-final-hook nil
  18764. "Hook for functions attaching themselves to `S-right'.
  18765. This one runs after all other options except shift-select have been excluded.
  18766. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18767. (defun org-modifier-cursor-error ()
  18768. "Throw an error, a modified cursor command was applied in wrong context."
  18769. (user-error "This command is active in special context like tables, headlines or items"))
  18770. (defun org-shiftselect-error ()
  18771. "Throw an error because Shift-Cursor command was applied in wrong context."
  18772. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18773. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18774. (user-error "This command works only in special context like headlines or timestamps")))
  18775. (defun org-call-for-shift-select (cmd)
  18776. (let ((this-command-keys-shift-translated t))
  18777. (call-interactively cmd)))
  18778. (defun org-shifttab (&optional arg)
  18779. "Global visibility cycling or move to previous table field.
  18780. Call `org-table-previous-field' within a table.
  18781. When ARG is nil, cycle globally through visibility states.
  18782. When ARG is a numeric prefix, show contents of this level."
  18783. (interactive "P")
  18784. (cond
  18785. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18786. ((integerp arg)
  18787. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18788. (message "Content view to level: %d" arg)
  18789. (org-content (prefix-numeric-value arg2))
  18790. (org-cycle-show-empty-lines t)
  18791. (setq org-cycle-global-status 'overview)))
  18792. (t (call-interactively 'org-global-cycle))))
  18793. (defun org-shiftmetaleft ()
  18794. "Promote subtree or delete table column.
  18795. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18796. `org-table-delete-column', depending on context. See the
  18797. individual commands for more information."
  18798. (interactive)
  18799. (cond
  18800. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18801. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18802. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18803. ((if (not (org-region-active-p)) (org-at-item-p)
  18804. (save-excursion (goto-char (region-beginning))
  18805. (org-at-item-p)))
  18806. (call-interactively 'org-outdent-item-tree))
  18807. (t (org-modifier-cursor-error))))
  18808. (defun org-shiftmetaright ()
  18809. "Demote subtree or insert table column.
  18810. Calls `org-demote-subtree', `org-indent-item-tree', or
  18811. `org-table-insert-column', depending on context. See the
  18812. individual commands for more information."
  18813. (interactive)
  18814. (cond
  18815. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18816. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18817. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18818. ((if (not (org-region-active-p)) (org-at-item-p)
  18819. (save-excursion (goto-char (region-beginning))
  18820. (org-at-item-p)))
  18821. (call-interactively 'org-indent-item-tree))
  18822. (t (org-modifier-cursor-error))))
  18823. (defun org-shiftmetaup (&optional _arg)
  18824. "Drag the line at point up.
  18825. In a table, kill the current row.
  18826. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18827. but also adjust the previous clocked item in the clock history.
  18828. Everywhere else, drag the line at point up."
  18829. (interactive "P")
  18830. (cond
  18831. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18832. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18833. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18834. (call-interactively 'org-timestamp-up)))
  18835. (t (call-interactively 'org-drag-line-backward))))
  18836. (defun org-shiftmetadown (&optional _arg)
  18837. "Drag the line at point down.
  18838. In a table, insert an empty row at the current line.
  18839. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18840. but also adjust the previous clocked item in the clock history.
  18841. Everywhere else, drag the line at point down."
  18842. (interactive "P")
  18843. (cond
  18844. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18845. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18846. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18847. (call-interactively 'org-timestamp-down)))
  18848. (t (call-interactively 'org-drag-line-forward))))
  18849. (defsubst org-hidden-tree-error ()
  18850. (user-error
  18851. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18852. (defun org-metaleft (&optional _arg)
  18853. "Promote heading, list item at point or move table column left.
  18854. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18855. depending on context. With no specific context, calls the Emacs
  18856. default `backward-word'. See the individual commands for more
  18857. information.
  18858. This function runs the hook `org-metaleft-hook' as a first step,
  18859. and returns at first non-nil value."
  18860. (interactive "P")
  18861. (cond
  18862. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18863. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18864. ((org-with-limited-levels
  18865. (or (org-at-heading-p)
  18866. (and (org-region-active-p)
  18867. (save-excursion
  18868. (goto-char (region-beginning))
  18869. (org-at-heading-p)))))
  18870. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18871. (call-interactively 'org-do-promote))
  18872. ;; At an inline task.
  18873. ((org-at-heading-p)
  18874. (call-interactively 'org-inlinetask-promote))
  18875. ((or (org-at-item-p)
  18876. (and (org-region-active-p)
  18877. (save-excursion
  18878. (goto-char (region-beginning))
  18879. (org-at-item-p))))
  18880. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18881. (call-interactively 'org-outdent-item))
  18882. (t (call-interactively 'backward-word))))
  18883. (defun org-metaright (&optional _arg)
  18884. "Demote heading, list item at point or move table column right.
  18885. In front of a drawer or a block keyword, indent it correctly.
  18886. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18887. `org-indent-drawer' or `org-indent-block' depending on context.
  18888. With no specific context, calls the Emacs default `forward-word'.
  18889. See the individual commands for more information.
  18890. This function runs the hook `org-metaright-hook' as a first step,
  18891. and returns at first non-nil value."
  18892. (interactive "P")
  18893. (cond
  18894. ((run-hook-with-args-until-success 'org-metaright-hook))
  18895. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18896. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18897. ((org-at-block-p) (call-interactively 'org-indent-block))
  18898. ((org-with-limited-levels
  18899. (or (org-at-heading-p)
  18900. (and (org-region-active-p)
  18901. (save-excursion
  18902. (goto-char (region-beginning))
  18903. (org-at-heading-p)))))
  18904. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18905. (call-interactively 'org-do-demote))
  18906. ;; At an inline task.
  18907. ((org-at-heading-p)
  18908. (call-interactively 'org-inlinetask-demote))
  18909. ((or (org-at-item-p)
  18910. (and (org-region-active-p)
  18911. (save-excursion
  18912. (goto-char (region-beginning))
  18913. (org-at-item-p))))
  18914. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18915. (call-interactively 'org-indent-item))
  18916. (t (call-interactively 'forward-word))))
  18917. (defun org-check-for-hidden (what)
  18918. "Check if there are hidden headlines/items in the current visual line.
  18919. WHAT can be either `headlines' or `items'. If the current line is
  18920. an outline or item heading and it has a folded subtree below it,
  18921. this function returns t, nil otherwise."
  18922. (let ((re (cond
  18923. ((eq what 'headlines) org-outline-regexp-bol)
  18924. ((eq what 'items) (org-item-beginning-re))
  18925. (t (error "This should not happen"))))
  18926. beg end)
  18927. (save-excursion
  18928. (catch 'exit
  18929. (unless (org-region-active-p)
  18930. (setq beg (point-at-bol))
  18931. (beginning-of-line 2)
  18932. (while (and (not (eobp)) ;; this is like `next-line'
  18933. (get-char-property (1- (point)) 'invisible))
  18934. (beginning-of-line 2))
  18935. (setq end (point))
  18936. (goto-char beg)
  18937. (goto-char (point-at-eol))
  18938. (setq end (max end (point)))
  18939. (while (re-search-forward re end t)
  18940. (when (get-char-property (match-beginning 0) 'invisible)
  18941. (throw 'exit t))))
  18942. nil))))
  18943. (defun org-metaup (&optional _arg)
  18944. "Move subtree up or move table row up.
  18945. Calls `org-move-subtree-up' or `org-table-move-row' or
  18946. `org-move-item-up', depending on context. See the individual commands
  18947. for more information."
  18948. (interactive "P")
  18949. (cond
  18950. ((run-hook-with-args-until-success 'org-metaup-hook))
  18951. ((org-region-active-p)
  18952. (let* ((a (min (region-beginning) (region-end)))
  18953. (b (1- (max (region-beginning) (region-end))))
  18954. (c (save-excursion (goto-char a)
  18955. (move-beginning-of-line 0)))
  18956. (d (save-excursion (goto-char a)
  18957. (move-end-of-line 0) (point))))
  18958. (transpose-regions a b c d)
  18959. (goto-char c)))
  18960. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18961. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18962. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18963. (t (org-drag-element-backward))))
  18964. (defun org-metadown (&optional _arg)
  18965. "Move subtree down or move table row down.
  18966. Calls `org-move-subtree-down' or `org-table-move-row' or
  18967. `org-move-item-down', depending on context. See the individual
  18968. commands for more information."
  18969. (interactive "P")
  18970. (cond
  18971. ((run-hook-with-args-until-success 'org-metadown-hook))
  18972. ((org-region-active-p)
  18973. (let* ((a (min (region-beginning) (region-end)))
  18974. (b (max (region-beginning) (region-end)))
  18975. (c (save-excursion (goto-char b)
  18976. (move-beginning-of-line 1)))
  18977. (d (save-excursion (goto-char b)
  18978. (move-end-of-line 1) (1+ (point)))))
  18979. (transpose-regions a b c d)
  18980. (goto-char d)))
  18981. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18982. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18983. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18984. (t (org-drag-element-forward))))
  18985. (defun org-shiftup (&optional arg)
  18986. "Increase item in timestamp or increase priority of current headline.
  18987. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18988. depending on context. See the individual commands for more information."
  18989. (interactive "P")
  18990. (cond
  18991. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18992. ((and org-support-shift-select (org-region-active-p))
  18993. (org-call-for-shift-select 'previous-line))
  18994. ((org-at-timestamp-p t)
  18995. (call-interactively (if org-edit-timestamp-down-means-later
  18996. 'org-timestamp-down 'org-timestamp-up)))
  18997. ((and (not (eq org-support-shift-select 'always))
  18998. org-enable-priority-commands
  18999. (org-at-heading-p))
  19000. (call-interactively 'org-priority-up))
  19001. ((and (not org-support-shift-select) (org-at-item-p))
  19002. (call-interactively 'org-previous-item))
  19003. ((org-clocktable-try-shift 'up arg))
  19004. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  19005. (org-support-shift-select
  19006. (org-call-for-shift-select 'previous-line))
  19007. (t (org-shiftselect-error))))
  19008. (defun org-shiftdown (&optional arg)
  19009. "Decrease item in timestamp or decrease priority of current headline.
  19010. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  19011. depending on context. See the individual commands for more information."
  19012. (interactive "P")
  19013. (cond
  19014. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  19015. ((and org-support-shift-select (org-region-active-p))
  19016. (org-call-for-shift-select 'next-line))
  19017. ((org-at-timestamp-p t)
  19018. (call-interactively (if org-edit-timestamp-down-means-later
  19019. 'org-timestamp-up 'org-timestamp-down)))
  19020. ((and (not (eq org-support-shift-select 'always))
  19021. org-enable-priority-commands
  19022. (org-at-heading-p))
  19023. (call-interactively 'org-priority-down))
  19024. ((and (not org-support-shift-select) (org-at-item-p))
  19025. (call-interactively 'org-next-item))
  19026. ((org-clocktable-try-shift 'down arg))
  19027. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19028. (org-support-shift-select
  19029. (org-call-for-shift-select 'next-line))
  19030. (t (org-shiftselect-error))))
  19031. (defun org-shiftright (&optional arg)
  19032. "Cycle the thing at point or in the current line, depending on context.
  19033. Depending on context, this does one of the following:
  19034. - switch a timestamp at point one day into the future
  19035. - on a headline, switch to the next TODO keyword.
  19036. - on an item, switch entire list to the next bullet type
  19037. - on a property line, switch to the next allowed value
  19038. - on a clocktable definition line, move time block into the future"
  19039. (interactive "P")
  19040. (cond
  19041. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19042. ((and org-support-shift-select (org-region-active-p))
  19043. (org-call-for-shift-select 'forward-char))
  19044. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19045. ((and (not (eq org-support-shift-select 'always))
  19046. (org-at-heading-p))
  19047. (let ((org-inhibit-logging
  19048. (not org-treat-S-cursor-todo-selection-as-state-change))
  19049. (org-inhibit-blocking
  19050. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19051. (org-call-with-arg 'org-todo 'right)))
  19052. ((or (and org-support-shift-select
  19053. (not (eq org-support-shift-select 'always))
  19054. (org-at-item-bullet-p))
  19055. (and (not org-support-shift-select) (org-at-item-p)))
  19056. (org-call-with-arg 'org-cycle-list-bullet nil))
  19057. ((and (not (eq org-support-shift-select 'always))
  19058. (org-at-property-p))
  19059. (call-interactively 'org-property-next-allowed-value))
  19060. ((org-clocktable-try-shift 'right arg))
  19061. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19062. (org-support-shift-select
  19063. (org-call-for-shift-select 'forward-char))
  19064. (t (org-shiftselect-error))))
  19065. (defun org-shiftleft (&optional arg)
  19066. "Cycle the thing at point or in the current line, depending on context.
  19067. Depending on context, this does one of the following:
  19068. - switch a timestamp at point one day into the past
  19069. - on a headline, switch to the previous TODO keyword.
  19070. - on an item, switch entire list to the previous bullet type
  19071. - on a property line, switch to the previous allowed value
  19072. - on a clocktable definition line, move time block into the past"
  19073. (interactive "P")
  19074. (cond
  19075. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19076. ((and org-support-shift-select (org-region-active-p))
  19077. (org-call-for-shift-select 'backward-char))
  19078. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19079. ((and (not (eq org-support-shift-select 'always))
  19080. (org-at-heading-p))
  19081. (let ((org-inhibit-logging
  19082. (not org-treat-S-cursor-todo-selection-as-state-change))
  19083. (org-inhibit-blocking
  19084. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19085. (org-call-with-arg 'org-todo 'left)))
  19086. ((or (and org-support-shift-select
  19087. (not (eq org-support-shift-select 'always))
  19088. (org-at-item-bullet-p))
  19089. (and (not org-support-shift-select) (org-at-item-p)))
  19090. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19091. ((and (not (eq org-support-shift-select 'always))
  19092. (org-at-property-p))
  19093. (call-interactively 'org-property-previous-allowed-value))
  19094. ((org-clocktable-try-shift 'left arg))
  19095. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19096. (org-support-shift-select
  19097. (org-call-for-shift-select 'backward-char))
  19098. (t (org-shiftselect-error))))
  19099. (defun org-shiftcontrolright ()
  19100. "Switch to next TODO set."
  19101. (interactive)
  19102. (cond
  19103. ((and org-support-shift-select (org-region-active-p))
  19104. (org-call-for-shift-select 'forward-word))
  19105. ((and (not (eq org-support-shift-select 'always))
  19106. (org-at-heading-p))
  19107. (org-call-with-arg 'org-todo 'nextset))
  19108. (org-support-shift-select
  19109. (org-call-for-shift-select 'forward-word))
  19110. (t (org-shiftselect-error))))
  19111. (defun org-shiftcontrolleft ()
  19112. "Switch to previous TODO set."
  19113. (interactive)
  19114. (cond
  19115. ((and org-support-shift-select (org-region-active-p))
  19116. (org-call-for-shift-select 'backward-word))
  19117. ((and (not (eq org-support-shift-select 'always))
  19118. (org-at-heading-p))
  19119. (org-call-with-arg 'org-todo 'previousset))
  19120. (org-support-shift-select
  19121. (org-call-for-shift-select 'backward-word))
  19122. (t (org-shiftselect-error))))
  19123. (defun org-shiftcontrolup (&optional n)
  19124. "Change timestamps synchronously up in CLOCK log lines.
  19125. Optional argument N tells to change by that many units."
  19126. (interactive "P")
  19127. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19128. (let (org-support-shift-select)
  19129. (org-clock-timestamps-up n))
  19130. (user-error "Not at a clock log")))
  19131. (defun org-shiftcontroldown (&optional n)
  19132. "Change timestamps synchronously down in CLOCK log lines.
  19133. Optional argument N tells to change by that many units."
  19134. (interactive "P")
  19135. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19136. (let (org-support-shift-select)
  19137. (org-clock-timestamps-down n))
  19138. (user-error "Not at a clock log")))
  19139. (defun org-increase-number-at-point (&optional inc)
  19140. "Increment the number at point.
  19141. With an optional prefix numeric argument INC, increment using
  19142. this numeric value."
  19143. (interactive "p")
  19144. (if (not (number-at-point))
  19145. (user-error "Not on a number")
  19146. (unless inc (setq inc 1))
  19147. (let ((pos (point))
  19148. (beg (skip-chars-backward "-+^/*0-9eE."))
  19149. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19150. (setq nap (buffer-substring-no-properties
  19151. (+ pos beg) (+ pos beg end)))
  19152. (delete-region (+ pos beg) (+ pos beg end))
  19153. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19154. (when (org-at-table-p)
  19155. (org-table-align)
  19156. (org-table-end-of-field 1))))
  19157. (defun org-decrease-number-at-point (&optional inc)
  19158. "Decrement the number at point.
  19159. With an optional prefix numeric argument INC, decrement using
  19160. this numeric value."
  19161. (interactive "p")
  19162. (org-increase-number-at-point (- (or inc 1))))
  19163. (defun org-ctrl-c-ret ()
  19164. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19165. (interactive)
  19166. (cond
  19167. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19168. (t (call-interactively 'org-insert-heading))))
  19169. (defun org-find-visible ()
  19170. (let ((s (point)))
  19171. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19172. (get-char-property s 'invisible)))
  19173. s))
  19174. (defun org-find-invisible ()
  19175. (let ((s (point)))
  19176. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19177. (not (get-char-property s 'invisible))))
  19178. s))
  19179. (defun org-copy-visible (beg end)
  19180. "Copy the visible parts of the region."
  19181. (interactive "r")
  19182. (let (snippets s)
  19183. (save-excursion
  19184. (save-restriction
  19185. (narrow-to-region beg end)
  19186. (setq s (goto-char (point-min)))
  19187. (while (not (= (point) (point-max)))
  19188. (goto-char (org-find-invisible))
  19189. (push (buffer-substring s (point)) snippets)
  19190. (setq s (goto-char (org-find-visible))))))
  19191. (kill-new (apply 'concat (nreverse snippets)))))
  19192. (defun org-copy-special ()
  19193. "Copy region in table or copy current subtree.
  19194. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19195. context. See the individual commands for more information."
  19196. (interactive)
  19197. (call-interactively
  19198. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19199. (defun org-cut-special ()
  19200. "Cut region in table or cut current subtree.
  19201. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19202. context. See the individual commands for more information."
  19203. (interactive)
  19204. (call-interactively
  19205. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19206. (defun org-paste-special (arg)
  19207. "Paste rectangular region into table, or past subtree relative to level.
  19208. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19209. See the individual commands for more information."
  19210. (interactive "P")
  19211. (if (org-at-table-p)
  19212. (org-table-paste-rectangle)
  19213. (org-paste-subtree arg)))
  19214. (defun org-edit-special (&optional arg)
  19215. "Call a special editor for the element at point.
  19216. When at a table, call the formula editor with `org-table-edit-formulas'.
  19217. When in a source code block, call `org-edit-src-code'.
  19218. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19219. When in an export block, call `org-edit-export-block'.
  19220. When at an #+INCLUDE keyword, visit the included file.
  19221. When at a footnote reference, call `org-edit-footnote-reference'
  19222. On a link, call `ffap' to visit the link at point.
  19223. Otherwise, return a user error."
  19224. (interactive "P")
  19225. (let ((element (org-element-at-point)))
  19226. (barf-if-buffer-read-only)
  19227. (pcase (org-element-type element)
  19228. (`src-block
  19229. (if (not arg) (org-edit-src-code)
  19230. (let* ((info (org-babel-get-src-block-info))
  19231. (lang (nth 0 info))
  19232. (params (nth 2 info))
  19233. (session (cdr (assq :session params))))
  19234. (if (not session) (org-edit-src-code)
  19235. ;; At a src-block with a session and function called with
  19236. ;; an ARG: switch to the buffer related to the inferior
  19237. ;; process.
  19238. (switch-to-buffer
  19239. (funcall (intern (concat "org-babel-prep-session:" lang))
  19240. session params))))))
  19241. (`keyword
  19242. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19243. (org-open-link-from-string
  19244. (format "[[%s]]"
  19245. (expand-file-name
  19246. (let ((value (org-element-property :value element)))
  19247. (cond ((not (org-string-nw-p value))
  19248. (user-error "No file to edit"))
  19249. ((string-match "\\`\"\\(.*?\\)\"" value)
  19250. (match-string 1 value))
  19251. ((string-match "\\`[^ \t\"]\\S-*" value)
  19252. (match-string 0 value))
  19253. (t (user-error "No valid file specified")))))))
  19254. (user-error "No special environment to edit here")))
  19255. (`table
  19256. (if (eq (org-element-property :type element) 'table.el)
  19257. (org-edit-table.el)
  19258. (call-interactively 'org-table-edit-formulas)))
  19259. ;; Only Org tables contain `table-row' type elements.
  19260. (`table-row (call-interactively 'org-table-edit-formulas))
  19261. (`example-block (org-edit-src-code))
  19262. (`export-block (org-edit-export-block))
  19263. (`fixed-width (org-edit-fixed-width-region))
  19264. (_
  19265. ;; No notable element at point. Though, we may be at a link or
  19266. ;; a footnote reference, which are objects. Thus, scan deeper.
  19267. (let ((context (org-element-context element)))
  19268. (pcase (org-element-type context)
  19269. (`footnote-reference (org-edit-footnote-reference))
  19270. (`inline-src-block (org-edit-inline-src-code))
  19271. (`link (call-interactively #'ffap))
  19272. (_ (user-error "No special environment to edit here"))))))))
  19273. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19274. (defun org-ctrl-c-ctrl-c (&optional arg)
  19275. "Set tags in headline, or update according to changed information at point.
  19276. This command does many different things, depending on context:
  19277. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19278. this is what we do.
  19279. - If the cursor is on a statistics cookie, update it.
  19280. - If the cursor is in a headline, prompt for tags and insert them
  19281. into the current line, aligned to `org-tags-column'. When called
  19282. with prefix arg, realign all tags in the current buffer.
  19283. - If the cursor is in one of the special #+KEYWORD lines, this
  19284. triggers scanning the buffer for these lines and updating the
  19285. information.
  19286. - If the cursor is inside a table, realign the table. This command
  19287. works even if the automatic table editor has been turned off.
  19288. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19289. the entire table.
  19290. - If the cursor is at a footnote reference or definition, jump to
  19291. the corresponding definition or references, respectively.
  19292. - If the cursor is a the beginning of a dynamic block, update it.
  19293. - If the current buffer is a capture buffer, close note and file it.
  19294. - If the cursor is on a <<<target>>>, update radio targets and
  19295. corresponding links in this buffer.
  19296. - If the cursor is on a numbered item in a plain list, renumber the
  19297. ordered list.
  19298. - If the cursor is on a checkbox, toggle it.
  19299. - If the cursor is on a code block, evaluate it. The variable
  19300. `org-confirm-babel-evaluate' can be used to control prompting
  19301. before code block evaluation, by default every code block
  19302. evaluation requires confirmation. Code block evaluation can be
  19303. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19304. (interactive "P")
  19305. (cond
  19306. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19307. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19308. (org-remove-occur-highlights)
  19309. (message "Temporary highlights/overlays removed from current buffer"))
  19310. ((and (local-variable-p 'org-finish-function)
  19311. (fboundp org-finish-function))
  19312. (funcall org-finish-function))
  19313. ((org-babel-hash-at-point))
  19314. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19315. ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
  19316. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19317. (user-error
  19318. (substitute-command-keys
  19319. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19320. (t
  19321. (let* ((context
  19322. (org-element-lineage
  19323. (org-element-context)
  19324. ;; Limit to supported contexts.
  19325. '(babel-call clock dynamic-block footnote-definition
  19326. footnote-reference inline-babel-call inline-src-block
  19327. item keyword node-property paragraph plain-list
  19328. property-drawer radio-target src-block
  19329. statistics-cookie table table-cell table-row
  19330. timestamp)
  19331. t))
  19332. (type (org-element-type context)))
  19333. ;; For convenience: at the first line of a paragraph on the same
  19334. ;; line as an item, apply function on that item instead.
  19335. (when (eq type 'paragraph)
  19336. (let ((parent (org-element-property :parent context)))
  19337. (when (and (eq (org-element-type parent) 'item)
  19338. (= (line-beginning-position)
  19339. (org-element-property :begin parent)))
  19340. (setq context parent)
  19341. (setq type 'item))))
  19342. ;; Act according to type of element or object at point.
  19343. (pcase type
  19344. ((or `babel-call `inline-babel-call)
  19345. (let ((info (org-babel-lob-get-info context)))
  19346. (when info (org-babel-execute-src-block nil info))))
  19347. (`clock (org-clock-update-time-maybe))
  19348. (`dynamic-block
  19349. (save-excursion
  19350. (goto-char (org-element-property :post-affiliated context))
  19351. (org-update-dblock)))
  19352. (`footnote-definition
  19353. (goto-char (org-element-property :post-affiliated context))
  19354. (call-interactively 'org-footnote-action))
  19355. (`footnote-reference (call-interactively #'org-footnote-action))
  19356. ((or `headline `inlinetask)
  19357. (save-excursion (goto-char (org-element-property :begin context))
  19358. (call-interactively #'org-set-tags)))
  19359. ((or `inline-src-block `src-block)
  19360. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19361. (org-babel-eval-wipe-error-buffer)
  19362. (org-babel-execute-src-block
  19363. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19364. (`item
  19365. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19366. ;; unconditionally, whereas `C-u' will toggle its presence.
  19367. ;; Without a universal argument, if the item has a checkbox,
  19368. ;; toggle it. Otherwise repair the list.
  19369. (let* ((box (org-element-property :checkbox context))
  19370. (struct (org-element-property :structure context))
  19371. (old-struct (copy-tree struct))
  19372. (parents (org-list-parents-alist struct))
  19373. (prevs (org-list-prevs-alist struct))
  19374. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19375. (org-list-set-checkbox
  19376. (org-element-property :begin context) struct
  19377. (cond ((equal arg '(16)) "[-]")
  19378. ((and (not box) (equal arg '(4))) "[ ]")
  19379. ((or (not box) (equal arg '(4))) nil)
  19380. ((eq box 'on) "[ ]")
  19381. (t "[X]")))
  19382. ;; Mimic `org-list-write-struct' but with grabbing a return
  19383. ;; value from `org-list-struct-fix-box'.
  19384. (org-list-struct-fix-ind struct parents 2)
  19385. (org-list-struct-fix-item-end struct)
  19386. (org-list-struct-fix-bul struct prevs)
  19387. (org-list-struct-fix-ind struct parents)
  19388. (let ((block-item
  19389. (org-list-struct-fix-box struct parents prevs orderedp)))
  19390. (if (and box (equal struct old-struct))
  19391. (if (equal arg '(16))
  19392. (message "Checkboxes already reset")
  19393. (user-error "Cannot toggle this checkbox: %s"
  19394. (if (eq box 'on)
  19395. "all subitems checked"
  19396. "unchecked subitems")))
  19397. (org-list-struct-apply-struct struct old-struct)
  19398. (org-update-checkbox-count-maybe))
  19399. (when block-item
  19400. (message "Checkboxes were removed due to empty box at line %d"
  19401. (org-current-line block-item))))))
  19402. (`keyword
  19403. (let ((org-inhibit-startup-visibility-stuff t)
  19404. (org-startup-align-all-tables nil))
  19405. (when (boundp 'org-table-coordinate-overlays)
  19406. (mapc #'delete-overlay org-table-coordinate-overlays)
  19407. (setq org-table-coordinate-overlays nil))
  19408. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19409. (message "Local setup has been refreshed"))
  19410. (`plain-list
  19411. ;; At a plain list, with a double C-u argument, set
  19412. ;; checkboxes of each item to "[-]", whereas a single one
  19413. ;; will toggle their presence according to the state of the
  19414. ;; first item in the list. Without an argument, repair the
  19415. ;; list.
  19416. (let* ((begin (org-element-property :contents-begin context))
  19417. (beginm (move-marker (make-marker) begin))
  19418. (struct (org-element-property :structure context))
  19419. (old-struct (copy-tree struct))
  19420. (first-box (save-excursion
  19421. (goto-char begin)
  19422. (looking-at org-list-full-item-re)
  19423. (match-string-no-properties 3)))
  19424. (new-box (cond ((equal arg '(16)) "[-]")
  19425. ((equal arg '(4)) (unless first-box "[ ]"))
  19426. ((equal first-box "[X]") "[ ]")
  19427. (t "[X]"))))
  19428. (cond
  19429. (arg
  19430. (dolist (pos
  19431. (org-list-get-all-items
  19432. begin struct (org-list-prevs-alist struct)))
  19433. (org-list-set-checkbox pos struct new-box)))
  19434. ((and first-box (eq (point) begin))
  19435. ;; For convenience, when point is at bol on the first
  19436. ;; item of the list and no argument is provided, simply
  19437. ;; toggle checkbox of that item, if any.
  19438. (org-list-set-checkbox begin struct new-box)))
  19439. (org-list-write-struct
  19440. struct (org-list-parents-alist struct) old-struct)
  19441. (org-update-checkbox-count-maybe)
  19442. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19443. ((or `property-drawer `node-property)
  19444. (call-interactively #'org-property-action))
  19445. (`radio-target
  19446. (call-interactively #'org-update-radio-target-regexp))
  19447. (`statistics-cookie
  19448. (call-interactively #'org-update-statistics-cookies))
  19449. ((or `table `table-cell `table-row)
  19450. ;; At a table, recalculate every field and align it. Also
  19451. ;; send the table if necessary. If the table has
  19452. ;; a `table.el' type, just give up. At a table row or cell,
  19453. ;; maybe recalculate line but always align table.
  19454. (if (eq (org-element-property :type context) 'table.el)
  19455. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19456. Use `\\[org-edit-special]' to edit table.el tables"))
  19457. (let ((org-enable-table-editor t))
  19458. (if (or (eq type 'table)
  19459. ;; Check if point is at a TBLFM line.
  19460. (and (eq type 'table-row)
  19461. (= (point) (org-element-property :end context))))
  19462. (save-excursion
  19463. (if (org-at-TBLFM-p)
  19464. (progn (require 'org-table)
  19465. (org-table-calc-current-TBLFM))
  19466. (goto-char (org-element-property :contents-begin context))
  19467. (org-call-with-arg 'org-table-recalculate (or arg t))
  19468. (orgtbl-send-table 'maybe)))
  19469. (org-table-maybe-eval-formula)
  19470. (cond (arg (call-interactively #'org-table-recalculate))
  19471. ((org-table-maybe-recalculate-line))
  19472. (t (org-table-align)))))))
  19473. (`timestamp (org-timestamp-change 0 'day))
  19474. ((and `nil (guard (org-at-heading-p)))
  19475. ;; When point is on an unsupported object type, we can miss
  19476. ;; the fact that it also is at a heading. Handle it here.
  19477. (call-interactively #'org-set-tags))
  19478. ((guard
  19479. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19480. (_
  19481. (user-error
  19482. (substitute-command-keys
  19483. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19484. (defun org-mode-restart ()
  19485. (interactive)
  19486. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19487. (funcall major-mode)
  19488. (hack-local-variables)
  19489. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19490. (org-indent-mode -1)))
  19491. (message "%s restarted" major-mode))
  19492. (defun org-kill-note-or-show-branches ()
  19493. "Abort storing current note, or call `outline-show-branches'."
  19494. (interactive)
  19495. (if (not org-finish-function)
  19496. (progn
  19497. (outline-hide-subtree)
  19498. (call-interactively 'outline-show-branches))
  19499. (let ((org-note-abort t))
  19500. (funcall org-finish-function))))
  19501. (defun org-delete-indentation (&optional arg)
  19502. "Join current line to previous and fix whitespace at join.
  19503. If previous line is a headline add to headline title. Otherwise
  19504. the function calls `delete-indentation'.
  19505. With a non-nil optional argument, join it to the following one."
  19506. (interactive "*P")
  19507. (if (save-excursion
  19508. (beginning-of-line (if arg 1 0))
  19509. (let ((case-fold-search nil))
  19510. (looking-at org-complex-heading-regexp)))
  19511. ;; At headline.
  19512. (let ((tags-column (when (match-beginning 5)
  19513. (save-excursion (goto-char (match-beginning 5))
  19514. (current-column))))
  19515. (string (concat " " (progn (when arg (forward-line 1))
  19516. (org-trim (delete-and-extract-region
  19517. (line-beginning-position)
  19518. (line-end-position)))))))
  19519. (unless (bobp) (delete-region (point) (1- (point))))
  19520. (goto-char (or (match-end 4)
  19521. (match-beginning 5)
  19522. (match-end 0)))
  19523. (skip-chars-backward " \t")
  19524. (save-excursion (insert string))
  19525. ;; Adjust alignment of tags.
  19526. (cond
  19527. ((not tags-column)) ;no tags
  19528. (org-auto-align-tags (org-set-tags nil t))
  19529. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19530. (delete-indentation arg)))
  19531. (defun org-open-line (n)
  19532. "Insert a new row in tables, call `open-line' elsewhere.
  19533. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19534. As a special case, when a document starts with a table, allow to
  19535. call `open-line' on the very first character."
  19536. (interactive "*p")
  19537. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19538. (org-table-insert-row)
  19539. (open-line n)))
  19540. (defun org-return (&optional indent)
  19541. "Goto next table row or insert a newline.
  19542. Calls `org-table-next-row' or `newline', depending on context.
  19543. When optional INDENT argument is non-nil, call
  19544. `newline-and-indent' instead of `newline'.
  19545. When `org-return-follows-link' is non-nil and point is on
  19546. a timestamp or a link, call `org-open-at-point'. However, it
  19547. will not happen if point is in a table or on a \"dead\"
  19548. object (e.g., within a comment). In these case, you need to use
  19549. `org-open-at-point' directly."
  19550. (interactive)
  19551. (let ((context (if org-return-follows-link (org-element-context)
  19552. (org-element-at-point))))
  19553. (cond
  19554. ;; In a table, call `org-table-next-row'.
  19555. ((or (and (eq (org-element-type context) 'table)
  19556. (>= (point) (org-element-property :contents-begin context))
  19557. (< (point) (org-element-property :contents-end context)))
  19558. (org-element-lineage context '(table-row table-cell) t))
  19559. (org-table-justify-field-maybe)
  19560. (call-interactively #'org-table-next-row))
  19561. ;; On a link or a timestamp, call `org-open-at-point' if
  19562. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19563. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19564. ((and org-return-follows-link
  19565. (or (org-in-regexp org-ts-regexp-both nil t)
  19566. (org-in-regexp org-tsr-regexp-both nil t)
  19567. (org-in-regexp org-any-link-re nil t)))
  19568. (call-interactively #'org-open-at-point))
  19569. ;; Insert newline in heading, but preserve tags.
  19570. ((and (not (bolp))
  19571. (save-excursion (beginning-of-line)
  19572. (let ((case-fold-search nil))
  19573. (looking-at org-complex-heading-regexp))))
  19574. ;; At headline. Split line. However, if point is on keyword,
  19575. ;; priority cookie or tags, do not break any of them: add
  19576. ;; a newline after the headline instead.
  19577. (let ((tags-column (and (match-beginning 5)
  19578. (save-excursion (goto-char (match-beginning 5))
  19579. (current-column))))
  19580. (string
  19581. (when (and (match-end 4) (org-point-in-group (point) 4))
  19582. (delete-and-extract-region (point) (match-end 4)))))
  19583. ;; Adjust tag alignment.
  19584. (cond
  19585. ((not (and tags-column string)))
  19586. (org-auto-align-tags (org-set-tags nil t))
  19587. (t (org--align-tags-here tags-column))) ;preserve tags column
  19588. (end-of-line)
  19589. (org-show-entry)
  19590. (if indent (newline-and-indent) (newline))
  19591. (when string (save-excursion (insert (org-trim string))))))
  19592. ;; In a list, make sure indenting keeps trailing text within.
  19593. ((and indent
  19594. (not (eolp))
  19595. (org-element-lineage context '(item)))
  19596. (let ((trailing-data
  19597. (delete-and-extract-region (point) (line-end-position))))
  19598. (newline-and-indent)
  19599. (save-excursion (insert trailing-data))))
  19600. (t (if indent (newline-and-indent) (newline))))))
  19601. (defun org-return-indent ()
  19602. "Goto next table row or insert a newline and indent.
  19603. Calls `org-table-next-row' or `newline-and-indent', depending on
  19604. context. See the individual commands for more information."
  19605. (interactive)
  19606. (org-return t))
  19607. (defun org-ctrl-c-star ()
  19608. "Compute table, or change heading status of lines.
  19609. Calls `org-table-recalculate' or `org-toggle-heading',
  19610. depending on context."
  19611. (interactive)
  19612. (cond
  19613. ((org-at-table-p)
  19614. (call-interactively 'org-table-recalculate))
  19615. (t
  19616. ;; Convert all lines in region to list items
  19617. (call-interactively 'org-toggle-heading))))
  19618. (defun org-ctrl-c-minus ()
  19619. "Insert separator line in table or modify bullet status of line.
  19620. Also turns a plain line or a region of lines into list items.
  19621. Calls `org-table-insert-hline', `org-toggle-item', or
  19622. `org-cycle-list-bullet', depending on context."
  19623. (interactive)
  19624. (cond
  19625. ((org-at-table-p)
  19626. (call-interactively 'org-table-insert-hline))
  19627. ((org-region-active-p)
  19628. (call-interactively 'org-toggle-item))
  19629. ((org-in-item-p)
  19630. (call-interactively 'org-cycle-list-bullet))
  19631. (t
  19632. (call-interactively 'org-toggle-item))))
  19633. (defun org-toggle-heading (&optional nstars)
  19634. "Convert headings to normal text, or items or text to headings.
  19635. If there is no active region, only convert the current line.
  19636. With a `\\[universal-argument]' prefix, convert the whole list at
  19637. point into heading.
  19638. In a region:
  19639. - If the first non blank line is a headline, remove the stars
  19640. from all headlines in the region.
  19641. - If it is a normal line, turn each and every normal line (i.e.,
  19642. not an heading or an item) in the region into headings. If you
  19643. want to convert only the first line of this region, use one
  19644. universal prefix argument.
  19645. - If it is a plain list item, turn all plain list items into headings.
  19646. When converting a line into a heading, the number of stars is chosen
  19647. such that the lines become children of the current entry. However,
  19648. when a numeric prefix argument is given, its value determines the
  19649. number of stars to add."
  19650. (interactive "P")
  19651. (let ((skip-blanks
  19652. (function
  19653. ;; Return beginning of first non-blank line, starting from
  19654. ;; line at POS.
  19655. (lambda (pos)
  19656. (save-excursion
  19657. (goto-char pos)
  19658. (while (org-at-comment-p) (forward-line))
  19659. (skip-chars-forward " \r\t\n")
  19660. (point-at-bol)))))
  19661. beg end toggled)
  19662. ;; Determine boundaries of changes. If a universal prefix has
  19663. ;; been given, put the list in a region. If region ends at a bol,
  19664. ;; do not consider the last line to be in the region.
  19665. (when (and current-prefix-arg (org-at-item-p))
  19666. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19667. (org-mark-element))
  19668. (if (org-region-active-p)
  19669. (setq beg (funcall skip-blanks (region-beginning))
  19670. end (copy-marker (save-excursion
  19671. (goto-char (region-end))
  19672. (if (bolp) (point) (point-at-eol)))))
  19673. (setq beg (funcall skip-blanks (point-at-bol))
  19674. end (copy-marker (point-at-eol))))
  19675. ;; Ensure inline tasks don't count as headings.
  19676. (org-with-limited-levels
  19677. (save-excursion
  19678. (goto-char beg)
  19679. (cond
  19680. ;; Case 1. Started at an heading: de-star headings.
  19681. ((org-at-heading-p)
  19682. (while (< (point) end)
  19683. (when (org-at-heading-p t)
  19684. (looking-at org-outline-regexp) (replace-match "")
  19685. (setq toggled t))
  19686. (forward-line)))
  19687. ;; Case 2. Started at an item: change items into headlines.
  19688. ;; One star will be added by `org-list-to-subtree'.
  19689. ((org-at-item-p)
  19690. (while (< (point) end)
  19691. (when (org-at-item-p)
  19692. ;; Pay attention to cases when region ends before list.
  19693. (let* ((struct (org-list-struct))
  19694. (list-end
  19695. (min (org-list-get-bottom-point struct) (1+ end))))
  19696. (save-restriction
  19697. (narrow-to-region (point) list-end)
  19698. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19699. (setq toggled t))
  19700. (forward-line)))
  19701. ;; Case 3. Started at normal text: make every line an heading,
  19702. ;; skipping headlines and items.
  19703. (t (let* ((stars
  19704. (make-string
  19705. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19706. (add-stars
  19707. (cond (nstars "") ; stars from prefix only
  19708. ((equal stars "") "*") ; before first heading
  19709. (org-odd-levels-only "**") ; inside heading, odd
  19710. (t "*"))) ; inside heading, oddeven
  19711. (rpl (concat stars add-stars " "))
  19712. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19713. (while (< (point) (if (equal nstars '(4)) lend end))
  19714. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19715. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19716. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19717. (forward-line)))))))
  19718. (unless toggled (message "Cannot toggle heading from here"))))
  19719. (defun org-meta-return (&optional _arg)
  19720. "Insert a new heading or wrap a region in a table.
  19721. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19722. on context. See the individual commands for more information."
  19723. (interactive)
  19724. (org-check-before-invisible-edit 'insert)
  19725. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19726. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19727. #'org-insert-heading))))
  19728. ;;; Menu entries
  19729. (defsubst org-in-subtree-not-table-p ()
  19730. "Are we in a subtree and not in a table?"
  19731. (and (not (org-before-first-heading-p))
  19732. (not (org-at-table-p))))
  19733. ;; Define the Org mode menus
  19734. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19735. '("Tbl"
  19736. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19737. ["Next Field" org-cycle (org-at-table-p)]
  19738. ["Previous Field" org-shifttab (org-at-table-p)]
  19739. ["Next Row" org-return (org-at-table-p)]
  19740. "--"
  19741. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19742. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19743. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19744. "--"
  19745. ("Column"
  19746. ["Move Column Left" org-metaleft (org-at-table-p)]
  19747. ["Move Column Right" org-metaright (org-at-table-p)]
  19748. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19749. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19750. ("Row"
  19751. ["Move Row Up" org-metaup (org-at-table-p)]
  19752. ["Move Row Down" org-metadown (org-at-table-p)]
  19753. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19754. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19755. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19756. "--"
  19757. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19758. ("Rectangle"
  19759. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19760. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19761. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19762. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19763. "--"
  19764. ("Calculate"
  19765. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19766. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19767. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19768. "--"
  19769. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19770. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19771. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19772. "--"
  19773. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19774. "--"
  19775. ["Sum Column/Rectangle" org-table-sum
  19776. (or (org-at-table-p) (org-region-active-p))]
  19777. ["Which Column?" org-table-current-column (org-at-table-p)])
  19778. ["Debug Formulas"
  19779. org-table-toggle-formula-debugger
  19780. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19781. ["Show Col/Row Numbers"
  19782. org-table-toggle-coordinate-overlays
  19783. :style toggle
  19784. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19785. "--"
  19786. ["Create" org-table-create (and (not (org-at-table-p))
  19787. org-enable-table-editor)]
  19788. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19789. ["Import from File" org-table-import (not (org-at-table-p))]
  19790. ["Export to File" org-table-export (org-at-table-p)]
  19791. "--"
  19792. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19793. "--"
  19794. ("Plot"
  19795. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19796. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19797. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19798. '("Org"
  19799. ("Show/Hide"
  19800. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19801. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19802. ["Sparse Tree..." org-sparse-tree t]
  19803. ["Reveal Context" org-reveal t]
  19804. ["Show All" outline-show-all t]
  19805. "--"
  19806. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19807. "--"
  19808. ["New Heading" org-insert-heading t]
  19809. ("Navigate Headings"
  19810. ["Up" outline-up-heading t]
  19811. ["Next" outline-next-visible-heading t]
  19812. ["Previous" outline-previous-visible-heading t]
  19813. ["Next Same Level" outline-forward-same-level t]
  19814. ["Previous Same Level" outline-backward-same-level t]
  19815. "--"
  19816. ["Jump" org-goto t])
  19817. ("Edit Structure"
  19818. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19819. "--"
  19820. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19821. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19822. "--"
  19823. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19824. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19825. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19826. "--"
  19827. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19828. "--"
  19829. ["Copy visible text" org-copy-visible t]
  19830. "--"
  19831. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19832. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19833. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19834. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19835. "--"
  19836. ["Sort Region/Children" org-sort t]
  19837. "--"
  19838. ["Convert to odd levels" org-convert-to-odd-levels t]
  19839. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19840. ("Editing"
  19841. ["Emphasis..." org-emphasize t]
  19842. ["Edit Source Example" org-edit-special t]
  19843. "--"
  19844. ["Footnote new/jump" org-footnote-action t]
  19845. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19846. ("Archive"
  19847. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19848. "--"
  19849. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19850. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19851. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19852. )
  19853. "--"
  19854. ("Hyperlinks"
  19855. ["Store Link (Global)" org-store-link t]
  19856. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19857. ["Insert Link" org-insert-link t]
  19858. ["Follow Link" org-open-at-point t]
  19859. "--"
  19860. ["Next link" org-next-link t]
  19861. ["Previous link" org-previous-link t]
  19862. "--"
  19863. ["Descriptive Links"
  19864. org-toggle-link-display
  19865. :style radio
  19866. :selected org-descriptive-links
  19867. ]
  19868. ["Literal Links"
  19869. org-toggle-link-display
  19870. :style radio
  19871. :selected (not org-descriptive-links)])
  19872. "--"
  19873. ("TODO Lists"
  19874. ["TODO/DONE/-" org-todo t]
  19875. ("Select keyword"
  19876. ["Next keyword" org-shiftright (org-at-heading-p)]
  19877. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19878. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19879. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19880. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19881. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19882. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19883. "--"
  19884. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19885. :selected org-enforce-todo-dependencies :style toggle :active t]
  19886. "Settings for tree at point"
  19887. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19888. :selected (org-entry-get nil "ORDERED")
  19889. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19890. ["Do Children parallel" org-toggle-ordered-property :style radio
  19891. :selected (not (org-entry-get nil "ORDERED"))
  19892. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19893. "--"
  19894. ["Set Priority" org-priority t]
  19895. ["Priority Up" org-shiftup t]
  19896. ["Priority Down" org-shiftdown t]
  19897. "--"
  19898. ["Get news from all feeds" org-feed-update-all t]
  19899. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19900. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19901. ("TAGS and Properties"
  19902. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19903. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19904. "--"
  19905. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19906. ["Column view of properties" org-columns t]
  19907. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19908. ("Dates and Scheduling"
  19909. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19910. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19911. ("Change Date"
  19912. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19913. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19914. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19915. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19916. ["Compute Time Range" org-evaluate-time-range t]
  19917. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19918. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19919. "--"
  19920. ["Custom time format" org-toggle-time-stamp-overlays
  19921. :style radio :selected org-display-custom-times]
  19922. "--"
  19923. ["Goto Calendar" org-goto-calendar t]
  19924. ["Date from Calendar" org-date-from-calendar t]
  19925. "--"
  19926. ["Start/Restart Timer" org-timer-start t]
  19927. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19928. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19929. ["Insert Timer String" org-timer t]
  19930. ["Insert Timer Item" org-timer-item t])
  19931. ("Logging work"
  19932. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19933. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19934. ["Clock out" org-clock-out t]
  19935. ["Clock cancel" org-clock-cancel t]
  19936. "--"
  19937. ["Mark as default task" org-clock-mark-default-task t]
  19938. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19939. ["Goto running clock" org-clock-goto t]
  19940. "--"
  19941. ["Display times" org-clock-display t]
  19942. ["Create clock table" org-clock-report t]
  19943. "--"
  19944. ["Record DONE time"
  19945. (progn (setq org-log-done (not org-log-done))
  19946. (message "Switching to %s will %s record a timestamp"
  19947. (car org-done-keywords)
  19948. (if org-log-done "automatically" "not")))
  19949. :style toggle :selected org-log-done])
  19950. "--"
  19951. ["Agenda Command..." org-agenda t]
  19952. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19953. ("File List for Agenda")
  19954. ("Special views current file"
  19955. ["TODO Tree" org-show-todo-tree t]
  19956. ["Check Deadlines" org-check-deadlines t]
  19957. ["Timeline" org-timeline t]
  19958. ["Tags/Property tree" org-match-sparse-tree t])
  19959. "--"
  19960. ["Export/Publish..." org-export-dispatch t]
  19961. ("LaTeX"
  19962. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19963. :selected org-cdlatex-mode]
  19964. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19965. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19966. ["Modify math symbol" org-cdlatex-math-modify
  19967. (org-inside-LaTeX-fragment-p)]
  19968. ["Insert citation" org-reftex-citation t])
  19969. "--"
  19970. ("MobileOrg"
  19971. ["Push Files and Views" org-mobile-push t]
  19972. ["Get Captured and Flagged" org-mobile-pull t]
  19973. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19974. "--"
  19975. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19976. "--"
  19977. ("Documentation"
  19978. ["Show Version" org-version t]
  19979. ["Info Documentation" org-info t])
  19980. ("Customize"
  19981. ["Browse Org Group" org-customize t]
  19982. "--"
  19983. ["Expand This Menu" org-create-customize-menu
  19984. (fboundp 'customize-menu-create)])
  19985. ["Send bug report" org-submit-bug-report t]
  19986. "--"
  19987. ("Refresh/Reload"
  19988. ["Refresh setup current buffer" org-mode-restart t]
  19989. ["Reload Org (after update)" org-reload t]
  19990. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19991. ))
  19992. (defun org-info (&optional node)
  19993. "Read documentation for Org in the info system.
  19994. With optional NODE, go directly to that node."
  19995. (interactive)
  19996. (info (format "(org)%s" (or node ""))))
  19997. ;;;###autoload
  19998. (defun org-submit-bug-report ()
  19999. "Submit a bug report on Org via mail.
  20000. Don't hesitate to report any problems or inaccurate documentation.
  20001. If you don't have setup sending mail from (X)Emacs, please copy the
  20002. output buffer into your mail program, as it gives us important
  20003. information about your Org version and configuration."
  20004. (interactive)
  20005. (require 'reporter)
  20006. (defvar reporter-prompt-for-summary-p)
  20007. (org-load-modules-maybe)
  20008. (org-require-autoloaded-modules)
  20009. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20010. (reporter-submit-bug-report
  20011. "emacs-orgmode@gnu.org"
  20012. (org-version nil 'full)
  20013. (let (list)
  20014. (save-window-excursion
  20015. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20016. (delete-other-windows)
  20017. (erase-buffer)
  20018. (insert "You are about to submit a bug report to the Org mailing list.
  20019. We would like to add your full Org and Outline configuration to the
  20020. bug report. This greatly simplifies the work of the maintainer and
  20021. other experts on the mailing list.
  20022. HOWEVER, some variables you have customized may contain private
  20023. information. The names of customers, colleagues, or friends, might
  20024. appear in the form of file names, tags, todo states, or search strings.
  20025. If you answer yes to the prompt, you might want to check and remove
  20026. such private information before sending the email.")
  20027. (add-text-properties (point-min) (point-max) '(face org-warning))
  20028. (when (yes-or-no-p "Include your Org configuration ")
  20029. (mapatoms
  20030. (lambda (v)
  20031. (and (boundp v)
  20032. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20033. (or (and (symbol-value v)
  20034. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20035. (and
  20036. (get v 'custom-type) (get v 'standard-value)
  20037. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20038. (push v list)))))
  20039. (kill-buffer (get-buffer "*Warn about privacy*"))
  20040. list))
  20041. nil nil
  20042. "Remember to cover the basics, that is, what you expected to happen and
  20043. what in fact did happen. You don't know how to make a good report? See
  20044. http://orgmode.org/manual/Feedback.html#Feedback
  20045. Your bug report will be posted to the Org mailing list.
  20046. ------------------------------------------------------------------------")
  20047. (save-excursion
  20048. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20049. (replace-match "\\1Bug: \\3 [\\2]")))))
  20050. (defun org-install-agenda-files-menu ()
  20051. (let ((bl (buffer-list)))
  20052. (save-excursion
  20053. (while bl
  20054. (set-buffer (pop bl))
  20055. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20056. (when (derived-mode-p 'org-mode)
  20057. (easy-menu-change
  20058. '("Org") "File List for Agenda"
  20059. (append
  20060. (list
  20061. ["Edit File List" (org-edit-agenda-file-list) t]
  20062. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20063. ["Remove Current File from List" org-remove-file t]
  20064. ["Cycle through agenda files" org-cycle-agenda-files t]
  20065. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20066. "--")
  20067. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20068. ;;;; Documentation
  20069. (defun org-require-autoloaded-modules ()
  20070. (interactive)
  20071. (mapc #'require
  20072. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20073. org-table org-timer)))
  20074. ;;;###autoload
  20075. (defun org-reload (&optional uncompiled)
  20076. "Reload all org lisp files.
  20077. With prefix arg UNCOMPILED, load the uncompiled versions."
  20078. (interactive "P")
  20079. (require 'loadhist)
  20080. (let* ((org-dir (org-find-library-dir "org"))
  20081. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20082. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20083. (remove-re (format "\\`%s\\'"
  20084. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20085. (feats (delete-dups
  20086. (mapcar 'file-name-sans-extension
  20087. (mapcar 'file-name-nondirectory
  20088. (delq nil
  20089. (mapcar 'feature-file
  20090. features))))))
  20091. (lfeat (append
  20092. (sort
  20093. (setq feats
  20094. (delq nil (mapcar
  20095. (lambda (f)
  20096. (if (and (string-match feature-re f)
  20097. (not (string-match remove-re f)))
  20098. f nil))
  20099. feats)))
  20100. 'string-lessp)
  20101. (list "org-version" "org")))
  20102. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20103. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20104. load-uncore load-misses)
  20105. (setq load-misses
  20106. (delq 't
  20107. (mapcar (lambda (f)
  20108. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20109. (and (string= org-dir contrib-dir)
  20110. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20111. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20112. (add-to-list 'load-uncore f 'append)
  20113. 't)
  20114. f))
  20115. lfeat)))
  20116. (when load-uncore
  20117. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20118. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20119. (if load-misses
  20120. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20121. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20122. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20123. ;;;###autoload
  20124. (defun org-customize ()
  20125. "Call the customize function with org as argument."
  20126. (interactive)
  20127. (org-load-modules-maybe)
  20128. (org-require-autoloaded-modules)
  20129. (customize-browse 'org))
  20130. (defun org-create-customize-menu ()
  20131. "Create a full customization menu for Org mode, insert it into the menu."
  20132. (interactive)
  20133. (org-load-modules-maybe)
  20134. (org-require-autoloaded-modules)
  20135. (if (fboundp 'customize-menu-create)
  20136. (progn
  20137. (easy-menu-change
  20138. '("Org") "Customize"
  20139. `(["Browse Org group" org-customize t]
  20140. "--"
  20141. ,(customize-menu-create 'org)
  20142. ["Set" Custom-set t]
  20143. ["Save" Custom-save t]
  20144. ["Reset to Current" Custom-reset-current t]
  20145. ["Reset to Saved" Custom-reset-saved t]
  20146. ["Reset to Standard Settings" Custom-reset-standard t]))
  20147. (message "\"Org\"-menu now contains full customization menu"))
  20148. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20149. ;;;; Miscellaneous stuff
  20150. ;;; Generally useful functions
  20151. (defun org-get-at-eol (property n)
  20152. "Get text property PROPERTY at the end of line less N characters."
  20153. (get-text-property (- (point-at-eol) n) property))
  20154. (defun org-find-text-property-in-string (prop s)
  20155. "Return the first non-nil value of property PROP in string S."
  20156. (or (get-text-property 0 prop s)
  20157. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20158. prop s)))
  20159. (defun org-display-warning (message)
  20160. "Display the given MESSAGE as a warning."
  20161. (display-warning 'org message :warning))
  20162. (defun org-eval (form)
  20163. "Eval FORM and return result."
  20164. (condition-case error
  20165. (eval form)
  20166. (error (format "%%![Error: %s]" error))))
  20167. (defun org-in-clocktable-p ()
  20168. "Check if the cursor is in a clocktable."
  20169. (let ((pos (point)) start)
  20170. (save-excursion
  20171. (end-of-line 1)
  20172. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20173. (setq start (match-beginning 0))
  20174. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20175. (>= (match-end 0) pos)
  20176. start))))
  20177. (defun org-in-verbatim-emphasis ()
  20178. (save-match-data
  20179. (and (org-in-regexp org-emph-re 2)
  20180. (>= (point) (match-beginning 3))
  20181. (<= (point) (match-end 4))
  20182. (member (match-string 3) '("=" "~")))))
  20183. (defun org-overlay-display (ovl text &optional face evap)
  20184. "Make overlay OVL display TEXT with face FACE."
  20185. (overlay-put ovl 'display text)
  20186. (if face (overlay-put ovl 'face face))
  20187. (if evap (overlay-put ovl 'evaporate t)))
  20188. (defun org-overlay-before-string (ovl text &optional face evap)
  20189. "Make overlay OVL display TEXT with face FACE."
  20190. (if face (org-add-props text nil 'face face))
  20191. (overlay-put ovl 'before-string text)
  20192. (if evap (overlay-put ovl 'evaporate t)))
  20193. (defun org-find-overlays (prop &optional pos delete)
  20194. "Find all overlays specifying PROP at POS or point.
  20195. If DELETE is non-nil, delete all those overlays."
  20196. (let (found)
  20197. (dolist (ov (overlays-at (or pos (point))) found)
  20198. (cond ((not (overlay-get ov prop)))
  20199. (delete (delete-overlay ov))
  20200. (t (push ov found))))))
  20201. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20202. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20203. (if (and marker (marker-buffer marker)
  20204. (buffer-live-p (marker-buffer marker)))
  20205. (progn
  20206. (pop-to-buffer-same-window (marker-buffer marker))
  20207. (when (or (> marker (point-max)) (< marker (point-min)))
  20208. (widen))
  20209. (goto-char marker)
  20210. (org-show-context 'org-goto))
  20211. (if bookmark
  20212. (bookmark-jump bookmark)
  20213. (error "Cannot find location"))))
  20214. (defun org-quote-csv-field (s)
  20215. "Quote field for inclusion in CSV material."
  20216. (if (string-match "[\",]" s)
  20217. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20218. s))
  20219. (defun org-force-self-insert (N)
  20220. "Needed to enforce self-insert under remapping."
  20221. (interactive "p")
  20222. (self-insert-command N))
  20223. (defun org-string-width (s)
  20224. "Compute width of string, ignoring invisible characters.
  20225. This ignores character with invisibility property `org-link', and also
  20226. characters with property `org-cwidth', because these will become invisible
  20227. upon the next fontification round."
  20228. (let (b l)
  20229. (when (or (eq t buffer-invisibility-spec)
  20230. (assq 'org-link buffer-invisibility-spec))
  20231. (while (setq b (text-property-any 0 (length s)
  20232. 'invisible 'org-link s))
  20233. (setq s (concat (substring s 0 b)
  20234. (substring s (or (next-single-property-change
  20235. b 'invisible s)
  20236. (length s)))))))
  20237. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20238. (setq s (concat (substring s 0 b)
  20239. (substring s (or (next-single-property-change
  20240. b 'org-cwidth s)
  20241. (length s))))))
  20242. (setq l (string-width s) b -1)
  20243. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20244. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20245. l))
  20246. (defun org-shorten-string (s maxlength)
  20247. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20248. If the string is shorter or has length MAXLENGTH, just return the
  20249. original string. If it is longer, the functions finds a space in the
  20250. string, breaks this string off at that locations and adds three dots
  20251. as ellipsis. Including the ellipsis, the string will not be longer
  20252. than MAXLENGTH. If finding a good breaking point in the string does
  20253. not work, the string is just chopped off in the middle of a word
  20254. if necessary."
  20255. (if (<= (length s) maxlength)
  20256. s
  20257. (let* ((n (max (- maxlength 4) 1))
  20258. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20259. (if (string-match re s)
  20260. (concat (match-string 1 s) "...")
  20261. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20262. (defun org-get-indentation (&optional line)
  20263. "Get the indentation of the current line, interpreting tabs.
  20264. When LINE is given, assume it represents a line and compute its indentation."
  20265. (if line
  20266. (when (string-match "^ *" (org-remove-tabs line))
  20267. (match-end 0))
  20268. (save-excursion
  20269. (beginning-of-line 1)
  20270. (skip-chars-forward " \t")
  20271. (current-column))))
  20272. (defun org-get-string-indentation (s)
  20273. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20274. (let ((n -1) (i 0) (w tab-width) c)
  20275. (catch 'exit
  20276. (while (< (setq n (1+ n)) (length s))
  20277. (setq c (aref s n))
  20278. (cond ((= c ?\ ) (setq i (1+ i)))
  20279. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20280. (t (throw 'exit t)))))
  20281. i))
  20282. (defun org-remove-tabs (s &optional width)
  20283. "Replace tabulators in S with spaces.
  20284. Assumes that s is a single line, starting in column 0."
  20285. (setq width (or width tab-width))
  20286. (while (string-match "\t" s)
  20287. (setq s (replace-match
  20288. (make-string
  20289. (- (* width (/ (+ (match-beginning 0) width) width))
  20290. (match-beginning 0)) ?\ )
  20291. t t s)))
  20292. s)
  20293. (defun org-fix-indentation (line ind)
  20294. "Fix indentation in LINE.
  20295. IND is a cons cell with target and minimum indentation.
  20296. If the current indentation in LINE is smaller than the minimum,
  20297. leave it alone. If it is larger than ind, set it to the target."
  20298. (let* ((l (org-remove-tabs line))
  20299. (i (org-get-indentation l))
  20300. (i1 (car ind)) (i2 (cdr ind)))
  20301. (when (>= i i2) (setq l (substring line i2)))
  20302. (if (> i1 0)
  20303. (concat (make-string i1 ?\ ) l)
  20304. l)))
  20305. (defun org-remove-indentation (code &optional n)
  20306. "Remove maximum common indentation in string CODE and return it.
  20307. N may optionally be the number of columns to remove. Return CODE
  20308. as-is if removal failed."
  20309. (with-temp-buffer
  20310. (insert code)
  20311. (if (org-do-remove-indentation n) (buffer-string) code)))
  20312. (defun org-do-remove-indentation (&optional n)
  20313. "Remove the maximum common indentation from the buffer.
  20314. When optional argument N is a positive integer, remove exactly
  20315. that much characters from indentation, if possible. Return nil
  20316. if it fails."
  20317. (catch :exit
  20318. (goto-char (point-min))
  20319. ;; Find maximum common indentation, if not specified.
  20320. (let ((n (or n
  20321. (let ((min-ind (point-max)))
  20322. (save-excursion
  20323. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20324. (let ((ind (1- (current-column))))
  20325. (if (zerop ind) (throw :exit nil)
  20326. (setq min-ind (min min-ind ind))))))
  20327. min-ind))))
  20328. (if (zerop n) (throw :exit nil)
  20329. ;; Remove exactly N indentation, but give up if not possible.
  20330. (while (not (eobp))
  20331. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20332. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20333. ((< ind n) (throw :exit nil))
  20334. (t (indent-line-to (- ind n))))
  20335. (forward-line)))
  20336. ;; Signal success.
  20337. t))))
  20338. (defun org-fill-template (template alist)
  20339. "Find each %key of ALIST in TEMPLATE and replace it."
  20340. (let ((case-fold-search nil))
  20341. (dolist (entry (sort (copy-sequence alist)
  20342. (lambda (a b) (< (length (car a)) (length (car b))))))
  20343. (setq template
  20344. (replace-regexp-in-string
  20345. (concat "%" (regexp-quote (car entry)))
  20346. (or (cdr entry) "") template t t)))
  20347. template))
  20348. (defun org-base-buffer (buffer)
  20349. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20350. (if (not buffer)
  20351. buffer
  20352. (or (buffer-base-buffer buffer)
  20353. buffer)))
  20354. (defun org-wrap (string &optional width lines)
  20355. "Wrap string to either a number of lines, or a width in characters.
  20356. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20357. that costs. If there is a word longer than WIDTH, the text is actually
  20358. wrapped to the length of that word.
  20359. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20360. many lines, whatever width that takes.
  20361. The return value is a list of lines, without newlines at the end."
  20362. (let* ((words (org-split-string string "[ \t\n]+"))
  20363. (maxword (apply 'max (mapcar 'org-string-width words)))
  20364. w ll)
  20365. (cond (width
  20366. (org-do-wrap words (max maxword width)))
  20367. (lines
  20368. (setq w maxword)
  20369. (setq ll (org-do-wrap words maxword))
  20370. (if (<= (length ll) lines)
  20371. ll
  20372. (setq ll words)
  20373. (while (> (length ll) lines)
  20374. (setq w (1+ w))
  20375. (setq ll (org-do-wrap words w)))
  20376. ll))
  20377. (t (error "Cannot wrap this")))))
  20378. (defun org-do-wrap (words width)
  20379. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20380. (let (lines line)
  20381. (while words
  20382. (setq line (pop words))
  20383. (while (and words (< (+ (length line) (length (car words))) width))
  20384. (setq line (concat line " " (pop words))))
  20385. (setq lines (push line lines)))
  20386. (nreverse lines)))
  20387. (defun org-split-string (string &optional separators)
  20388. "Splits STRING into substrings at SEPARATORS.
  20389. SEPARATORS is a regular expression.
  20390. No empty strings are returned if there are matches at the beginning
  20391. and end of string."
  20392. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20393. (let ((start 0) notfirst list)
  20394. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20395. (if (and notfirst
  20396. (= start (match-beginning 0))
  20397. (< start (length string)))
  20398. (1+ start) start))
  20399. (< (match-beginning 0) (length string)))
  20400. (setq notfirst t)
  20401. (or (eq (match-beginning 0) 0)
  20402. (and (eq (match-beginning 0) (match-end 0))
  20403. (eq (match-beginning 0) start))
  20404. (push (substring string start (match-beginning 0)) list))
  20405. (setq start (match-end 0)))
  20406. (or (eq start (length string))
  20407. (push (substring string start) list))
  20408. (nreverse list)))
  20409. (defun org-quote-vert (s)
  20410. "Replace \"|\" with \"\\vert\"."
  20411. (while (string-match "|" s)
  20412. (setq s (replace-match "\\vert" t t s)))
  20413. s)
  20414. (defun org-uuidgen-p (s)
  20415. "Is S an ID created by UUIDGEN?"
  20416. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20417. (defun org-in-src-block-p (&optional inside)
  20418. "Whether point is in a code source block.
  20419. When INSIDE is non-nil, don't consider we are within a src block
  20420. when point is at #+BEGIN_SRC or #+END_SRC."
  20421. (let ((case-fold-search t))
  20422. (or (and (eq (get-char-property (point) 'src-block) t))
  20423. (and (not inside)
  20424. (save-match-data
  20425. (save-excursion
  20426. (beginning-of-line)
  20427. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20428. (defun org-context ()
  20429. "Return a list of contexts of the current cursor position.
  20430. If several contexts apply, all are returned.
  20431. Each context entry is a list with a symbol naming the context, and
  20432. two positions indicating start and end of the context. Possible
  20433. contexts are:
  20434. :headline anywhere in a headline
  20435. :headline-stars on the leading stars in a headline
  20436. :todo-keyword on a TODO keyword (including DONE) in a headline
  20437. :tags on the TAGS in a headline
  20438. :priority on the priority cookie in a headline
  20439. :item on the first line of a plain list item
  20440. :item-bullet on the bullet/number of a plain list item
  20441. :checkbox on the checkbox in a plain list item
  20442. :table in an Org table
  20443. :table-special on a special filed in a table
  20444. :table-table in a table.el table
  20445. :clocktable in a clocktable
  20446. :src-block in a source block
  20447. :link on a hyperlink
  20448. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20449. :target on a <<target>>
  20450. :radio-target on a <<<radio-target>>>
  20451. :latex-fragment on a LaTeX fragment
  20452. :latex-preview on a LaTeX fragment with overlaid preview image
  20453. This function expects the position to be visible because it uses font-lock
  20454. faces as a help to recognize the following contexts: :table-special, :link,
  20455. and :keyword."
  20456. (let* ((f (get-text-property (point) 'face))
  20457. (faces (if (listp f) f (list f)))
  20458. (case-fold-search t)
  20459. (p (point)) clist o)
  20460. ;; First the large context
  20461. (cond
  20462. ((org-at-heading-p t)
  20463. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20464. (when (progn
  20465. (beginning-of-line 1)
  20466. (looking-at org-todo-line-tags-regexp))
  20467. (push (org-point-in-group p 1 :headline-stars) clist)
  20468. (push (org-point-in-group p 2 :todo-keyword) clist)
  20469. (push (org-point-in-group p 4 :tags) clist))
  20470. (goto-char p)
  20471. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20472. (when (looking-at "\\[#[A-Z0-9]\\]")
  20473. (push (org-point-in-group p 0 :priority) clist)))
  20474. ((org-at-item-p)
  20475. (push (org-point-in-group p 2 :item-bullet) clist)
  20476. (push (list :item (point-at-bol)
  20477. (save-excursion (org-end-of-item) (point)))
  20478. clist)
  20479. (and (org-at-item-checkbox-p)
  20480. (push (org-point-in-group p 0 :checkbox) clist)))
  20481. ((org-at-table-p)
  20482. (push (list :table (org-table-begin) (org-table-end)) clist)
  20483. (when (memq 'org-formula faces)
  20484. (push (list :table-special
  20485. (previous-single-property-change p 'face)
  20486. (next-single-property-change p 'face)) clist)))
  20487. ((org-at-table-p 'any)
  20488. (push (list :table-table) clist)))
  20489. (goto-char p)
  20490. (let ((case-fold-search t))
  20491. ;; New the "medium" contexts: clocktables, source blocks
  20492. (cond ((org-in-clocktable-p)
  20493. (push (list :clocktable
  20494. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20495. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20496. (match-beginning 1))
  20497. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20498. (match-end 0))) clist))
  20499. ((org-in-src-block-p)
  20500. (push (list :src-block
  20501. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20502. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20503. (match-beginning 1))
  20504. (and (search-forward "#+END_SRC" nil t)
  20505. (match-beginning 0))) clist))))
  20506. (goto-char p)
  20507. ;; Now the small context
  20508. (cond
  20509. ((org-at-timestamp-p)
  20510. (push (org-point-in-group p 0 :timestamp) clist))
  20511. ((memq 'org-link faces)
  20512. (push (list :link
  20513. (previous-single-property-change p 'face)
  20514. (next-single-property-change p 'face)) clist))
  20515. ((memq 'org-special-keyword faces)
  20516. (push (list :keyword
  20517. (previous-single-property-change p 'face)
  20518. (next-single-property-change p 'face)) clist))
  20519. ((org-at-target-p)
  20520. (push (org-point-in-group p 0 :target) clist)
  20521. (goto-char (1- (match-beginning 0)))
  20522. (when (looking-at org-radio-target-regexp)
  20523. (push (org-point-in-group p 0 :radio-target) clist))
  20524. (goto-char p))
  20525. ((setq o (cl-some
  20526. (lambda (o)
  20527. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20528. o))
  20529. (overlays-at (point))))
  20530. (push (list :latex-fragment
  20531. (overlay-start o) (overlay-end o)) clist)
  20532. (push (list :latex-preview
  20533. (overlay-start o) (overlay-end o)) clist))
  20534. ((org-inside-LaTeX-fragment-p)
  20535. ;; FIXME: positions wrong.
  20536. (push (list :latex-fragment (point) (point)) clist)))
  20537. (setq clist (nreverse (delq nil clist)))
  20538. clist))
  20539. (defun org-in-regexp (regexp &optional nlines visually)
  20540. "Check if point is inside a match of REGEXP.
  20541. Normally only the current line is checked, but you can include
  20542. NLINES extra lines around point into the search. If VISUALLY is
  20543. set, require that the cursor is not after the match but really
  20544. on, so that the block visually is on the match.
  20545. Return nil or a cons cell (BEG . END) where BEG and END are,
  20546. respectively, the positions at the beginning and the end of the
  20547. match."
  20548. (catch :exit
  20549. (let ((pos (point))
  20550. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20551. (save-excursion
  20552. (beginning-of-line (- 1 (or nlines 0)))
  20553. (while (and (re-search-forward regexp eol t)
  20554. (<= (match-beginning 0) pos))
  20555. (let ((end (match-end 0)))
  20556. (when (or (> end pos) (and (= end pos) (not visually)))
  20557. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20558. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20559. "Non-nil when point is between matches of START-RE and END-RE.
  20560. Also return a non-nil value when point is on one of the matches.
  20561. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20562. buffer positions. Default values are the positions of headlines
  20563. surrounding the point.
  20564. The functions returns a cons cell whose car (resp. cdr) is the
  20565. position before START-RE (resp. after END-RE)."
  20566. (save-match-data
  20567. (let ((pos (point))
  20568. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20569. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20570. beg end)
  20571. (save-excursion
  20572. ;; Point is on a block when on START-RE or if START-RE can be
  20573. ;; found before it...
  20574. (and (or (org-in-regexp start-re)
  20575. (re-search-backward start-re limit-up t))
  20576. (setq beg (match-beginning 0))
  20577. ;; ... and END-RE after it...
  20578. (goto-char (match-end 0))
  20579. (re-search-forward end-re limit-down t)
  20580. (> (setq end (match-end 0)) pos)
  20581. ;; ... without another START-RE in-between.
  20582. (goto-char (match-beginning 0))
  20583. (not (re-search-backward start-re (1+ beg) t))
  20584. ;; Return value.
  20585. (cons beg end))))))
  20586. (defun org-in-block-p (names)
  20587. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20588. NAMES is a list of strings containing names of blocks.
  20589. Return first block name matched, or nil. Beware that in case of
  20590. nested blocks, the returned name may not belong to the closest
  20591. block from point."
  20592. (save-match-data
  20593. (catch 'exit
  20594. (let ((case-fold-search t)
  20595. (lim-up (save-excursion (outline-previous-heading)))
  20596. (lim-down (save-excursion (outline-next-heading))))
  20597. (dolist (name names)
  20598. (let ((n (regexp-quote name)))
  20599. (when (org-between-regexps-p
  20600. (concat "^[ \t]*#\\+begin_" n)
  20601. (concat "^[ \t]*#\\+end_" n)
  20602. lim-up lim-down)
  20603. (throw 'exit n)))))
  20604. nil)))
  20605. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20606. "Call `multi-occur' with buffers for all agenda files."
  20607. (interactive "sOrg-files matching: ")
  20608. (let* ((files (org-agenda-files))
  20609. (tnames (mapcar #'file-truename files))
  20610. (extra org-agenda-text-search-extra-files))
  20611. (when (eq (car extra) 'agenda-archives)
  20612. (setq extra (cdr extra))
  20613. (setq files (org-add-archive-files files)))
  20614. (dolist (f extra)
  20615. (unless (member (file-truename f) tnames)
  20616. (unless (member f files) (setq files (append files (list f))))
  20617. (setq tnames (append tnames (list (file-truename f))))))
  20618. (multi-occur
  20619. (mapcar (lambda (x)
  20620. (with-current-buffer
  20621. ;; FIXME: Why not just (find-file-noselect x)?
  20622. ;; Is it to avoid the "revert buffer" prompt?
  20623. (or (get-file-buffer x) (find-file-noselect x))
  20624. (widen)
  20625. (current-buffer)))
  20626. files)
  20627. regexp)))
  20628. (add-hook 'occur-mode-find-occurrence-hook
  20629. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20630. (defun org-occur-link-in-agenda-files ()
  20631. "Create a link and search for it in the agendas.
  20632. The link is not stored in `org-stored-links', it is just created
  20633. for the search purpose."
  20634. (interactive)
  20635. (let ((link (condition-case nil
  20636. (org-store-link nil)
  20637. (error "Unable to create a link to here"))))
  20638. (org-occur-in-agenda-files (regexp-quote link))))
  20639. (defun org-reverse-string (string)
  20640. "Return the reverse of STRING."
  20641. (apply 'string (reverse (string-to-list string))))
  20642. ;; defsubst org-uniquify must be defined before first use
  20643. (defun org-uniquify-alist (alist)
  20644. "Merge elements of ALIST with the same key.
  20645. For example, in this alist:
  20646. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20647. => \\='((a 1 3) (b 2))
  20648. merge (a 1) and (a 3) into (a 1 3).
  20649. The function returns the new ALIST."
  20650. (let (rtn)
  20651. (dolist (e alist rtn)
  20652. (let (n)
  20653. (if (not (assoc (car e) rtn))
  20654. (push e rtn)
  20655. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20656. (setq rtn (assq-delete-all (car e) rtn))
  20657. (push n rtn))))))
  20658. (defun org-delete-all (elts list)
  20659. "Remove all elements in ELTS from LIST.
  20660. Comparison is done with `equal'. It is a destructive operation
  20661. that may remove elements by altering the list structure."
  20662. (while elts
  20663. (setq list (delete (pop elts) list)))
  20664. list)
  20665. (defun org-back-over-empty-lines ()
  20666. "Move backwards over whitespace, to the beginning of the first empty line.
  20667. Returns the number of empty lines passed."
  20668. (let ((pos (point)))
  20669. (if (cdr (assq 'heading org-blank-before-new-entry))
  20670. (skip-chars-backward " \t\n\r")
  20671. (unless (eobp)
  20672. (forward-line -1)))
  20673. (beginning-of-line 2)
  20674. (goto-char (min (point) pos))
  20675. (count-lines (point) pos)))
  20676. (defun org-skip-whitespace ()
  20677. (skip-chars-forward " \t\n\r"))
  20678. (defun org-point-in-group (point group &optional context)
  20679. "Check if POINT is in match-group GROUP.
  20680. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20681. match. If the match group does not exist or point is not inside it,
  20682. return nil."
  20683. (and (match-beginning group)
  20684. (>= point (match-beginning group))
  20685. (<= point (match-end group))
  20686. (if context
  20687. (list context (match-beginning group) (match-end group))
  20688. t)))
  20689. (defun org-switch-to-buffer-other-window (&rest args)
  20690. "Switch to buffer in a second window on the current frame.
  20691. In particular, do not allow pop-up frames.
  20692. Returns the newly created buffer."
  20693. (org-no-popups
  20694. (apply 'switch-to-buffer-other-window args)))
  20695. (defun org-combine-plists (&rest plists)
  20696. "Create a single property list from all plists in PLISTS.
  20697. The process starts by copying the first list, and then setting properties
  20698. from the other lists. Settings in the last list are the most significant
  20699. ones and overrule settings in the other lists."
  20700. (let ((rtn (copy-sequence (pop plists)))
  20701. p v ls)
  20702. (while plists
  20703. (setq ls (pop plists))
  20704. (while ls
  20705. (setq p (pop ls) v (pop ls))
  20706. (setq rtn (plist-put rtn p v))))
  20707. rtn))
  20708. (defun org-replace-escapes (string table)
  20709. "Replace %-escapes in STRING with values in TABLE.
  20710. TABLE is an association list with keys like \"%a\" and string values.
  20711. The sequences in STRING may contain normal field width and padding information,
  20712. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20713. so values can contain further %-escapes if they are define later in TABLE."
  20714. (let ((tbl (copy-alist table))
  20715. (case-fold-search nil)
  20716. (pchg 0)
  20717. re rpl)
  20718. (dolist (e tbl)
  20719. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20720. (when (and (cdr e) (string-match re (cdr e)))
  20721. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20722. (safe "SREF"))
  20723. (add-text-properties 0 3 (list 'sref sref) safe)
  20724. (setcdr e (replace-match safe t t (cdr e)))))
  20725. (while (string-match re string)
  20726. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20727. (cdr e)))
  20728. (setq string (replace-match rpl t t string))))
  20729. (while (setq pchg (next-property-change pchg string))
  20730. (let ((sref (get-text-property pchg 'sref string)))
  20731. (when (and sref (string-match "SREF" string pchg))
  20732. (setq string (replace-match sref t t string)))))
  20733. string))
  20734. (defun org-find-base-buffer-visiting (file)
  20735. "Like `find-buffer-visiting' but always return the base buffer and
  20736. not an indirect buffer."
  20737. (let ((buf (or (get-file-buffer file)
  20738. (find-buffer-visiting file))))
  20739. (if buf
  20740. (or (buffer-base-buffer buf) buf)
  20741. nil)))
  20742. ;;; TODO: Only called once, from ox-odt which should probably use
  20743. ;;; org-export-inline-image-p or something.
  20744. (defun org-file-image-p (file)
  20745. "Return non-nil if FILE is an image."
  20746. (save-match-data
  20747. (string-match (image-file-name-regexp) file)))
  20748. (defun org-get-cursor-date (&optional with-time)
  20749. "Return the date at cursor in as a time.
  20750. This works in the calendar and in the agenda, anywhere else it just
  20751. returns the current time.
  20752. If WITH-TIME is non-nil, returns the time of the event at point (in
  20753. the agenda) or the current time of the day."
  20754. (let (date day defd tp hod mod)
  20755. (when with-time
  20756. (setq tp (get-text-property (point) 'time))
  20757. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20758. (setq hod (string-to-number (match-string 1 tp))
  20759. mod (string-to-number (match-string 2 tp))))
  20760. (or tp (let ((now (decode-time)))
  20761. (setq hod (nth 2 now)
  20762. mod (nth 1 now)))))
  20763. (cond
  20764. ((eq major-mode 'calendar-mode)
  20765. (setq date (calendar-cursor-to-date)
  20766. defd (encode-time 0 (or mod 0) (or hod 0)
  20767. (nth 1 date) (nth 0 date) (nth 2 date))))
  20768. ((eq major-mode 'org-agenda-mode)
  20769. (setq day (get-text-property (point) 'day))
  20770. (when day
  20771. (setq date (calendar-gregorian-from-absolute day)
  20772. defd (encode-time 0 (or mod 0) (or hod 0)
  20773. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20774. (or defd (current-time))))
  20775. (defun org-mark-subtree (&optional up)
  20776. "Mark the current subtree.
  20777. This puts point at the start of the current subtree, and mark at
  20778. the end. If a numeric prefix UP is given, move up into the
  20779. hierarchy of headlines by UP levels before marking the subtree."
  20780. (interactive "P")
  20781. (org-with-limited-levels
  20782. (cond ((org-at-heading-p) (beginning-of-line))
  20783. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20784. (t (outline-previous-visible-heading 1))))
  20785. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20786. (if (called-interactively-p 'any)
  20787. (call-interactively 'org-mark-element)
  20788. (org-mark-element)))
  20789. (defun org-file-newer-than-p (file time)
  20790. "Non-nil if FILE is newer than TIME.
  20791. FILE is a filename, as a string, TIME is a list of integers, as
  20792. returned by, e.g., `current-time'."
  20793. (and (file-exists-p file)
  20794. ;; Only compare times up to whole seconds as some file-systems
  20795. ;; (e.g. HFS+) do not retain any finer granularity. As
  20796. ;; a consequence, make sure we return non-nil when the two
  20797. ;; times are equal.
  20798. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20799. (cl-subseq time 0 2)))))
  20800. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20801. "Compile a SOURCE file using PROCESS.
  20802. PROCESS is either a function or a list of shell commands, as
  20803. strings. EXT is a file extension, without the leading dot, as
  20804. a string. It is used to check if the process actually succeeded.
  20805. PROCESS must create a file with the same base name and directory
  20806. as SOURCE, but ending with EXT. The function then returns its
  20807. filename. Otherwise, it raises an error. The error message can
  20808. then be refined by providing string ERR-MSG, which is appended to
  20809. the standard message.
  20810. If PROCESS is a function, it is called with a single argument:
  20811. the SOURCE file.
  20812. If it is a list of commands, each of them is called using
  20813. `shell-command'. By default, in each command, %b, %f, %F and %o
  20814. are replaced with, respectively, SOURCE base name, name, full
  20815. name and directory. It is possible, however, to use more
  20816. place-holders by specifying them in optional argument SPEC, as an
  20817. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20818. When PROCESS is a list of commands, optional argument LOG-BUF can
  20819. be set to a buffer or a buffer name. `shell-command' then uses
  20820. it for output.
  20821. `default-directory' is set to SOURCE directory during the whole
  20822. process."
  20823. (let* ((source-name (file-name-nondirectory source))
  20824. (base-name (file-name-sans-extension source-name))
  20825. (full-name (file-truename source))
  20826. (out-dir (file-name-directory source))
  20827. (time (current-time))
  20828. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20829. (save-window-excursion
  20830. (let ((default-directory (file-name-directory full-name)))
  20831. (pcase process
  20832. ((pred functionp) (funcall process (shell-quote-argument source)))
  20833. ((pred consp)
  20834. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20835. (spec (append spec
  20836. `((?b . ,(shell-quote-argument base-name))
  20837. (?f . ,(shell-quote-argument source-name))
  20838. (?F . ,(shell-quote-argument full-name))
  20839. (?o . ,(shell-quote-argument out-dir))))))
  20840. (dolist (command process)
  20841. (shell-command (format-spec command spec) log-buf))))
  20842. (_ (error "No valid command to process %S%s" source err-msg)))))
  20843. ;; Check for process failure.
  20844. (let ((output (concat out-dir base-name "." ext)))
  20845. (unless (org-file-newer-than-p output time)
  20846. (error (format "File %S wasn't produced%s" output err-msg)))
  20847. output)))
  20848. ;;; Indentation
  20849. (defun org--get-expected-indentation (element contentsp)
  20850. "Expected indentation column for current line, according to ELEMENT.
  20851. ELEMENT is an element containing point. CONTENTSP is non-nil
  20852. when indentation is to be computed according to contents of
  20853. ELEMENT."
  20854. (let ((type (org-element-type element))
  20855. (start (org-element-property :begin element))
  20856. (post-affiliated (org-element-property :post-affiliated element)))
  20857. (org-with-wide-buffer
  20858. (cond
  20859. (contentsp
  20860. (cl-case type
  20861. ((diary-sexp footnote-definition) 0)
  20862. ((headline inlinetask nil)
  20863. (if (not org-adapt-indentation) 0
  20864. (let ((level (org-current-level)))
  20865. (if level (1+ level) 0))))
  20866. ((item plain-list) (org-list-item-body-column post-affiliated))
  20867. (t
  20868. (goto-char start)
  20869. (org-get-indentation))))
  20870. ((memq type '(headline inlinetask nil))
  20871. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20872. (org--get-expected-indentation element t)
  20873. 0))
  20874. ((memq type '(diary-sexp footnote-definition)) 0)
  20875. ;; First paragraph of a footnote definition or an item.
  20876. ;; Indent like parent.
  20877. ((< (line-beginning-position) start)
  20878. (org--get-expected-indentation
  20879. (org-element-property :parent element) t))
  20880. ;; At first line: indent according to previous sibling, if any,
  20881. ;; ignoring footnote definitions and inline tasks, or parent's
  20882. ;; contents.
  20883. ((= (line-beginning-position) start)
  20884. (catch 'exit
  20885. (while t
  20886. (if (= (point-min) start) (throw 'exit 0)
  20887. (goto-char (1- start))
  20888. (let* ((previous (org-element-at-point))
  20889. (parent previous))
  20890. (while (and parent (<= (org-element-property :end parent) start))
  20891. (setq previous parent
  20892. parent (org-element-property :parent parent)))
  20893. (cond
  20894. ((not previous) (throw 'exit 0))
  20895. ((> (org-element-property :end previous) start)
  20896. (throw 'exit (org--get-expected-indentation previous t)))
  20897. ((memq (org-element-type previous)
  20898. '(footnote-definition inlinetask))
  20899. (setq start (org-element-property :begin previous)))
  20900. (t (goto-char (org-element-property :begin previous))
  20901. (throw 'exit
  20902. (if (bolp) (org-get-indentation)
  20903. ;; At first paragraph in an item or
  20904. ;; a footnote definition.
  20905. (org--get-expected-indentation
  20906. (org-element-property :parent previous) t))))))))))
  20907. ;; Otherwise, move to the first non-blank line above.
  20908. (t
  20909. (beginning-of-line)
  20910. (let ((pos (point)))
  20911. (skip-chars-backward " \r\t\n")
  20912. (cond
  20913. ;; Two blank lines end a footnote definition or a plain
  20914. ;; list. When we indent an empty line after them, the
  20915. ;; containing list or footnote definition is over, so it
  20916. ;; qualifies as a previous sibling. Therefore, we indent
  20917. ;; like its first line.
  20918. ((and (memq type '(footnote-definition plain-list))
  20919. (> (count-lines (point) pos) 2))
  20920. (goto-char start)
  20921. (org-get-indentation))
  20922. ;; Line above is the first one of a paragraph at the
  20923. ;; beginning of an item or a footnote definition. Indent
  20924. ;; like parent.
  20925. ((< (line-beginning-position) start)
  20926. (org--get-expected-indentation
  20927. (org-element-property :parent element) t))
  20928. ;; Line above is the beginning of an element, i.e., point
  20929. ;; was originally on the blank lines between element's start
  20930. ;; and contents.
  20931. ((= (line-beginning-position) post-affiliated)
  20932. (org--get-expected-indentation element t))
  20933. ;; POS is after contents in a greater element. Indent like
  20934. ;; the beginning of the element.
  20935. ;;
  20936. ;; As a special case, if point is at the end of a footnote
  20937. ;; definition or an item, indent like the very last element
  20938. ;; within. If that last element is an item, indent like its
  20939. ;; contents.
  20940. ((and (not (eq type 'paragraph))
  20941. (let ((cend (org-element-property :contents-end element)))
  20942. (and cend (<= cend pos))))
  20943. (if (memq type '(footnote-definition item plain-list))
  20944. (let ((last (org-element-at-point)))
  20945. (org--get-expected-indentation
  20946. last (eq (org-element-type last) 'item)))
  20947. (goto-char start)
  20948. (org-get-indentation)))
  20949. ;; In any other case, indent like the current line.
  20950. (t (org-get-indentation)))))))))
  20951. (defun org--align-node-property ()
  20952. "Align node property at point.
  20953. Alignment is done according to `org-property-format', which see."
  20954. (when (save-excursion
  20955. (beginning-of-line)
  20956. (looking-at org-property-re))
  20957. (replace-match
  20958. (concat (match-string 4)
  20959. (org-trim
  20960. (format org-property-format (match-string 1) (match-string 3))))
  20961. t t)))
  20962. (defun org-indent-line ()
  20963. "Indent line depending on context.
  20964. Indentation is done according to the following rules:
  20965. - Footnote definitions, diary sexps, headlines and inline tasks
  20966. have to start at column 0.
  20967. - On the very first line of an element, consider, in order, the
  20968. next rules until one matches:
  20969. 1. If there's a sibling element before, ignoring footnote
  20970. definitions and inline tasks, indent like its first line.
  20971. 2. If element has a parent, indent like its contents. More
  20972. precisely, if parent is an item, indent after the
  20973. description part, if any, or the bullet (see
  20974. `org-list-description-max-indent'). Else, indent like
  20975. parent's first line.
  20976. 3. Otherwise, indent relatively to current level, if
  20977. `org-adapt-indentation' is non-nil, or to left margin.
  20978. - On a blank line at the end of an element, indent according to
  20979. the type of the element. More precisely
  20980. 1. If element is a plain list, an item, or a footnote
  20981. definition, indent like the very last element within.
  20982. 2. If element is a paragraph, indent like its last non blank
  20983. line.
  20984. 3. Otherwise, indent like its very first line.
  20985. - In the code part of a source block, use language major mode
  20986. to indent current line if `org-src-tab-acts-natively' is
  20987. non-nil. If it is nil, do nothing.
  20988. - Otherwise, indent like the first non-blank line above.
  20989. The function doesn't indent an item as it could break the whole
  20990. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20991. `\\[org-shiftmetaright]'.
  20992. Also align node properties according to `org-property-format'."
  20993. (interactive)
  20994. (cond
  20995. (orgstruct-is-++
  20996. (let ((indent-line-function
  20997. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20998. (indent-according-to-mode)))
  20999. ((org-at-heading-p) 'noindent)
  21000. (t
  21001. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21002. (type (org-element-type element)))
  21003. (cond ((and (memq type '(plain-list item))
  21004. (= (line-beginning-position)
  21005. (org-element-property :post-affiliated element)))
  21006. 'noindent)
  21007. ((and (eq type 'src-block)
  21008. org-src-tab-acts-natively
  21009. (> (line-beginning-position)
  21010. (org-element-property :post-affiliated element))
  21011. (< (line-beginning-position)
  21012. (org-with-wide-buffer
  21013. (goto-char (org-element-property :end element))
  21014. (skip-chars-backward " \r\t\n")
  21015. (line-beginning-position))))
  21016. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21017. (t
  21018. (let ((column (org--get-expected-indentation element nil)))
  21019. ;; Preserve current column.
  21020. (if (<= (current-column) (current-indentation))
  21021. (indent-line-to column)
  21022. (save-excursion (indent-line-to column))))
  21023. ;; Align node property. Also preserve current column.
  21024. (when (eq type 'node-property)
  21025. (let ((column (current-column)))
  21026. (org--align-node-property)
  21027. (org-move-to-column column)))))))))
  21028. (defun org-indent-region (start end)
  21029. "Indent each non-blank line in the region.
  21030. Called from a program, START and END specify the region to
  21031. indent. The function will not indent contents of example blocks,
  21032. verse blocks and export blocks as leading white spaces are
  21033. assumed to be significant there."
  21034. (interactive "r")
  21035. (save-excursion
  21036. (goto-char start)
  21037. (skip-chars-forward " \r\t\n")
  21038. (unless (eobp) (beginning-of-line))
  21039. (let ((indent-to
  21040. (lambda (ind pos)
  21041. ;; Set IND as indentation for all lines between point and
  21042. ;; POS. Blank lines are ignored. Leave point after POS
  21043. ;; once done.
  21044. (let ((limit (copy-marker pos)))
  21045. (while (< (point) limit)
  21046. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21047. (forward-line))
  21048. (set-marker limit nil))))
  21049. (end (copy-marker end)))
  21050. (while (< (point) end)
  21051. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21052. (let* ((element (org-element-at-point))
  21053. (type (org-element-type element))
  21054. (element-end (copy-marker (org-element-property :end element)))
  21055. (ind (org--get-expected-indentation element nil)))
  21056. (cond
  21057. ((or (memq type '(paragraph table table-row))
  21058. (not (or (org-element-property :contents-begin element)
  21059. (memq type
  21060. '(example-block export-block src-block)))))
  21061. ;; Elements here are indented as a single block. Also
  21062. ;; align node properties.
  21063. (when (eq type 'node-property)
  21064. (org--align-node-property)
  21065. (beginning-of-line))
  21066. (funcall indent-to ind (min element-end end)))
  21067. (t
  21068. ;; Elements in this category consist of three parts:
  21069. ;; before the contents, the contents, and after the
  21070. ;; contents. The contents are treated specially,
  21071. ;; according to the element type, or not indented at
  21072. ;; all. Other parts are indented as a single block.
  21073. (let* ((post (copy-marker
  21074. (org-element-property :post-affiliated element)))
  21075. (cbeg
  21076. (copy-marker
  21077. (cond
  21078. ((not (org-element-property :contents-begin element))
  21079. ;; Fake contents for source blocks.
  21080. (org-with-wide-buffer
  21081. (goto-char post)
  21082. (forward-line)
  21083. (point)))
  21084. ((memq type '(footnote-definition item plain-list))
  21085. ;; Contents in these elements could start on
  21086. ;; the same line as the beginning of the
  21087. ;; element. Make sure we start indenting
  21088. ;; from the second line.
  21089. (org-with-wide-buffer
  21090. (goto-char post)
  21091. (end-of-line)
  21092. (skip-chars-forward " \r\t\n")
  21093. (if (eobp) (point) (line-beginning-position))))
  21094. (t (org-element-property :contents-begin element)))))
  21095. (cend (copy-marker
  21096. (or (org-element-property :contents-end element)
  21097. ;; Fake contents for source blocks.
  21098. (org-with-wide-buffer
  21099. (goto-char element-end)
  21100. (skip-chars-backward " \r\t\n")
  21101. (line-beginning-position)))
  21102. t)))
  21103. ;; Do not change items indentation individually as it
  21104. ;; might break the list as a whole. On the other
  21105. ;; hand, when at a plain list, indent it as a whole.
  21106. (cond ((eq type 'plain-list)
  21107. (let ((offset (- ind (org-get-indentation))))
  21108. (unless (zerop offset)
  21109. (indent-rigidly (org-element-property :begin element)
  21110. (org-element-property :end element)
  21111. offset))
  21112. (goto-char cbeg)))
  21113. ((eq type 'item) (goto-char cbeg))
  21114. (t (funcall indent-to ind (min cbeg end))))
  21115. (when (< (point) end)
  21116. (cl-case type
  21117. ((example-block export-block verse-block))
  21118. (src-block
  21119. ;; In a source block, indent source code
  21120. ;; according to language major mode, but only if
  21121. ;; `org-src-tab-acts-natively' is non-nil.
  21122. (when (and (< (point) end) org-src-tab-acts-natively)
  21123. (ignore-errors
  21124. (org-babel-do-in-edit-buffer
  21125. (indent-region (point-min) (point-max))))))
  21126. (t (org-indent-region (point) (min cend end))))
  21127. (goto-char (min cend end))
  21128. (when (< (point) end)
  21129. (funcall indent-to ind (min element-end end))))
  21130. (set-marker post nil)
  21131. (set-marker cbeg nil)
  21132. (set-marker cend nil))))
  21133. (set-marker element-end nil))))
  21134. (set-marker end nil))))
  21135. (defun org-indent-drawer ()
  21136. "Indent the drawer at point."
  21137. (interactive)
  21138. (unless (save-excursion
  21139. (beginning-of-line)
  21140. (looking-at-p org-drawer-regexp))
  21141. (user-error "Not at a drawer"))
  21142. (let ((element (org-element-at-point)))
  21143. (unless (memq (org-element-type element) '(drawer property-drawer))
  21144. (user-error "Not at a drawer"))
  21145. (org-with-wide-buffer
  21146. (org-indent-region (org-element-property :begin element)
  21147. (org-element-property :end element))))
  21148. (message "Drawer at point indented"))
  21149. (defun org-indent-block ()
  21150. "Indent the block at point."
  21151. (interactive)
  21152. (unless (save-excursion
  21153. (beginning-of-line)
  21154. (let ((case-fold-search t))
  21155. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21156. (user-error "Not at a block"))
  21157. (let ((element (org-element-at-point)))
  21158. (unless (memq (org-element-type element)
  21159. '(comment-block center-block dynamic-block example-block
  21160. export-block quote-block special-block
  21161. src-block verse-block))
  21162. (user-error "Not at a block"))
  21163. (org-with-wide-buffer
  21164. (org-indent-region (org-element-property :begin element)
  21165. (org-element-property :end element))))
  21166. (message "Block at point indented"))
  21167. ;;; Filling
  21168. ;; We use our own fill-paragraph and auto-fill functions.
  21169. ;; `org-fill-paragraph' relies on adaptive filling and context
  21170. ;; checking. Appropriate `fill-prefix' is computed with
  21171. ;; `org-adaptive-fill-function'.
  21172. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21173. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21174. ;; `org-adaptive-fill-function' value. Internally,
  21175. ;; `org-comment-line-break-function' breaks the line.
  21176. ;; `org-setup-filling' installs filling and auto-filling related
  21177. ;; variables during `org-mode' initialization.
  21178. (defvar org-element-paragraph-separate) ; org-element.el
  21179. (defun org-setup-filling ()
  21180. (require 'org-element)
  21181. ;; Prevent auto-fill from inserting unwanted new items.
  21182. (when (boundp 'fill-nobreak-predicate)
  21183. (setq-local
  21184. fill-nobreak-predicate
  21185. (org-uniquify
  21186. (append fill-nobreak-predicate
  21187. '(org-fill-line-break-nobreak-p
  21188. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21189. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21190. (setq-local paragraph-start paragraph-ending)
  21191. (setq-local paragraph-separate paragraph-ending))
  21192. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21193. (setq-local auto-fill-inhibit-regexp nil)
  21194. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21195. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21196. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21197. (defun org-fill-line-break-nobreak-p ()
  21198. "Non-nil when a new line at point would create an Org line break."
  21199. (save-excursion
  21200. (skip-chars-backward "[ \t]")
  21201. (skip-chars-backward "\\\\")
  21202. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21203. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21204. "Non-nil when a new line at point would split a timestamp."
  21205. (and (org-at-timestamp-p t)
  21206. (not (looking-at org-ts-regexp-both))))
  21207. (declare-function message-in-body-p "message" ())
  21208. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21209. (defun org-adaptive-fill-function ()
  21210. "Compute a fill prefix for the current line.
  21211. Return fill prefix, as a string, or nil if current line isn't
  21212. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21213. matches in paragraphs or comments, use it."
  21214. (catch 'exit
  21215. (when (derived-mode-p 'message-mode)
  21216. (save-excursion
  21217. (beginning-of-line)
  21218. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21219. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21220. ((looking-at message-cite-prefix-regexp)
  21221. (throw 'exit (match-string-no-properties 0)))
  21222. ((looking-at org-outline-regexp)
  21223. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21224. (org-with-wide-buffer
  21225. (unless (org-at-heading-p)
  21226. (let* ((p (line-beginning-position))
  21227. (element (save-excursion
  21228. (beginning-of-line)
  21229. (org-element-at-point)))
  21230. (type (org-element-type element))
  21231. (post-affiliated (org-element-property :post-affiliated element)))
  21232. (unless (< p post-affiliated)
  21233. (cl-case type
  21234. (comment
  21235. (save-excursion
  21236. (beginning-of-line)
  21237. (looking-at "[ \t]*")
  21238. (concat (match-string 0) "# ")))
  21239. (footnote-definition "")
  21240. ((item plain-list)
  21241. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21242. (paragraph
  21243. ;; Fill prefix is usually the same as the current line,
  21244. ;; unless the paragraph is at the beginning of an item.
  21245. (let ((parent (org-element-property :parent element)))
  21246. (save-excursion
  21247. (beginning-of-line)
  21248. (cond ((eq (org-element-type parent) 'item)
  21249. (make-string (org-list-item-body-column
  21250. (org-element-property :begin parent))
  21251. ?\s))
  21252. ((and adaptive-fill-regexp
  21253. ;; Locally disable
  21254. ;; `adaptive-fill-function' to let
  21255. ;; `fill-context-prefix' handle
  21256. ;; `adaptive-fill-regexp' variable.
  21257. (let (adaptive-fill-function)
  21258. (fill-context-prefix
  21259. post-affiliated
  21260. (org-element-property :end element)))))
  21261. ((looking-at "[ \t]+") (match-string 0))
  21262. (t "")))))
  21263. (comment-block
  21264. ;; Only fill contents if P is within block boundaries.
  21265. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21266. (forward-line)
  21267. (point)))
  21268. (cend (save-excursion
  21269. (goto-char (org-element-property :end element))
  21270. (skip-chars-backward " \r\t\n")
  21271. (line-beginning-position))))
  21272. (when (and (>= p cbeg) (< p cend))
  21273. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21274. (match-string 0)
  21275. "")))))))))))
  21276. (declare-function message-goto-body "message" ())
  21277. (defvar message-cite-prefix-regexp) ; From message.el
  21278. (defun org-fill-paragraph (&optional justify)
  21279. "Fill element at point, when applicable.
  21280. This function only applies to comment blocks, comments, example
  21281. blocks and paragraphs. Also, as a special case, re-align table
  21282. when point is at one.
  21283. If JUSTIFY is non-nil (interactively, with prefix argument),
  21284. justify as well. If `sentence-end-double-space' is non-nil, then
  21285. period followed by one space does not end a sentence, so don't
  21286. break a line there. The variable `fill-column' controls the
  21287. width for filling.
  21288. For convenience, when point is at a plain list, an item or
  21289. a footnote definition, try to fill the first paragraph within."
  21290. (interactive)
  21291. (if (and (derived-mode-p 'message-mode)
  21292. (or (not (message-in-body-p))
  21293. (save-excursion (move-beginning-of-line 1)
  21294. (looking-at message-cite-prefix-regexp))))
  21295. ;; First ensure filling is correct in message-mode.
  21296. (let ((fill-paragraph-function
  21297. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21298. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21299. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21300. (paragraph-separate
  21301. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21302. (fill-paragraph nil))
  21303. (with-syntax-table org-mode-transpose-word-syntax-table
  21304. ;; Move to end of line in order to get the first paragraph
  21305. ;; within a plain list or a footnote definition.
  21306. (let ((element (save-excursion
  21307. (end-of-line)
  21308. (or (ignore-errors (org-element-at-point))
  21309. (user-error "An element cannot be parsed line %d"
  21310. (line-number-at-pos (point)))))))
  21311. ;; First check if point is in a blank line at the beginning of
  21312. ;; the buffer. In that case, ignore filling.
  21313. (cl-case (org-element-type element)
  21314. ;; Use major mode filling function is src blocks.
  21315. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21316. ;; Align Org tables, leave table.el tables as-is.
  21317. (table-row (org-table-align) t)
  21318. (table
  21319. (when (eq (org-element-property :type element) 'org)
  21320. (save-excursion
  21321. (goto-char (org-element-property :post-affiliated element))
  21322. (org-table-align)))
  21323. t)
  21324. (paragraph
  21325. ;; Paragraphs may contain `line-break' type objects.
  21326. (let ((beg (max (point-min)
  21327. (org-element-property :contents-begin element)))
  21328. (end (min (point-max)
  21329. (org-element-property :contents-end element))))
  21330. ;; Do nothing if point is at an affiliated keyword.
  21331. (if (< (line-end-position) beg) t
  21332. (when (derived-mode-p 'message-mode)
  21333. ;; In `message-mode', do not fill following citation
  21334. ;; in current paragraph nor text before message body.
  21335. (let ((body-start (save-excursion (message-goto-body))))
  21336. (when body-start (setq beg (max body-start beg))))
  21337. (when (save-excursion
  21338. (re-search-forward
  21339. (concat "^" message-cite-prefix-regexp) end t))
  21340. (setq end (match-beginning 0))))
  21341. ;; Fill paragraph, taking line breaks into account.
  21342. (save-excursion
  21343. (goto-char beg)
  21344. (let ((cuts (list beg)))
  21345. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21346. (when (eq 'line-break
  21347. (org-element-type
  21348. (save-excursion (backward-char)
  21349. (org-element-context))))
  21350. (push (point) cuts)))
  21351. (dolist (c (delq end cuts))
  21352. (fill-region-as-paragraph c end justify)
  21353. (setq end c))))
  21354. t)))
  21355. ;; Contents of `comment-block' type elements should be
  21356. ;; filled as plain text, but only if point is within block
  21357. ;; markers.
  21358. (comment-block
  21359. (let* ((case-fold-search t)
  21360. (beg (save-excursion
  21361. (goto-char (org-element-property :begin element))
  21362. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21363. (forward-line)
  21364. (point)))
  21365. (end (save-excursion
  21366. (goto-char (org-element-property :end element))
  21367. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21368. (line-beginning-position))))
  21369. (if (or (< (point) beg) (> (point) end)) t
  21370. (fill-region-as-paragraph
  21371. (save-excursion (end-of-line)
  21372. (re-search-backward "^[ \t]*$" beg 'move)
  21373. (line-beginning-position))
  21374. (save-excursion (beginning-of-line)
  21375. (re-search-forward "^[ \t]*$" end 'move)
  21376. (line-beginning-position))
  21377. justify))))
  21378. ;; Fill comments.
  21379. (comment
  21380. (let ((begin (org-element-property :post-affiliated element))
  21381. (end (org-element-property :end element)))
  21382. (when (and (>= (point) begin) (<= (point) end))
  21383. (let ((begin (save-excursion
  21384. (end-of-line)
  21385. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21386. (progn (forward-line) (point))
  21387. begin)))
  21388. (end (save-excursion
  21389. (end-of-line)
  21390. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21391. (1- (line-beginning-position))
  21392. (skip-chars-backward " \r\t\n")
  21393. (line-end-position)))))
  21394. ;; Do not fill comments when at a blank line.
  21395. (when (> end begin)
  21396. (let ((fill-prefix
  21397. (save-excursion
  21398. (beginning-of-line)
  21399. (looking-at "[ \t]*#")
  21400. (let ((comment-prefix (match-string 0)))
  21401. (goto-char (match-end 0))
  21402. (if (looking-at adaptive-fill-regexp)
  21403. (concat comment-prefix (match-string 0))
  21404. (concat comment-prefix " "))))))
  21405. (save-excursion
  21406. (fill-region-as-paragraph begin end justify))))))
  21407. t))
  21408. ;; Ignore every other element.
  21409. (otherwise t))))))
  21410. (defun org-auto-fill-function ()
  21411. "Auto-fill function."
  21412. ;; Check if auto-filling is meaningful.
  21413. (let ((fc (current-fill-column)))
  21414. (when (and fc (> (current-column) fc))
  21415. (let* ((fill-prefix (org-adaptive-fill-function))
  21416. ;; Enforce empty fill prefix, if required. Otherwise, it
  21417. ;; will be computed again.
  21418. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21419. (when fill-prefix (do-auto-fill))))))
  21420. (defun org-comment-line-break-function (&optional soft)
  21421. "Break line at point and indent, continuing comment if within one.
  21422. The inserted newline is marked hard if variable
  21423. `use-hard-newlines' is true, unless optional argument SOFT is
  21424. non-nil."
  21425. (if soft (insert-and-inherit ?\n) (newline 1))
  21426. (save-excursion (forward-char -1) (delete-horizontal-space))
  21427. (delete-horizontal-space)
  21428. (indent-to-left-margin)
  21429. (insert-before-markers-and-inherit fill-prefix))
  21430. ;;; Fixed Width Areas
  21431. (defun org-toggle-fixed-width ()
  21432. "Toggle fixed-width markup.
  21433. Add or remove fixed-width markup on current line, whenever it
  21434. makes sense. Return an error otherwise.
  21435. If a region is active and if it contains only fixed-width areas
  21436. or blank lines, remove all fixed-width markup in it. If the
  21437. region contains anything else, convert all non-fixed-width lines
  21438. to fixed-width ones.
  21439. Blank lines at the end of the region are ignored unless the
  21440. region only contains such lines."
  21441. (interactive)
  21442. (if (not (org-region-active-p))
  21443. ;; No region:
  21444. ;;
  21445. ;; Remove fixed width marker only in a fixed-with element.
  21446. ;;
  21447. ;; Add fixed width maker in paragraphs, in blank lines after
  21448. ;; elements or at the beginning of a headline or an inlinetask,
  21449. ;; and before any one-line elements (e.g., a clock).
  21450. (progn
  21451. (beginning-of-line)
  21452. (let* ((element (org-element-at-point))
  21453. (type (org-element-type element)))
  21454. (cond
  21455. ((and (eq type 'fixed-width)
  21456. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21457. (replace-match
  21458. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21459. ((and (memq type '(babel-call clock comment diary-sexp headline
  21460. horizontal-rule keyword paragraph
  21461. planning))
  21462. (<= (org-element-property :post-affiliated element) (point)))
  21463. (skip-chars-forward " \t")
  21464. (insert ": "))
  21465. ((and (looking-at-p "[ \t]*$")
  21466. (or (eq type 'inlinetask)
  21467. (save-excursion
  21468. (skip-chars-forward " \r\t\n")
  21469. (<= (org-element-property :end element) (point)))))
  21470. (delete-region (point) (line-end-position))
  21471. (org-indent-line)
  21472. (insert ": "))
  21473. (t (user-error "Cannot insert a fixed-width line here")))))
  21474. ;; Region active.
  21475. (let* ((begin (save-excursion
  21476. (goto-char (region-beginning))
  21477. (line-beginning-position)))
  21478. (end (copy-marker
  21479. (save-excursion
  21480. (goto-char (region-end))
  21481. (unless (eolp) (beginning-of-line))
  21482. (if (save-excursion (re-search-backward "\\S-" begin t))
  21483. (progn (skip-chars-backward " \r\t\n") (point))
  21484. (point)))))
  21485. (all-fixed-width-p
  21486. (catch 'not-all-p
  21487. (save-excursion
  21488. (goto-char begin)
  21489. (skip-chars-forward " \r\t\n")
  21490. (when (eobp) (throw 'not-all-p nil))
  21491. (while (< (point) end)
  21492. (let ((element (org-element-at-point)))
  21493. (if (eq (org-element-type element) 'fixed-width)
  21494. (goto-char (org-element-property :end element))
  21495. (throw 'not-all-p nil))))
  21496. t))))
  21497. (if all-fixed-width-p
  21498. (save-excursion
  21499. (goto-char begin)
  21500. (while (< (point) end)
  21501. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21502. (replace-match
  21503. "" nil nil nil
  21504. (if (= (line-end-position) (match-end 0)) 0 1)))
  21505. (forward-line)))
  21506. (let ((min-ind (point-max)))
  21507. ;; Find minimum indentation across all lines.
  21508. (save-excursion
  21509. (goto-char begin)
  21510. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21511. (setq min-ind 0)
  21512. (catch 'zerop
  21513. (while (< (point) end)
  21514. (unless (looking-at-p "[ \t]*$")
  21515. (let ((ind (org-get-indentation)))
  21516. (setq min-ind (min min-ind ind))
  21517. (when (zerop ind) (throw 'zerop t))))
  21518. (forward-line)))))
  21519. ;; Loop over all lines and add fixed-width markup everywhere
  21520. ;; but in fixed-width lines.
  21521. (save-excursion
  21522. (goto-char begin)
  21523. (while (< (point) end)
  21524. (cond
  21525. ((org-at-heading-p)
  21526. (insert ": ")
  21527. (forward-line)
  21528. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21529. (insert ":")
  21530. (forward-line)))
  21531. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21532. (let* ((element (org-element-at-point))
  21533. (element-end (org-element-property :end element)))
  21534. (if (eq (org-element-type element) 'fixed-width)
  21535. (progn (goto-char element-end)
  21536. (skip-chars-backward " \r\t\n")
  21537. (forward-line))
  21538. (let ((limit (min end element-end)))
  21539. (while (< (point) limit)
  21540. (org-move-to-column min-ind t)
  21541. (insert ": ")
  21542. (forward-line))))))
  21543. (t
  21544. (org-move-to-column min-ind t)
  21545. (insert ": ")
  21546. (forward-line)))))))
  21547. (set-marker end nil))))
  21548. ;;; Comments
  21549. ;; Org comments syntax is quite complex. It requires the entire line
  21550. ;; to be just a comment. Also, even with the right syntax at the
  21551. ;; beginning of line, some some elements (i.e. verse-block or
  21552. ;; example-block) don't accept comments. Usual Emacs comment commands
  21553. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21554. ;; Org still relies on `comment-dwim', but cannot trust
  21555. ;; `comment-only-p'. So, `comment-region-function' and
  21556. ;; `uncomment-region-function' both point
  21557. ;; to`org-comment-or-uncomment-region'. Eventually,
  21558. ;; `org-insert-comment' takes care of insertion of comments at the
  21559. ;; beginning of line.
  21560. ;; `org-setup-comments-handling' install comments related variables
  21561. ;; during `org-mode' initialization.
  21562. (defun org-setup-comments-handling ()
  21563. (interactive)
  21564. (setq-local comment-use-syntax nil)
  21565. (setq-local comment-start "# ")
  21566. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21567. (setq-local comment-insert-comment-function 'org-insert-comment)
  21568. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21569. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21570. (defun org-insert-comment ()
  21571. "Insert an empty comment above current line.
  21572. If the line is empty, insert comment at its beginning. When
  21573. point is within a source block, comment according to the related
  21574. major mode."
  21575. (if (let ((element (org-element-at-point)))
  21576. (and (eq (org-element-type element) 'src-block)
  21577. (< (save-excursion
  21578. (goto-char (org-element-property :post-affiliated element))
  21579. (line-end-position))
  21580. (point))
  21581. (> (save-excursion
  21582. (goto-char (org-element-property :end element))
  21583. (skip-chars-backward " \r\t\n")
  21584. (line-beginning-position))
  21585. (point))))
  21586. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21587. (beginning-of-line)
  21588. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21589. (open-line 1))
  21590. (org-indent-line)
  21591. (insert "# ")))
  21592. (defvar comment-empty-lines) ; From newcomment.el.
  21593. (defun org-comment-or-uncomment-region (beg end &rest _)
  21594. "Comment or uncomment each non-blank line in the region.
  21595. Uncomment each non-blank line between BEG and END if it only
  21596. contains commented lines. Otherwise, comment them. If region is
  21597. strictly within a source block, use appropriate comment syntax."
  21598. (if (let ((element (org-element-at-point)))
  21599. (and (eq (org-element-type element) 'src-block)
  21600. (< (save-excursion
  21601. (goto-char (org-element-property :post-affiliated element))
  21602. (line-end-position))
  21603. beg)
  21604. (>= (save-excursion
  21605. (goto-char (org-element-property :end element))
  21606. (skip-chars-backward " \r\t\n")
  21607. (line-beginning-position))
  21608. end)))
  21609. ;; Translate region boundaries for the Org buffer to the source
  21610. ;; buffer.
  21611. (let ((offset (- end beg)))
  21612. (save-excursion
  21613. (goto-char beg)
  21614. (org-babel-do-in-edit-buffer
  21615. (comment-or-uncomment-region (point) (+ offset (point))))))
  21616. (save-restriction
  21617. ;; Restrict region
  21618. (narrow-to-region (save-excursion (goto-char beg)
  21619. (skip-chars-forward " \r\t\n" end)
  21620. (line-beginning-position))
  21621. (save-excursion (goto-char end)
  21622. (skip-chars-backward " \r\t\n" beg)
  21623. (line-end-position)))
  21624. (let ((uncommentp
  21625. ;; UNCOMMENTP is non-nil when every non blank line between
  21626. ;; BEG and END is a comment.
  21627. (save-excursion
  21628. (goto-char (point-min))
  21629. (while (and (not (eobp))
  21630. (let ((element (org-element-at-point)))
  21631. (and (eq (org-element-type element) 'comment)
  21632. (goto-char (min (point-max)
  21633. (org-element-property
  21634. :end element)))))))
  21635. (eobp))))
  21636. (if uncommentp
  21637. ;; Only blank lines and comments in region: uncomment it.
  21638. (save-excursion
  21639. (goto-char (point-min))
  21640. (while (not (eobp))
  21641. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21642. (replace-match "" nil nil nil 1))
  21643. (forward-line)))
  21644. ;; Comment each line in region.
  21645. (let ((min-indent (point-max)))
  21646. ;; First find the minimum indentation across all lines.
  21647. (save-excursion
  21648. (goto-char (point-min))
  21649. (while (and (not (eobp)) (not (zerop min-indent)))
  21650. (unless (looking-at "[ \t]*$")
  21651. (setq min-indent (min min-indent (current-indentation))))
  21652. (forward-line)))
  21653. ;; Then loop over all lines.
  21654. (save-excursion
  21655. (goto-char (point-min))
  21656. (while (not (eobp))
  21657. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21658. ;; Don't get fooled by invisible text (e.g. link path)
  21659. ;; when moving to column MIN-INDENT.
  21660. (let ((buffer-invisibility-spec nil))
  21661. (org-move-to-column min-indent t))
  21662. (insert comment-start))
  21663. (forward-line)))))))))
  21664. (defun org-comment-dwim (_arg)
  21665. "Call `comment-dwim' within a source edit buffer if needed."
  21666. (interactive "*P")
  21667. (if (org-in-src-block-p)
  21668. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21669. (call-interactively 'comment-dwim)))
  21670. ;;; Timestamps API
  21671. ;; This section contains tools to operate on timestamp objects, as
  21672. ;; returned by, e.g. `org-element-context'.
  21673. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21674. "Encode TIMESTAMP object into Emacs internal time.
  21675. Use end of date range or time range when END is non-nil."
  21676. (apply #'encode-time
  21677. (cons 0
  21678. (mapcar
  21679. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21680. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21681. '(:minute-start :hour-start :day-start :month-start
  21682. :year-start))))))
  21683. (defun org-timestamp-has-time-p (timestamp)
  21684. "Non-nil when TIMESTAMP has a time specified."
  21685. (org-element-property :hour-start timestamp))
  21686. (defun org-timestamp-format (timestamp format &optional end utc)
  21687. "Format a TIMESTAMP object into a string.
  21688. FORMAT is a format specifier to be passed to
  21689. `format-time-string'.
  21690. When optional argument END is non-nil, use end of date-range or
  21691. time-range, if possible.
  21692. When optional argument UTC is non-nil, time will be expressed as
  21693. Universal Time."
  21694. (format-time-string
  21695. format (org-timestamp--to-internal-time timestamp end)
  21696. (and utc t)))
  21697. (defun org-timestamp-split-range (timestamp &optional end)
  21698. "Extract a TIMESTAMP object from a date or time range.
  21699. END, when non-nil, means extract the end of the range.
  21700. Otherwise, extract its start.
  21701. Return a new timestamp object."
  21702. (let ((type (org-element-property :type timestamp)))
  21703. (if (memq type '(active inactive diary)) timestamp
  21704. (let ((split-ts (org-element-copy timestamp)))
  21705. ;; Set new type.
  21706. (org-element-put-property
  21707. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21708. ;; Copy start properties over end properties if END is
  21709. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21710. (let ((p-alist '((:minute-start . :minute-end)
  21711. (:hour-start . :hour-end)
  21712. (:day-start . :day-end)
  21713. (:month-start . :month-end)
  21714. (:year-start . :year-end))))
  21715. (dolist (p-cell p-alist)
  21716. (org-element-put-property
  21717. split-ts
  21718. (funcall (if end #'car #'cdr) p-cell)
  21719. (org-element-property
  21720. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21721. ;; Eventually refresh `:raw-value'.
  21722. (org-element-put-property split-ts :raw-value nil)
  21723. (org-element-put-property
  21724. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21725. (defun org-timestamp-translate (timestamp &optional boundary)
  21726. "Translate TIMESTAMP object to custom format.
  21727. Format string is defined in `org-time-stamp-custom-formats',
  21728. which see.
  21729. When optional argument BOUNDARY is non-nil, it is either the
  21730. symbol `start' or `end'. In this case, only translate the
  21731. starting or ending part of TIMESTAMP if it is a date or time
  21732. range. Otherwise, translate both parts.
  21733. Return timestamp as-is if `org-display-custom-times' is nil or if
  21734. it has a `diary' type."
  21735. (let ((type (org-element-property :type timestamp)))
  21736. (if (or (not org-display-custom-times) (eq type 'diary))
  21737. (org-element-interpret-data timestamp)
  21738. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21739. org-time-stamp-custom-formats)))
  21740. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21741. (concat (org-timestamp-format timestamp fmt)
  21742. "--"
  21743. (org-timestamp-format timestamp fmt t))
  21744. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21745. ;;; Other stuff.
  21746. (defvar reftex-docstruct-symbol)
  21747. (defvar org--rds)
  21748. (defun org-reftex-citation ()
  21749. "Use reftex-citation to insert a citation into the buffer.
  21750. This looks for a line like
  21751. #+BIBLIOGRAPHY: foo plain option:-d
  21752. and derives from it that foo.bib is the bibliography file relevant
  21753. for this document. It then installs the necessary environment for RefTeX
  21754. to work in this buffer and calls `reftex-citation' to insert a citation
  21755. into the buffer.
  21756. Export of such citations to both LaTeX and HTML is handled by the contributed
  21757. package ox-bibtex by Taru Karttunen."
  21758. (interactive)
  21759. (let ((reftex-docstruct-symbol 'org--rds)
  21760. org--rds bib)
  21761. (org-with-wide-buffer
  21762. (let ((case-fold-search t)
  21763. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21764. (if (not (save-excursion
  21765. (or (re-search-forward re nil t)
  21766. (re-search-backward re nil t))))
  21767. (user-error "No bibliography defined in file")
  21768. (setq bib (concat (match-string 1) ".bib")
  21769. org--rds (list (list 'bib bib))))))
  21770. (call-interactively 'reftex-citation)))
  21771. ;;;; Functions extending outline functionality
  21772. (defun org-beginning-of-line (&optional n)
  21773. "Go to the beginning of the current visible line.
  21774. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21775. tags on the first attempt, and only move to after the tags when
  21776. the cursor is already beyond the end of the headline.
  21777. With argument N not nil or 1, move forward N - 1 lines first."
  21778. (interactive "^p")
  21779. (let ((origin (point))
  21780. (special (pcase org-special-ctrl-a/e
  21781. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21782. deactivate-mark)
  21783. ;; First move to a visible line.
  21784. (if (bound-and-true-p visual-line-mode)
  21785. (beginning-of-visual-line n)
  21786. (move-beginning-of-line n)
  21787. ;; `move-beginning-of-line' may leave point after invisible
  21788. ;; characters if line starts with such of these (e.g., with
  21789. ;; a link at column 0). Really move to the beginning of the
  21790. ;; current visible line.
  21791. (beginning-of-line))
  21792. (cond
  21793. ;; No special behavior. Point is already at the beginning of
  21794. ;; a line, logical or visual.
  21795. ((not special))
  21796. ;; `beginning-of-visual-line' left point before logical beginning
  21797. ;; of line: point is at the beginning of a visual line. Bail
  21798. ;; out.
  21799. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21800. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21801. ;; At a headline, special position is before the title, but
  21802. ;; after any TODO keyword or priority cookie.
  21803. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21804. (line-end-position)))
  21805. (bol (point)))
  21806. (if (eq special 'reversed)
  21807. (when (and (= origin bol) (eq last-command this-command))
  21808. (goto-char refpos))
  21809. (when (or (> origin refpos) (= origin bol))
  21810. (goto-char refpos)))))
  21811. ((and (looking-at org-list-full-item-re)
  21812. (memq (org-element-type (save-match-data (org-element-at-point)))
  21813. '(item plain-list)))
  21814. ;; Set special position at first white space character after
  21815. ;; bullet, and check-box, if any.
  21816. (let ((after-bullet
  21817. (let ((box (match-end 3)))
  21818. (cond ((not box) (match-end 1))
  21819. ((eq (char-after box) ?\s) (1+ box))
  21820. (t box)))))
  21821. (if (eq special 'reversed)
  21822. (when (and (= (point) origin) (eq last-command this-command))
  21823. (goto-char after-bullet))
  21824. (when (or (> origin after-bullet) (= (point) origin))
  21825. (goto-char after-bullet)))))
  21826. ;; No special context. Point is already at beginning of line.
  21827. (t nil))))
  21828. (defun org-end-of-line (&optional n)
  21829. "Go to the end of the line, but before ellipsis, if any.
  21830. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21831. tags on the first attempt, and only move to after the tags when
  21832. the cursor is already beyond the end of the headline.
  21833. With argument N not nil or 1, move forward N - 1 lines first."
  21834. (interactive "^p")
  21835. (let ((origin (point))
  21836. (special (pcase org-special-ctrl-a/e
  21837. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21838. deactivate-mark)
  21839. ;; First move to a visible line.
  21840. (if (bound-and-true-p visual-line-mode)
  21841. (beginning-of-visual-line n)
  21842. (move-beginning-of-line n))
  21843. (cond
  21844. ;; At a headline, with tags.
  21845. ((and special
  21846. (save-excursion
  21847. (beginning-of-line)
  21848. (let ((case-fold-search nil))
  21849. (looking-at org-complex-heading-regexp)))
  21850. (match-end 5))
  21851. (let ((tags (save-excursion
  21852. (goto-char (match-beginning 5))
  21853. (skip-chars-backward " \t")
  21854. (point)))
  21855. (visual-end (and (bound-and-true-p visual-line-mode)
  21856. (save-excursion
  21857. (end-of-visual-line)
  21858. (point)))))
  21859. ;; If `end-of-visual-line' brings us before end of line or
  21860. ;; even tags, i.e., the headline spans over multiple visual
  21861. ;; lines, move there.
  21862. (cond ((and visual-end
  21863. (< visual-end tags)
  21864. (<= origin visual-end))
  21865. (goto-char visual-end))
  21866. ((eq special 'reversed)
  21867. (if (and (= origin (line-end-position))
  21868. (eq this-command last-command))
  21869. (goto-char tags)
  21870. (end-of-line)))
  21871. (t
  21872. (if (or (< origin tags) (= origin (line-end-position)))
  21873. (goto-char tags)
  21874. (end-of-line))))))
  21875. ((bound-and-true-p visual-line-mode)
  21876. (let ((bol (line-beginning-position)))
  21877. (end-of-visual-line)
  21878. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21879. ;; end of a line, backtrack and use `end-of-line' instead.
  21880. (when (/= bol (line-beginning-position))
  21881. (goto-char bol)
  21882. (end-of-line))))
  21883. (t (end-of-line)))))
  21884. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21885. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21886. (defun org-backward-sentence (&optional _arg)
  21887. "Go to beginning of sentence, or beginning of table field.
  21888. This will call `backward-sentence' or `org-table-beginning-of-field',
  21889. depending on context."
  21890. (interactive)
  21891. (let* ((element (org-element-at-point))
  21892. (contents-begin (org-element-property :contents-begin element))
  21893. (table (org-element-lineage element '(table) t)))
  21894. (if (and table
  21895. (> (point) contents-begin)
  21896. (<= (point) (org-element-property :contents-end table)))
  21897. (call-interactively #'org-table-beginning-of-field)
  21898. (save-restriction
  21899. (when (and contents-begin
  21900. (< (point-min) contents-begin)
  21901. (> (point) contents-begin))
  21902. (narrow-to-region contents-begin
  21903. (org-element-property :contents-end element)))
  21904. (call-interactively #'backward-sentence)))))
  21905. (defun org-forward-sentence (&optional _arg)
  21906. "Go to end of sentence, or end of table field.
  21907. This will call `forward-sentence' or `org-table-end-of-field',
  21908. depending on context."
  21909. (interactive)
  21910. (let* ((element (org-element-at-point))
  21911. (contents-end (org-element-property :contents-end element))
  21912. (table (org-element-lineage element '(table) t)))
  21913. (if (and table
  21914. (>= (point) (org-element-property :contents-begin table))
  21915. (< (point) contents-end))
  21916. (call-interactively #'org-table-end-of-field)
  21917. (save-restriction
  21918. (when (and contents-end
  21919. (> (point-max) contents-end)
  21920. ;; Skip blank lines between elements.
  21921. (< (org-element-property :end element)
  21922. (save-excursion (goto-char contents-end)
  21923. (skip-chars-forward " \r\t\n"))))
  21924. (narrow-to-region (org-element-property :contents-begin element)
  21925. contents-end))
  21926. (call-interactively #'forward-sentence)))))
  21927. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21928. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21929. (defun org-kill-line (&optional _arg)
  21930. "Kill line, to tags or end of line."
  21931. (interactive)
  21932. (cond
  21933. ((or (not org-special-ctrl-k)
  21934. (bolp)
  21935. (not (org-at-heading-p)))
  21936. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21937. org-ctrl-k-protect-subtree
  21938. (or (eq org-ctrl-k-protect-subtree 'error)
  21939. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21940. (user-error "C-k aborted as it would kill a hidden subtree"))
  21941. (call-interactively
  21942. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21943. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21944. (kill-region (point) (match-beginning 1))
  21945. (org-set-tags nil t))
  21946. (t (kill-region (point) (point-at-eol)))))
  21947. (define-key org-mode-map "\C-k" 'org-kill-line)
  21948. (defun org-yank (&optional arg)
  21949. "Yank. If the kill is a subtree, treat it specially.
  21950. This command will look at the current kill and check if is a single
  21951. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21952. cursor is at the beginning of a line or after the stars of a currently
  21953. empty headline, then the yank is handled specially. How exactly depends
  21954. on the value of the following variables.
  21955. `org-yank-folded-subtrees'
  21956. By default, this variable is non-nil, which results in
  21957. subtree(s) being folded after insertion, except if doing so
  21958. would swallow text after the yanked text.
  21959. `org-yank-adjusted-subtrees'
  21960. When non-nil (the default value is nil), the subtree will be
  21961. promoted or demoted in order to fit into the local outline tree
  21962. structure, which means that the level will be adjusted so that it
  21963. becomes the smaller one of the two *visible* surrounding headings.
  21964. Any prefix to this command will cause `yank' to be called directly with
  21965. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21966. will just
  21967. plainly yank the text as it is.
  21968. \[1] The test checks if the first non-white line is a heading
  21969. and if there are no other headings with fewer stars."
  21970. (interactive "P")
  21971. (org-yank-generic 'yank arg))
  21972. (defun org-yank-generic (command arg)
  21973. "Perform some yank-like command.
  21974. This function implements the behavior described in the `org-yank'
  21975. documentation. However, it has been generalized to work for any
  21976. interactive command with similar behavior."
  21977. ;; pretend to be command COMMAND
  21978. (setq this-command command)
  21979. (if arg
  21980. (call-interactively command)
  21981. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21982. (and (org-kill-is-subtree-p)
  21983. (or (bolp)
  21984. (and (looking-at "[ \t]*$")
  21985. (string-match
  21986. "\\`\\*+\\'"
  21987. (buffer-substring (point-at-bol) (point)))))))
  21988. swallowp)
  21989. (cond
  21990. ((and subtreep org-yank-folded-subtrees)
  21991. (let ((beg (point))
  21992. end)
  21993. (if (and subtreep org-yank-adjusted-subtrees)
  21994. (org-paste-subtree nil nil 'for-yank)
  21995. (call-interactively command))
  21996. (setq end (point))
  21997. (goto-char beg)
  21998. (when (and (bolp) subtreep
  21999. (not (setq swallowp
  22000. (org-yank-folding-would-swallow-text beg end))))
  22001. (org-with-limited-levels
  22002. (or (looking-at org-outline-regexp)
  22003. (re-search-forward org-outline-regexp-bol end t))
  22004. (while (and (< (point) end) (looking-at org-outline-regexp))
  22005. (outline-hide-subtree)
  22006. (org-cycle-show-empty-lines 'folded)
  22007. (condition-case nil
  22008. (outline-forward-same-level 1)
  22009. (error (goto-char end))))))
  22010. (when swallowp
  22011. (message
  22012. "Inserted text not folded because that would swallow text"))
  22013. (goto-char end)
  22014. (skip-chars-forward " \t\n\r")
  22015. (beginning-of-line 1)
  22016. (push-mark beg 'nomsg)))
  22017. ((and subtreep org-yank-adjusted-subtrees)
  22018. (let ((beg (point-at-bol)))
  22019. (org-paste-subtree nil nil 'for-yank)
  22020. (push-mark beg 'nomsg)))
  22021. (t
  22022. (call-interactively command))))))
  22023. (defun org-yank-folding-would-swallow-text (beg end)
  22024. "Would hide-subtree at BEG swallow any text after END?"
  22025. (let (level)
  22026. (org-with-limited-levels
  22027. (save-excursion
  22028. (goto-char beg)
  22029. (when (or (looking-at org-outline-regexp)
  22030. (re-search-forward org-outline-regexp-bol end t))
  22031. (setq level (org-outline-level)))
  22032. (goto-char end)
  22033. (skip-chars-forward " \t\r\n\v\f")
  22034. (not (or (eobp)
  22035. (and (bolp) (looking-at-p org-outline-regexp)
  22036. (<= (org-outline-level) level))))))))
  22037. (define-key org-mode-map "\C-y" 'org-yank)
  22038. (defun org-truely-invisible-p ()
  22039. "Check if point is at a character currently not visible.
  22040. This version does not only check the character property, but also
  22041. `visible-mode'."
  22042. ;; Early versions of noutline don't have `outline-invisible-p'.
  22043. (unless (bound-and-true-p visible-mode)
  22044. (outline-invisible-p)))
  22045. (defun org-invisible-p2 ()
  22046. "Check if point is at a character currently not visible."
  22047. (save-excursion
  22048. (when (and (eolp) (not (bobp))) (backward-char 1))
  22049. ;; Early versions of noutline don't have `outline-invisible-p'.
  22050. (outline-invisible-p)))
  22051. (defun org-back-to-heading (&optional invisible-ok)
  22052. "Call `outline-back-to-heading', but provide a better error message."
  22053. (condition-case nil
  22054. (outline-back-to-heading invisible-ok)
  22055. (error (error "Before first headline at position %d in buffer %s"
  22056. (point) (current-buffer)))))
  22057. (defun org-before-first-heading-p ()
  22058. "Before first heading?"
  22059. (save-excursion
  22060. (end-of-line)
  22061. (null (re-search-backward org-outline-regexp-bol nil t))))
  22062. (defun org-at-heading-p (&optional ignored)
  22063. (outline-on-heading-p t))
  22064. (defun org-in-commented-heading-p (&optional no-inheritance)
  22065. "Non-nil if point is under a commented heading.
  22066. This function also checks ancestors of the current headline,
  22067. unless optional argument NO-INHERITANCE is non-nil."
  22068. (cond
  22069. ((org-before-first-heading-p) nil)
  22070. ((let ((headline (nth 4 (org-heading-components))))
  22071. (and headline
  22072. (let ((case-fold-search nil))
  22073. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22074. headline)))))
  22075. (no-inheritance nil)
  22076. (t
  22077. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22078. (defun org-at-comment-p nil
  22079. "Is cursor in a commented line?"
  22080. (save-excursion
  22081. (save-match-data
  22082. (beginning-of-line)
  22083. (looking-at "^[ \t]*# "))))
  22084. (defun org-at-drawer-p nil
  22085. "Is cursor at a drawer keyword?"
  22086. (save-excursion
  22087. (move-beginning-of-line 1)
  22088. (looking-at org-drawer-regexp)))
  22089. (defun org-at-block-p nil
  22090. "Is cursor at a block keyword?"
  22091. (save-excursion
  22092. (move-beginning-of-line 1)
  22093. (looking-at org-block-regexp)))
  22094. (defun org-point-at-end-of-empty-headline ()
  22095. "If point is at the end of an empty headline, return t, else nil.
  22096. If the heading only contains a TODO keyword, it is still still considered
  22097. empty."
  22098. (and (looking-at "[ \t]*$")
  22099. (when org-todo-line-regexp
  22100. (save-excursion
  22101. (beginning-of-line 1)
  22102. (let ((case-fold-search nil))
  22103. (looking-at org-todo-line-regexp)
  22104. (string= (match-string 3) ""))))))
  22105. (defun org-at-heading-or-item-p ()
  22106. (or (org-at-heading-p) (org-at-item-p)))
  22107. (defun org-at-target-p ()
  22108. (or (org-in-regexp org-radio-target-regexp)
  22109. (org-in-regexp org-target-regexp)))
  22110. ;; Compatibility alias with Org versions < 7.8.03
  22111. (defalias 'org-on-target-p 'org-at-target-p)
  22112. (defun org-up-heading-all (arg)
  22113. "Move to the heading line of which the present line is a subheading.
  22114. This function considers both visible and invisible heading lines.
  22115. With argument, move up ARG levels."
  22116. (outline-up-heading arg t))
  22117. (defun org-up-heading-safe ()
  22118. "Move to the heading line of which the present line is a subheading.
  22119. This version will not throw an error. It will return the level of the
  22120. headline found, or nil if no higher level is found.
  22121. Also, this function will be a lot faster than `outline-up-heading',
  22122. because it relies on stars being the outline starters. This can really
  22123. make a significant difference in outlines with very many siblings."
  22124. (when (ignore-errors (org-back-to-heading t))
  22125. (let ((level-up (1- (funcall outline-level))))
  22126. (and (> level-up 0)
  22127. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22128. (funcall outline-level)))))
  22129. (defun org-first-sibling-p ()
  22130. "Is this heading the first child of its parents?"
  22131. (interactive)
  22132. (let ((re org-outline-regexp-bol)
  22133. level l)
  22134. (unless (org-at-heading-p t)
  22135. (user-error "Not at a heading"))
  22136. (setq level (funcall outline-level))
  22137. (save-excursion
  22138. (if (not (re-search-backward re nil t))
  22139. t
  22140. (setq l (funcall outline-level))
  22141. (< l level)))))
  22142. (defun org-goto-sibling (&optional previous)
  22143. "Goto the next sibling, even if it is invisible.
  22144. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22145. when a sibling was found. When none is found, return nil and don't
  22146. move point."
  22147. (let ((fun (if previous 're-search-backward 're-search-forward))
  22148. (pos (point))
  22149. (re org-outline-regexp-bol)
  22150. level l)
  22151. (when (ignore-errors (org-back-to-heading t))
  22152. (setq level (funcall outline-level))
  22153. (catch 'exit
  22154. (or previous (forward-char 1))
  22155. (while (funcall fun re nil t)
  22156. (setq l (funcall outline-level))
  22157. (when (< l level) (goto-char pos) (throw 'exit nil))
  22158. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22159. (goto-char pos)
  22160. nil))))
  22161. (defun org-show-siblings ()
  22162. "Show all siblings of the current headline."
  22163. (save-excursion
  22164. (while (org-goto-sibling) (org-flag-heading nil)))
  22165. (save-excursion
  22166. (while (org-goto-sibling 'previous)
  22167. (org-flag-heading nil))))
  22168. (defun org-goto-first-child ()
  22169. "Goto the first child, even if it is invisible.
  22170. Return t when a child was found. Otherwise don't move point and
  22171. return nil."
  22172. (let (level (pos (point)) (re org-outline-regexp-bol))
  22173. (when (ignore-errors (org-back-to-heading t))
  22174. (setq level (outline-level))
  22175. (forward-char 1)
  22176. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22177. (progn (goto-char (match-beginning 0)) t)
  22178. (goto-char pos) nil))))
  22179. (defun org-show-hidden-entry ()
  22180. "Show an entry where even the heading is hidden."
  22181. (save-excursion
  22182. (org-show-entry)))
  22183. (defun org-flag-heading (flag &optional entry)
  22184. "Flag the current heading. FLAG non-nil means make invisible.
  22185. When ENTRY is non-nil, show the entire entry."
  22186. (save-excursion
  22187. (org-back-to-heading t)
  22188. ;; Check if we should show the entire entry
  22189. (if entry
  22190. (progn
  22191. (org-show-entry)
  22192. (save-excursion
  22193. (and (outline-next-heading)
  22194. (org-flag-heading nil))))
  22195. (outline-flag-region (max (point-min) (1- (point)))
  22196. (save-excursion (outline-end-of-heading) (point))
  22197. flag))))
  22198. (defun org-get-next-sibling ()
  22199. "Move to next heading of the same level, and return point.
  22200. If there is no such heading, return nil.
  22201. This is like outline-next-sibling, but invisible headings are ok."
  22202. (let ((level (funcall outline-level)))
  22203. (outline-next-heading)
  22204. (while (and (not (eobp)) (> (funcall outline-level) level))
  22205. (outline-next-heading))
  22206. (unless (or (eobp) (< (funcall outline-level) level))
  22207. (point))))
  22208. (defun org-get-last-sibling ()
  22209. "Move to previous heading of the same level, and return point.
  22210. If there is no such heading, return nil."
  22211. (let ((opoint (point))
  22212. (level (funcall outline-level)))
  22213. (outline-previous-heading)
  22214. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22215. (while (and (> (funcall outline-level) level)
  22216. (not (bobp)))
  22217. (outline-previous-heading))
  22218. (unless (< (funcall outline-level) level)
  22219. (point)))))
  22220. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22221. "Goto to the end of a subtree."
  22222. ;; This contains an exact copy of the original function, but it uses
  22223. ;; `org-back-to-heading', to make it work also in invisible
  22224. ;; trees. And is uses an invisible-ok argument.
  22225. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22226. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22227. ;; with many children and grandchildren etc, this can be much faster
  22228. ;; than the outline version.
  22229. (org-back-to-heading invisible-ok)
  22230. (let ((first t)
  22231. (level (funcall outline-level)))
  22232. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22233. ;; A true heading (not a plain list item), in Org
  22234. ;; This means we can easily find the end by looking
  22235. ;; only for the right number of stars. Using a regexp to do
  22236. ;; this is so much faster than using a Lisp loop.
  22237. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22238. (forward-char 1)
  22239. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22240. ;; something else, do it the slow way
  22241. (while (and (not (eobp))
  22242. (or first (> (funcall outline-level) level)))
  22243. (setq first nil)
  22244. (outline-next-heading)))
  22245. (unless to-heading
  22246. (when (memq (preceding-char) '(?\n ?\^M))
  22247. ;; Go to end of line before heading
  22248. (forward-char -1)
  22249. (when (memq (preceding-char) '(?\n ?\^M))
  22250. ;; leave blank line before heading
  22251. (forward-char -1)))))
  22252. (point))
  22253. (defun org-end-of-meta-data (&optional full)
  22254. "Skip planning line and properties drawer in current entry.
  22255. When optional argument FULL is non-nil, also skip empty lines,
  22256. clocking lines and regular drawers at the beginning of the
  22257. entry."
  22258. (org-back-to-heading t)
  22259. (forward-line)
  22260. (when (looking-at-p org-planning-line-re) (forward-line))
  22261. (when (looking-at org-property-drawer-re)
  22262. (goto-char (match-end 0))
  22263. (forward-line))
  22264. (when (and full (not (org-at-heading-p)))
  22265. (catch 'exit
  22266. (let ((end (save-excursion (outline-next-heading) (point)))
  22267. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22268. (while (not (eobp))
  22269. (cond ((looking-at-p org-drawer-regexp)
  22270. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22271. (forward-line)
  22272. (throw 'exit t)))
  22273. ((looking-at-p re) (forward-line))
  22274. (t (throw 'exit t))))))))
  22275. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22276. "Move forward to the ARG'th subheading at same level as this one.
  22277. Stop at the first and last subheadings of a superior heading.
  22278. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22279. non-nil it will also look at invisible ones."
  22280. (interactive "p")
  22281. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22282. (if (and arg (< arg 0))
  22283. (goto-char (point-min))
  22284. (outline-next-heading))
  22285. (org-at-heading-p)
  22286. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22287. (f (if (and arg (< arg 0))
  22288. 're-search-backward
  22289. 're-search-forward))
  22290. (count (if arg (abs arg) 1))
  22291. (result (point)))
  22292. (while (and (prog1 (> count 0)
  22293. (forward-char (if (and arg (< arg 0)) -1 1)))
  22294. (funcall f org-outline-regexp-bol nil 'move))
  22295. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22296. (cond ((< l level) (setq count 0))
  22297. ((and (= l level)
  22298. (or invisible-ok
  22299. (progn
  22300. (goto-char (line-beginning-position))
  22301. (not (outline-invisible-p)))))
  22302. (setq count (1- count))
  22303. (when (eq l level)
  22304. (setq result (point)))))))
  22305. (goto-char result))
  22306. (beginning-of-line 1)))
  22307. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22308. "Move backward to the ARG'th subheading at same level as this one.
  22309. Stop at the first and last subheadings of a superior heading."
  22310. (interactive "p")
  22311. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22312. (defun org-next-visible-heading (arg)
  22313. "Move to the next visible heading.
  22314. This function wraps `outline-next-visible-heading' with
  22315. `org-with-limited-levels' in order to skip over inline tasks and
  22316. respect customization of `org-odd-levels-only'."
  22317. (interactive "p")
  22318. (org-with-limited-levels
  22319. (outline-next-visible-heading arg)))
  22320. (defun org-previous-visible-heading (arg)
  22321. "Move to the previous visible heading.
  22322. This function wraps `outline-previous-visible-heading' with
  22323. `org-with-limited-levels' in order to skip over inline tasks and
  22324. respect customization of `org-odd-levels-only'."
  22325. (interactive "p")
  22326. (org-with-limited-levels
  22327. (outline-previous-visible-heading arg)))
  22328. (defun org-next-block (arg &optional backward block-regexp)
  22329. "Jump to the next block.
  22330. With a prefix argument ARG, jump forward ARG many blocks.
  22331. When BACKWARD is non-nil, jump to the previous block.
  22332. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22333. Match data is set according to this regexp when the function
  22334. returns.
  22335. Return point at beginning of the opening line of found block.
  22336. Throw an error if no block is found."
  22337. (interactive "p")
  22338. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22339. (case-fold-search t)
  22340. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22341. (count (or arg 1))
  22342. (origin (point))
  22343. last-element)
  22344. (if backward (beginning-of-line) (end-of-line))
  22345. (while (and (> count 0) (funcall search-fn re nil t))
  22346. (let ((element (save-excursion
  22347. (goto-char (match-beginning 0))
  22348. (save-match-data (org-element-at-point)))))
  22349. (when (and (memq (org-element-type element)
  22350. '(center-block comment-block dynamic-block
  22351. example-block export-block quote-block
  22352. special-block src-block verse-block))
  22353. (<= (match-beginning 0)
  22354. (org-element-property :post-affiliated element)))
  22355. (setq last-element element)
  22356. (cl-decf count))))
  22357. (if (= count 0)
  22358. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22359. (save-match-data (org-show-context)))
  22360. (goto-char origin)
  22361. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22362. (defun org-previous-block (arg &optional block-regexp)
  22363. "Jump to the previous block.
  22364. With a prefix argument ARG, jump backward ARG many source blocks.
  22365. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22366. (interactive "p")
  22367. (org-next-block arg t block-regexp))
  22368. (defun org-forward-paragraph ()
  22369. "Move forward to beginning of next paragraph or equivalent.
  22370. The function moves point to the beginning of the next visible
  22371. structural element, which can be a paragraph, a table, a list
  22372. item, etc. It also provides some special moves for convenience:
  22373. - On an affiliated keyword, jump to the beginning of the
  22374. relative element.
  22375. - On an item or a footnote definition, move to the second
  22376. element inside, if any.
  22377. - On a table or a property drawer, jump after it.
  22378. - On a verse or source block, stop after blank lines."
  22379. (interactive)
  22380. (when (eobp) (user-error "Cannot move further down"))
  22381. (let* ((deactivate-mark nil)
  22382. (element (org-element-at-point))
  22383. (type (org-element-type element))
  22384. (post-affiliated (org-element-property :post-affiliated element))
  22385. (contents-begin (org-element-property :contents-begin element))
  22386. (contents-end (org-element-property :contents-end element))
  22387. (end (let ((end (org-element-property :end element)) (parent element))
  22388. (while (and (setq parent (org-element-property :parent parent))
  22389. (= (org-element-property :contents-end parent) end))
  22390. (setq end (org-element-property :end parent)))
  22391. end)))
  22392. (cond ((not element)
  22393. (skip-chars-forward " \r\t\n")
  22394. (or (eobp) (beginning-of-line)))
  22395. ;; On affiliated keywords, move to element's beginning.
  22396. ((< (point) post-affiliated)
  22397. (goto-char post-affiliated))
  22398. ;; At a table row, move to the end of the table. Similarly,
  22399. ;; at a node property, move to the end of the property
  22400. ;; drawer.
  22401. ((memq type '(node-property table-row))
  22402. (goto-char (org-element-property
  22403. :end (org-element-property :parent element))))
  22404. ((memq type '(property-drawer table)) (goto-char end))
  22405. ;; Consider blank lines as separators in verse and source
  22406. ;; blocks to ease editing.
  22407. ((memq type '(src-block verse-block))
  22408. (when (eq type 'src-block)
  22409. (setq contents-end
  22410. (save-excursion (goto-char end)
  22411. (skip-chars-backward " \r\t\n")
  22412. (line-beginning-position))))
  22413. (beginning-of-line)
  22414. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22415. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22416. (goto-char end)
  22417. (skip-chars-forward " \r\t\n")
  22418. (if (= (point) contents-end) (goto-char end)
  22419. (beginning-of-line))))
  22420. ;; With no contents, just skip element.
  22421. ((not contents-begin) (goto-char end))
  22422. ;; If contents are invisible, skip the element altogether.
  22423. ((outline-invisible-p (line-end-position))
  22424. (cl-case type
  22425. (headline
  22426. (org-with-limited-levels (outline-next-visible-heading 1)))
  22427. ;; At a plain list, make sure we move to the next item
  22428. ;; instead of skipping the whole list.
  22429. (plain-list (forward-char)
  22430. (org-forward-paragraph))
  22431. (otherwise (goto-char end))))
  22432. ((>= (point) contents-end) (goto-char end))
  22433. ((>= (point) contents-begin)
  22434. ;; This can only happen on paragraphs and plain lists.
  22435. (cl-case type
  22436. (paragraph (goto-char end))
  22437. ;; At a plain list, try to move to second element in
  22438. ;; first item, if possible.
  22439. (plain-list (end-of-line)
  22440. (org-forward-paragraph))))
  22441. ;; When contents start on the middle of a line (e.g. in
  22442. ;; items and footnote definitions), try to reach first
  22443. ;; element starting after current line.
  22444. ((> (line-end-position) contents-begin)
  22445. (end-of-line)
  22446. (org-forward-paragraph))
  22447. (t (goto-char contents-begin)))))
  22448. (defun org-backward-paragraph ()
  22449. "Move backward to start of previous paragraph or equivalent.
  22450. The function moves point to the beginning of the current
  22451. structural element, which can be a paragraph, a table, a list
  22452. item, etc., or to the beginning of the previous visible one if
  22453. point is already there. It also provides some special moves for
  22454. convenience:
  22455. - On an affiliated keyword, jump to the first one.
  22456. - On a table or a property drawer, move to its beginning.
  22457. - On a verse or source block, stop before blank lines."
  22458. (interactive)
  22459. (when (bobp) (user-error "Cannot move further up"))
  22460. (let* ((deactivate-mark nil)
  22461. (element (org-element-at-point))
  22462. (type (org-element-type element))
  22463. (contents-begin (org-element-property :contents-begin element))
  22464. (contents-end (org-element-property :contents-end element))
  22465. (post-affiliated (org-element-property :post-affiliated element))
  22466. (begin (org-element-property :begin element)))
  22467. (cond
  22468. ((not element) (goto-char (point-min)))
  22469. ((= (point) begin)
  22470. (backward-char)
  22471. (org-backward-paragraph))
  22472. ((<= (point) post-affiliated) (goto-char begin))
  22473. ((memq type '(node-property table-row))
  22474. (goto-char (org-element-property
  22475. :post-affiliated (org-element-property :parent element))))
  22476. ((memq type '(property-drawer table)) (goto-char begin))
  22477. ((memq type '(src-block verse-block))
  22478. (when (eq type 'src-block)
  22479. (setq contents-begin
  22480. (save-excursion (goto-char begin) (forward-line) (point))))
  22481. (if (= (point) contents-begin) (goto-char post-affiliated)
  22482. ;; Inside a verse block, see blank lines as paragraph
  22483. ;; separators.
  22484. (let ((origin (point)))
  22485. (skip-chars-backward " \r\t\n" contents-begin)
  22486. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22487. (skip-chars-forward " \r\t\n" origin)
  22488. (if (= (point) origin) (goto-char contents-begin)
  22489. (beginning-of-line))))))
  22490. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22491. ((eq type 'paragraph)
  22492. (goto-char contents-begin)
  22493. ;; When at first paragraph in an item or a footnote definition,
  22494. ;; move directly to beginning of line.
  22495. (let ((parent-contents
  22496. (org-element-property
  22497. :contents-begin (org-element-property :parent element))))
  22498. (when (and parent-contents (= parent-contents contents-begin))
  22499. (beginning-of-line))))
  22500. ;; At the end of a greater element, move to the beginning of the
  22501. ;; last element within.
  22502. ((>= (point) contents-end)
  22503. (goto-char (1- contents-end))
  22504. (org-backward-paragraph))
  22505. (t (goto-char (or post-affiliated begin))))
  22506. ;; Ensure we never leave point invisible.
  22507. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22508. (defun org-forward-element ()
  22509. "Move forward by one element.
  22510. Move to the next element at the same level, when possible."
  22511. (interactive)
  22512. (cond ((eobp) (user-error "Cannot move further down"))
  22513. ((org-with-limited-levels (org-at-heading-p))
  22514. (let ((origin (point)))
  22515. (goto-char (org-end-of-subtree nil t))
  22516. (unless (org-with-limited-levels (org-at-heading-p))
  22517. (goto-char origin)
  22518. (user-error "Cannot move further down"))))
  22519. (t
  22520. (let* ((elem (org-element-at-point))
  22521. (end (org-element-property :end elem))
  22522. (parent (org-element-property :parent elem)))
  22523. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22524. (goto-char (org-element-property :end parent)))
  22525. ((integer-or-marker-p end) (goto-char end))
  22526. (t (message "No element at point")))))))
  22527. (defun org-backward-element ()
  22528. "Move backward by one element.
  22529. Move to the previous element at the same level, when possible."
  22530. (interactive)
  22531. (cond ((bobp) (user-error "Cannot move further up"))
  22532. ((org-with-limited-levels (org-at-heading-p))
  22533. ;; At a headline, move to the previous one, if any, or stay
  22534. ;; here.
  22535. (let ((origin (point)))
  22536. (org-with-limited-levels (org-backward-heading-same-level 1))
  22537. ;; When current headline has no sibling above, move to its
  22538. ;; parent.
  22539. (when (= (point) origin)
  22540. (or (org-with-limited-levels (org-up-heading-safe))
  22541. (progn (goto-char origin)
  22542. (user-error "Cannot move further up"))))))
  22543. (t
  22544. (let* ((elem (org-element-at-point))
  22545. (beg (org-element-property :begin elem)))
  22546. (cond
  22547. ;; Move to beginning of current element if point isn't
  22548. ;; there already.
  22549. ((null beg) (message "No element at point"))
  22550. ((/= (point) beg) (goto-char beg))
  22551. (t (goto-char beg)
  22552. (skip-chars-backward " \r\t\n")
  22553. (unless (bobp)
  22554. (let ((prev (org-element-at-point)))
  22555. (goto-char (org-element-property :begin prev))
  22556. (while (and (setq prev (org-element-property :parent prev))
  22557. (<= (org-element-property :end prev) beg))
  22558. (goto-char (org-element-property :begin prev)))))))))))
  22559. (defun org-up-element ()
  22560. "Move to upper element."
  22561. (interactive)
  22562. (if (org-with-limited-levels (org-at-heading-p))
  22563. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22564. (let* ((elem (org-element-at-point))
  22565. (parent (org-element-property :parent elem)))
  22566. (if parent (goto-char (org-element-property :begin parent))
  22567. (if (org-with-limited-levels (org-before-first-heading-p))
  22568. (user-error "No surrounding element")
  22569. (org-with-limited-levels (org-back-to-heading)))))))
  22570. (defvar org-element-greater-elements)
  22571. (defun org-down-element ()
  22572. "Move to inner element."
  22573. (interactive)
  22574. (let ((element (org-element-at-point)))
  22575. (cond
  22576. ((memq (org-element-type element) '(plain-list table))
  22577. (goto-char (org-element-property :contents-begin element))
  22578. (forward-char))
  22579. ((memq (org-element-type element) org-element-greater-elements)
  22580. ;; If contents are hidden, first disclose them.
  22581. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22582. (goto-char (or (org-element-property :contents-begin element)
  22583. (user-error "No content for this element"))))
  22584. (t (user-error "No inner element")))))
  22585. (defun org-drag-element-backward ()
  22586. "Move backward element at point."
  22587. (interactive)
  22588. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22589. (let* ((elem (org-element-at-point))
  22590. (prev-elem
  22591. (save-excursion
  22592. (goto-char (org-element-property :begin elem))
  22593. (skip-chars-backward " \r\t\n")
  22594. (unless (bobp)
  22595. (let* ((beg (org-element-property :begin elem))
  22596. (prev (org-element-at-point))
  22597. (up prev))
  22598. (while (and (setq up (org-element-property :parent up))
  22599. (<= (org-element-property :end up) beg))
  22600. (setq prev up))
  22601. prev)))))
  22602. ;; Error out if no previous element or previous element is
  22603. ;; a parent of the current one.
  22604. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22605. (user-error "Cannot drag element backward")
  22606. (let ((pos (point)))
  22607. (org-element-swap-A-B prev-elem elem)
  22608. (goto-char (+ (org-element-property :begin prev-elem)
  22609. (- pos (org-element-property :begin elem)))))))))
  22610. (defun org-drag-element-forward ()
  22611. "Move forward element at point."
  22612. (interactive)
  22613. (let* ((pos (point))
  22614. (elem (org-element-at-point)))
  22615. (when (= (point-max) (org-element-property :end elem))
  22616. (user-error "Cannot drag element forward"))
  22617. (goto-char (org-element-property :end elem))
  22618. (let ((next-elem (org-element-at-point)))
  22619. (when (or (org-element-nested-p elem next-elem)
  22620. (and (eq (org-element-type next-elem) 'headline)
  22621. (not (eq (org-element-type elem) 'headline))))
  22622. (goto-char pos)
  22623. (user-error "Cannot drag element forward"))
  22624. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22625. ;; body's length (without final blanks) and by the length of
  22626. ;; blanks between ELEM and NEXT-ELEM.
  22627. (let ((size-next (- (save-excursion
  22628. (goto-char (org-element-property :end next-elem))
  22629. (skip-chars-backward " \r\t\n")
  22630. (forward-line)
  22631. ;; Small correction if buffer doesn't end
  22632. ;; with a newline character.
  22633. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22634. (org-element-property :begin next-elem)))
  22635. (size-blank (- (org-element-property :end elem)
  22636. (save-excursion
  22637. (goto-char (org-element-property :end elem))
  22638. (skip-chars-backward " \r\t\n")
  22639. (forward-line)
  22640. (point)))))
  22641. (org-element-swap-A-B elem next-elem)
  22642. (goto-char (+ pos size-next size-blank))))))
  22643. (defun org-drag-line-forward (arg)
  22644. "Drag the line at point ARG lines forward."
  22645. (interactive "p")
  22646. (dotimes (_ (abs arg))
  22647. (let ((c (current-column)))
  22648. (if (< 0 arg)
  22649. (progn
  22650. (beginning-of-line 2)
  22651. (transpose-lines 1)
  22652. (beginning-of-line 0))
  22653. (transpose-lines 1)
  22654. (beginning-of-line -1))
  22655. (org-move-to-column c))))
  22656. (defun org-drag-line-backward (arg)
  22657. "Drag the line at point ARG lines backward."
  22658. (interactive "p")
  22659. (org-drag-line-forward (- arg)))
  22660. (defun org-mark-element ()
  22661. "Put point at beginning of this element, mark at end.
  22662. Interactively, if this command is repeated or (in Transient Mark
  22663. mode) if the mark is active, it marks the next element after the
  22664. ones already marked."
  22665. (interactive)
  22666. (let (deactivate-mark)
  22667. (if (and (called-interactively-p 'any)
  22668. (or (and (eq last-command this-command) (mark t))
  22669. (and transient-mark-mode mark-active)))
  22670. (set-mark
  22671. (save-excursion
  22672. (goto-char (mark))
  22673. (goto-char (org-element-property :end (org-element-at-point)))))
  22674. (let ((element (org-element-at-point)))
  22675. (end-of-line)
  22676. (push-mark (org-element-property :end element) t t)
  22677. (goto-char (org-element-property :begin element))))))
  22678. (defun org-narrow-to-element ()
  22679. "Narrow buffer to current element."
  22680. (interactive)
  22681. (let ((elem (org-element-at-point)))
  22682. (cond
  22683. ((eq (car elem) 'headline)
  22684. (narrow-to-region
  22685. (org-element-property :begin elem)
  22686. (org-element-property :end elem)))
  22687. ((memq (car elem) org-element-greater-elements)
  22688. (narrow-to-region
  22689. (org-element-property :contents-begin elem)
  22690. (org-element-property :contents-end elem)))
  22691. (t
  22692. (narrow-to-region
  22693. (org-element-property :begin elem)
  22694. (org-element-property :end elem))))))
  22695. (defun org-transpose-element ()
  22696. "Transpose current and previous elements, keeping blank lines between.
  22697. Point is moved after both elements."
  22698. (interactive)
  22699. (org-skip-whitespace)
  22700. (let ((end (org-element-property :end (org-element-at-point))))
  22701. (org-drag-element-backward)
  22702. (goto-char end)))
  22703. (defun org-unindent-buffer ()
  22704. "Un-indent the visible part of the buffer.
  22705. Relative indentation (between items, inside blocks, etc.) isn't
  22706. modified."
  22707. (interactive)
  22708. (unless (eq major-mode 'org-mode)
  22709. (user-error "Cannot un-indent a buffer not in Org mode"))
  22710. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22711. (unindent-tree
  22712. (lambda (contents)
  22713. (dolist (element (reverse contents))
  22714. (if (memq (org-element-type element) '(headline section))
  22715. (funcall unindent-tree (org-element-contents element))
  22716. (save-excursion
  22717. (save-restriction
  22718. (narrow-to-region
  22719. (org-element-property :begin element)
  22720. (org-element-property :end element))
  22721. (org-do-remove-indentation))))))))
  22722. (funcall unindent-tree (org-element-contents parse-tree))))
  22723. (defun org-show-children (&optional level)
  22724. "Show all direct subheadings of this heading.
  22725. Prefix arg LEVEL is how many levels below the current level
  22726. should be shown. Default is enough to cause the following
  22727. heading to appear."
  22728. (interactive "p")
  22729. ;; If `orgstruct-mode' is active, use the slower version.
  22730. (if orgstruct-mode (call-interactively #'outline-show-children)
  22731. (save-excursion
  22732. (org-back-to-heading t)
  22733. (let* ((current-level (funcall outline-level))
  22734. (max-level (org-get-valid-level
  22735. current-level
  22736. (if level (prefix-numeric-value level) 1)))
  22737. (end (save-excursion (org-end-of-subtree t t)))
  22738. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22739. (past-first-child nil)
  22740. ;; Make sure to skip inlinetasks.
  22741. (re (format regexp-fmt
  22742. current-level
  22743. (cond
  22744. ((not (featurep 'org-inlinetask)) "")
  22745. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22746. 3))
  22747. (t (1- org-inlinetask-min-level))))))
  22748. ;; Display parent heading.
  22749. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22750. (forward-line)
  22751. ;; Display children. First child may be deeper than expected
  22752. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22753. ;; MAX-LEVEL accordingly.
  22754. (while (re-search-forward re end t)
  22755. (unless past-first-child
  22756. (setq re (format regexp-fmt
  22757. current-level
  22758. (max (funcall outline-level) max-level)))
  22759. (setq past-first-child t))
  22760. (outline-flag-region
  22761. (line-end-position 0) (line-end-position) nil))))))
  22762. (defun org-show-subtree ()
  22763. "Show everything after this heading at deeper levels."
  22764. (interactive)
  22765. (outline-flag-region
  22766. (point)
  22767. (save-excursion
  22768. (org-end-of-subtree t t))
  22769. nil))
  22770. (defun org-show-entry ()
  22771. "Show the body directly following this heading.
  22772. Show the heading too, if it is currently invisible."
  22773. (interactive)
  22774. (save-excursion
  22775. (ignore-errors
  22776. (org-back-to-heading t)
  22777. (outline-flag-region
  22778. (max (point-min) (1- (point)))
  22779. (save-excursion
  22780. (if (re-search-forward
  22781. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22782. (match-beginning 1)
  22783. (point-max)))
  22784. nil)
  22785. (org-cycle-hide-drawers 'children))))
  22786. (defun org-make-options-regexp (kwds &optional extra)
  22787. "Make a regular expression for keyword lines.
  22788. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22789. when non-nil, is a regexp matching keywords names."
  22790. (concat "^[ \t]*#\\+\\("
  22791. (regexp-opt kwds)
  22792. (and extra (concat (and kwds "\\|") extra))
  22793. "\\):[ \t]*\\(.*\\)"))
  22794. ;;;; Integration with and fixes for other packages
  22795. ;;; Imenu support
  22796. (defvar-local org-imenu-markers nil
  22797. "All markers currently used by Imenu.")
  22798. (defun org-imenu-new-marker (&optional pos)
  22799. "Return a new marker for use by Imenu, and remember the marker."
  22800. (let ((m (make-marker)))
  22801. (move-marker m (or pos (point)))
  22802. (push m org-imenu-markers)
  22803. m))
  22804. (defun org-imenu-get-tree ()
  22805. "Produce the index for Imenu."
  22806. (dolist (x org-imenu-markers) (move-marker x nil))
  22807. (setq org-imenu-markers nil)
  22808. (let* ((case-fold-search nil)
  22809. (n org-imenu-depth)
  22810. (re (concat "^" (org-get-limited-outline-regexp)))
  22811. (subs (make-vector (1+ n) nil))
  22812. (last-level 0)
  22813. m level head0 head)
  22814. (org-with-wide-buffer
  22815. (goto-char (point-max))
  22816. (while (re-search-backward re nil t)
  22817. (setq level (org-reduced-level (funcall outline-level)))
  22818. (when (and (<= level n)
  22819. (looking-at org-complex-heading-regexp)
  22820. (setq head0 (match-string-no-properties 4)))
  22821. (setq head (org-link-display-format head0)
  22822. m (org-imenu-new-marker))
  22823. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22824. (if (>= level last-level)
  22825. (push (cons head m) (aref subs level))
  22826. (push (cons head (aref subs (1+ level))) (aref subs level))
  22827. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22828. (setq last-level level))))
  22829. (aref subs 1)))
  22830. (eval-after-load "imenu"
  22831. '(progn
  22832. (add-hook 'imenu-after-jump-hook
  22833. (lambda ()
  22834. (when (derived-mode-p 'org-mode)
  22835. (org-show-context 'org-goto))))))
  22836. (defun org-link-display-format (s)
  22837. "Replace links in string S with their description.
  22838. If there is no description, use the link target."
  22839. (save-match-data
  22840. (replace-regexp-in-string
  22841. org-bracket-link-analytic-regexp
  22842. (lambda (m)
  22843. (if (match-end 5) (match-string 5 m)
  22844. (concat (match-string 1 m) (match-string 3 m))))
  22845. s nil t)))
  22846. (defun org-toggle-link-display ()
  22847. "Toggle the literal or descriptive display of links."
  22848. (interactive)
  22849. (if org-descriptive-links
  22850. (progn (org-remove-from-invisibility-spec '(org-link))
  22851. (org-restart-font-lock)
  22852. (setq org-descriptive-links nil))
  22853. (progn (add-to-invisibility-spec '(org-link))
  22854. (org-restart-font-lock)
  22855. (setq org-descriptive-links t))))
  22856. ;; Speedbar support
  22857. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22858. "Overlay marking the agenda restriction line in speedbar.")
  22859. (overlay-put org-speedbar-restriction-lock-overlay
  22860. 'face 'org-agenda-restriction-lock)
  22861. (overlay-put org-speedbar-restriction-lock-overlay
  22862. 'help-echo "Agendas are currently limited to this item.")
  22863. (delete-overlay org-speedbar-restriction-lock-overlay)
  22864. (defun org-speedbar-set-agenda-restriction ()
  22865. "Restrict future agenda commands to the location at point in speedbar.
  22866. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22867. (interactive)
  22868. (require 'org-agenda)
  22869. (let (p m tp np dir txt)
  22870. (cond
  22871. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22872. 'org-imenu t))
  22873. (setq m (get-text-property p 'org-imenu-marker))
  22874. (with-current-buffer (marker-buffer m)
  22875. (goto-char m)
  22876. (org-agenda-set-restriction-lock 'subtree)))
  22877. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22878. 'speedbar-function 'speedbar-find-file))
  22879. (setq tp (previous-single-property-change
  22880. (1+ p) 'speedbar-function)
  22881. np (next-single-property-change
  22882. tp 'speedbar-function)
  22883. dir (speedbar-line-directory)
  22884. txt (buffer-substring-no-properties (or tp (point-min))
  22885. (or np (point-max))))
  22886. (with-current-buffer (find-file-noselect
  22887. (let ((default-directory dir))
  22888. (expand-file-name txt)))
  22889. (unless (derived-mode-p 'org-mode)
  22890. (user-error "Cannot restrict to non-Org mode file"))
  22891. (org-agenda-set-restriction-lock 'file)))
  22892. (t (user-error "Don't know how to restrict Org mode agenda")))
  22893. (move-overlay org-speedbar-restriction-lock-overlay
  22894. (point-at-bol) (point-at-eol))
  22895. (setq current-prefix-arg nil)
  22896. (org-agenda-maybe-redo)))
  22897. (defvar speedbar-file-key-map)
  22898. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22899. (eval-after-load "speedbar"
  22900. '(progn
  22901. (speedbar-add-supported-extension ".org")
  22902. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22903. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22904. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22905. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22906. (add-hook 'speedbar-visiting-tag-hook
  22907. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22908. ;;; Fixes and Hacks for problems with other packages
  22909. (defun org--flyspell-object-check-p (element)
  22910. "Non-nil when Flyspell can check object at point.
  22911. ELEMENT is the element at point."
  22912. (let ((object (save-excursion
  22913. (when (looking-at-p "\\>") (backward-char))
  22914. (org-element-context element))))
  22915. (cl-case (org-element-type object)
  22916. ;; Prevent checks in links due to keybinding conflict with
  22917. ;; Flyspell.
  22918. ((code entity export-snippet inline-babel-call
  22919. inline-src-block line-break latex-fragment link macro
  22920. statistics-cookie target timestamp verbatim)
  22921. nil)
  22922. (footnote-reference
  22923. ;; Only in inline footnotes, within the definition.
  22924. (and (eq (org-element-property :type object) 'inline)
  22925. (< (save-excursion
  22926. (goto-char (org-element-property :begin object))
  22927. (search-forward ":" nil t 2))
  22928. (point))))
  22929. (otherwise t))))
  22930. (defun org-mode-flyspell-verify ()
  22931. "Function used for `flyspell-generic-check-word-predicate'."
  22932. (if (org-at-heading-p)
  22933. ;; At a headline or an inlinetask, check title only. This is
  22934. ;; faster than relying on `org-element-at-point'.
  22935. (and (save-excursion (beginning-of-line)
  22936. (and (let ((case-fold-search t))
  22937. (not (looking-at-p "\\*+ END[ \t]*$")))
  22938. (let ((case-fold-search nil))
  22939. (looking-at org-complex-heading-regexp))))
  22940. (match-beginning 4)
  22941. (>= (point) (match-beginning 4))
  22942. (or (not (match-beginning 5))
  22943. (< (point) (match-beginning 5))))
  22944. (let* ((element (org-element-at-point))
  22945. (post-affiliated (org-element-property :post-affiliated element)))
  22946. (cond
  22947. ;; Ignore checks in all affiliated keywords but captions.
  22948. ((< (point) post-affiliated)
  22949. (and (save-excursion
  22950. (beginning-of-line)
  22951. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22952. (> (point) (match-end 0))
  22953. (org--flyspell-object-check-p element)))
  22954. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22955. ((let ((log (org-log-into-drawer)))
  22956. (and log
  22957. (let ((drawer (org-element-lineage element '(drawer))))
  22958. (and drawer
  22959. (eq (compare-strings
  22960. log nil nil
  22961. (org-element-property :drawer-name drawer) nil nil t)
  22962. t)))))
  22963. nil)
  22964. (t
  22965. (cl-case (org-element-type element)
  22966. ((comment quote-section) t)
  22967. (comment-block
  22968. ;; Allow checks between block markers, not on them.
  22969. (and (> (line-beginning-position) post-affiliated)
  22970. (save-excursion
  22971. (end-of-line)
  22972. (skip-chars-forward " \r\t\n")
  22973. (< (point) (org-element-property :end element)))))
  22974. ;; Arbitrary list of keywords where checks are meaningful.
  22975. ;; Make sure point is on the value part of the element.
  22976. (keyword
  22977. (and (member (org-element-property :key element)
  22978. '("DESCRIPTION" "TITLE"))
  22979. (save-excursion
  22980. (search-backward ":" (line-beginning-position) t))))
  22981. ;; Check is globally allowed in paragraphs verse blocks and
  22982. ;; table rows (after affiliated keywords) but some objects
  22983. ;; must not be affected.
  22984. ((paragraph table-row verse-block)
  22985. (let ((cbeg (org-element-property :contents-begin element))
  22986. (cend (org-element-property :contents-end element)))
  22987. (and cbeg (>= (point) cbeg) (< (point) cend)
  22988. (org--flyspell-object-check-p element))))))))))
  22989. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22990. (defun org-remove-flyspell-overlays-in (beg end)
  22991. "Remove flyspell overlays in region."
  22992. (and (bound-and-true-p flyspell-mode)
  22993. (fboundp 'flyspell-delete-region-overlays)
  22994. (flyspell-delete-region-overlays beg end)))
  22995. (defvar flyspell-delayed-commands)
  22996. (eval-after-load "flyspell"
  22997. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22998. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22999. (eval-after-load "bookmark"
  23000. '(if (boundp 'bookmark-after-jump-hook)
  23001. ;; We can use the hook
  23002. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23003. ;; Hook not available, use advice
  23004. (defadvice bookmark-jump (after org-make-visible activate)
  23005. "Make the position visible."
  23006. (org-bookmark-jump-unhide))))
  23007. ;; Make sure saveplace shows the location if it was hidden
  23008. (eval-after-load "saveplace"
  23009. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23010. "Make the position visible."
  23011. (org-bookmark-jump-unhide)))
  23012. ;; Make sure ecb shows the location if it was hidden
  23013. (eval-after-load "ecb"
  23014. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23015. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23016. (when (derived-mode-p 'org-mode)
  23017. (org-show-context))))
  23018. (defun org-bookmark-jump-unhide ()
  23019. "Unhide the current position, to show the bookmark location."
  23020. (and (derived-mode-p 'org-mode)
  23021. (or (outline-invisible-p)
  23022. (save-excursion (goto-char (max (point-min) (1- (point))))
  23023. (outline-invisible-p)))
  23024. (org-show-context 'bookmark-jump)))
  23025. (defun org-mark-jump-unhide ()
  23026. "Make the point visible with `org-show-context' after jumping to the mark."
  23027. (when (and (derived-mode-p 'org-mode)
  23028. (outline-invisible-p))
  23029. (org-show-context 'mark-goto)))
  23030. (eval-after-load "simple"
  23031. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23032. "Make the point visible with `org-show-context'."
  23033. (org-mark-jump-unhide)))
  23034. (eval-after-load "simple"
  23035. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23036. "Make the point visible with `org-show-context'."
  23037. (org-mark-jump-unhide)))
  23038. (eval-after-load "simple"
  23039. '(defadvice pop-global-mark (after org-make-visible activate)
  23040. "Make the point visible with `org-show-context'."
  23041. (org-mark-jump-unhide)))
  23042. ;; Make session.el ignore our circular variable
  23043. (defvar session-globals-exclude)
  23044. (eval-after-load "session"
  23045. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23046. ;;;; Finish up
  23047. (provide 'org)
  23048. (run-hooks 'org-load-hook)
  23049. ;;; org.el ends here