org.el 951 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194
  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 if you want
  807. to ignore this option when Org opens agenda files for the first
  808. time."
  809. :group 'org-startup
  810. :type '(choice
  811. (const :tag "nofold: show all" nil)
  812. (const :tag "fold: overview" t)
  813. (const :tag "content: all headlines" content)
  814. (const :tag "show everything, even drawers" showeverything)))
  815. (defcustom org-startup-truncated t
  816. "Non-nil means entering Org mode will set `truncate-lines'.
  817. This is useful since some lines containing links can be very long and
  818. uninteresting. Also tables look terrible when wrapped.
  819. The variable `org-startup-truncated' allows to configure
  820. truncation for Org mode different to the other modes that use the
  821. variable `truncate-lines' and as a shortcut instead of putting
  822. the variable `truncate-lines' into the `org-mode-hook'. If one
  823. wants to configure truncation for Org mode not statically but
  824. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  825. the variable `truncate-lines' has to be used because in such a
  826. case it is too late to set the variable `org-startup-truncated'."
  827. :group 'org-startup
  828. :type 'boolean)
  829. (defcustom org-startup-indented nil
  830. "Non-nil means turn on `org-indent-mode' on startup.
  831. This can also be configured on a per-file basis by adding one of
  832. the following lines anywhere in the buffer:
  833. #+STARTUP: indent
  834. #+STARTUP: noindent"
  835. :group 'org-structure
  836. :type '(choice
  837. (const :tag "Not" nil)
  838. (const :tag "Globally (slow on startup in large files)" t)))
  839. (defcustom org-use-sub-superscripts t
  840. "Non-nil means interpret \"_\" and \"^\" for display.
  841. If you want to control how Org exports those characters, see
  842. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  843. used to be an alias for `org-export-with-sub-superscripts' in
  844. Org <8.0, it is not anymore.
  845. When this option is turned on, you can use TeX-like syntax for
  846. sub- and superscripts within the buffer. Several characters after
  847. \"_\" or \"^\" will be considered as a single item - so grouping
  848. with {} is normally not needed. For example, the following things
  849. will be parsed as single sub- or superscripts:
  850. 10^24 or 10^tau several digits will be considered 1 item.
  851. 10^-12 or 10^-tau a leading sign with digits or a word
  852. x^2-y^3 will be read as x^2 - y^3, because items are
  853. terminated by almost any nonword/nondigit char.
  854. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  855. Still, ambiguity is possible. So when in doubt, use {} to enclose
  856. the sub/superscript. If you set this variable to the symbol `{}',
  857. the braces are *required* in order to trigger interpretations as
  858. sub/superscript. This can be helpful in documents that need \"_\"
  859. frequently in plain text."
  860. :group 'org-startup
  861. :version "24.4"
  862. :package-version '(Org . "8.0")
  863. :type '(choice
  864. (const :tag "Always interpret" t)
  865. (const :tag "Only with braces" {})
  866. (const :tag "Never interpret" nil)))
  867. (defcustom org-startup-with-beamer-mode nil
  868. "Non-nil means turn on `org-beamer-mode' on startup.
  869. This can also be configured on a per-file basis by adding one of
  870. the following lines anywhere in the buffer:
  871. #+STARTUP: beamer"
  872. :group 'org-startup
  873. :version "24.1"
  874. :type 'boolean)
  875. (defcustom org-startup-align-all-tables nil
  876. "Non-nil means align all tables when visiting a file.
  877. This is useful when the column width in tables is forced with <N> cookies
  878. in table fields. Such tables will look correct only after the first re-align.
  879. This can also be configured on a per-file basis by adding one of
  880. the following lines anywhere in the buffer:
  881. #+STARTUP: align
  882. #+STARTUP: noalign"
  883. :group 'org-startup
  884. :type 'boolean)
  885. (defcustom org-startup-with-inline-images nil
  886. "Non-nil means show inline images when loading a new Org file.
  887. This can also be configured on a per-file basis by adding one of
  888. the following lines anywhere in the buffer:
  889. #+STARTUP: inlineimages
  890. #+STARTUP: noinlineimages"
  891. :group 'org-startup
  892. :version "24.1"
  893. :type 'boolean)
  894. (defcustom org-startup-with-latex-preview nil
  895. "Non-nil means preview LaTeX fragments when loading a new Org file.
  896. This can also be configured on a per-file basis by adding one of
  897. the following lines anywhere in the buffer:
  898. #+STARTUP: latexpreview
  899. #+STARTUP: nolatexpreview"
  900. :group 'org-startup
  901. :version "24.4"
  902. :package-version '(Org . "8.0")
  903. :type 'boolean)
  904. (defcustom org-insert-mode-line-in-empty-file nil
  905. "Non-nil means insert the first line setting Org mode in empty files.
  906. When the function `org-mode' is called interactively in an empty file, this
  907. normally means that the file name does not automatically trigger Org mode.
  908. To ensure that the file will always be in Org mode in the future, a
  909. line enforcing Org mode will be inserted into the buffer, if this option
  910. has been set."
  911. :group 'org-startup
  912. :type 'boolean)
  913. (defcustom org-replace-disputed-keys nil
  914. "Non-nil means use alternative key bindings for some keys.
  915. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  916. These keys are also used by other packages like shift-selection-mode'
  917. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  918. If you want to use Org mode together with one of these other modes,
  919. or more generally if you would like to move some Org mode commands to
  920. other keys, set this variable and configure the keys with the variable
  921. `org-disputed-keys'.
  922. This option is only relevant at load-time of Org mode, and must be set
  923. *before* org.el is loaded. Changing it requires a restart of Emacs to
  924. become effective."
  925. :group 'org-startup
  926. :type 'boolean)
  927. (defcustom org-use-extra-keys nil
  928. "Non-nil means use extra key sequence definitions for certain commands.
  929. This happens automatically if `window-system' is nil. This
  930. variable lets you do the same manually. You must set it before
  931. loading Org."
  932. :group 'org-startup
  933. :type 'boolean)
  934. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  935. (defcustom org-disputed-keys
  936. '(([(shift up)] . [(meta p)])
  937. ([(shift down)] . [(meta n)])
  938. ([(shift left)] . [(meta -)])
  939. ([(shift right)] . [(meta +)])
  940. ([(control shift right)] . [(meta shift +)])
  941. ([(control shift left)] . [(meta shift -)]))
  942. "Keys for which Org mode and other modes compete.
  943. This is an alist, cars are the default keys, second element specifies
  944. the alternative to use when `org-replace-disputed-keys' is t.
  945. Keys can be specified in any syntax supported by `define-key'.
  946. The value of this option takes effect only at Org mode startup,
  947. therefore you'll have to restart Emacs to apply it after changing."
  948. :group 'org-startup
  949. :type 'alist)
  950. (defun org-key (key)
  951. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  952. Or return the original if not disputed."
  953. (when org-replace-disputed-keys
  954. (let* ((nkey (key-description key))
  955. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  956. org-disputed-keys)))
  957. (setq key (if x (cdr x) key))))
  958. key)
  959. (defun org-defkey (keymap key def)
  960. "Define a key, possibly translated, as returned by `org-key'."
  961. (define-key keymap (org-key key) def))
  962. (defcustom org-ellipsis nil
  963. "The ellipsis to use in the Org mode outline.
  964. When nil, just use the standard three dots.
  965. When a string, use that string instead.
  966. The change affects only Org mode (which will then use its own display table).
  967. Changing this requires executing `\\[org-mode]' in a buffer to become
  968. effective."
  969. :group 'org-startup
  970. :type '(choice (const :tag "Default" nil)
  971. (string :tag "String" :value "...#"))
  972. :safe #'string-or-null-p)
  973. (defvar org-display-table nil
  974. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  975. (defgroup org-keywords nil
  976. "Keywords in Org mode."
  977. :tag "Org Keywords"
  978. :group 'org)
  979. (defcustom org-closed-keep-when-no-todo nil
  980. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  981. :group 'org-todo
  982. :group 'org-keywords
  983. :version "24.4"
  984. :package-version '(Org . "8.0")
  985. :type 'boolean)
  986. (defgroup org-structure nil
  987. "Options concerning the general structure of Org files."
  988. :tag "Org Structure"
  989. :group 'org)
  990. (defgroup org-reveal-location nil
  991. "Options about how to make context of a location visible."
  992. :tag "Org Reveal Location"
  993. :group 'org-structure)
  994. (defcustom org-show-context-detail '((agenda . local)
  995. (bookmark-jump . lineage)
  996. (isearch . lineage)
  997. (default . ancestors))
  998. "Alist between context and visibility span when revealing a location.
  999. \\<org-mode-map>Some actions may move point into invisible
  1000. locations. As a consequence, Org always expose a neighborhood
  1001. around point. How much is shown depends on the initial action,
  1002. or context. Valid contexts are
  1003. agenda when exposing an entry from the agenda
  1004. org-goto when using the command `org-goto' (`\\[org-goto]')
  1005. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1006. tags-tree when constructing a sparse tree based on tags matches
  1007. link-search when exposing search matches associated with a link
  1008. mark-goto when exposing the jump goal of a mark
  1009. bookmark-jump when exposing a bookmark location
  1010. isearch when exiting from an incremental search
  1011. default default for all contexts not set explicitly
  1012. Allowed visibility spans are
  1013. minimal show current headline; if point is not on headline,
  1014. also show entry
  1015. local show current headline, entry and next headline
  1016. ancestors show current headline and its direct ancestors; if
  1017. point is not on headline, also show entry
  1018. lineage show current headline, its direct ancestors and all
  1019. their children; if point is not on headline, also show
  1020. entry and first child
  1021. tree show current headline, its direct ancestors and all
  1022. their children; if point is not on headline, also show
  1023. entry and all children
  1024. canonical show current headline, its direct ancestors along with
  1025. their entries and children; if point is not located on
  1026. the headline, also show current entry and all children
  1027. As special cases, a nil or t value means show all contexts in
  1028. `minimal' or `canonical' view, respectively.
  1029. Some views can make displayed information very compact, but also
  1030. make it harder to edit the location of the match. In such
  1031. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1032. more context."
  1033. :group 'org-reveal-location
  1034. :version "25.2"
  1035. :package-version '(Org . "9.0")
  1036. :type '(choice
  1037. (const :tag "Canonical" t)
  1038. (const :tag "Minimal" nil)
  1039. (repeat :greedy t :tag "Individual contexts"
  1040. (cons
  1041. (choice :tag "Context"
  1042. (const agenda)
  1043. (const org-goto)
  1044. (const occur-tree)
  1045. (const tags-tree)
  1046. (const link-search)
  1047. (const mark-goto)
  1048. (const bookmark-jump)
  1049. (const isearch)
  1050. (const default))
  1051. (choice :tag "Detail level"
  1052. (const minimal)
  1053. (const local)
  1054. (const ancestors)
  1055. (const lineage)
  1056. (const tree)
  1057. (const canonical))))))
  1058. (defcustom org-indirect-buffer-display 'other-window
  1059. "How should indirect tree buffers be displayed?
  1060. This applies to indirect buffers created with the commands
  1061. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1062. Valid values are:
  1063. current-window Display in the current window
  1064. other-window Just display in another window.
  1065. dedicated-frame Create one new frame, and re-use it each time.
  1066. new-frame Make a new frame each time. Note that in this case
  1067. previously-made indirect buffers are kept, and you need to
  1068. kill these buffers yourself."
  1069. :group 'org-structure
  1070. :group 'org-agenda-windows
  1071. :type '(choice
  1072. (const :tag "In current window" current-window)
  1073. (const :tag "In current frame, other window" other-window)
  1074. (const :tag "Each time a new frame" new-frame)
  1075. (const :tag "One dedicated frame" dedicated-frame)))
  1076. (defcustom org-use-speed-commands nil
  1077. "Non-nil means activate single letter commands at beginning of a headline.
  1078. This may also be a function to test for appropriate locations where speed
  1079. commands should be active.
  1080. For example, to activate speed commands when the point is on any
  1081. star at the beginning of the headline, you can do this:
  1082. (setq org-use-speed-commands
  1083. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1084. :group 'org-structure
  1085. :type '(choice
  1086. (const :tag "Never" nil)
  1087. (const :tag "At beginning of headline stars" t)
  1088. (function)))
  1089. (defcustom org-speed-commands-user nil
  1090. "Alist of additional speed commands.
  1091. This list will be checked before `org-speed-commands-default'
  1092. when the variable `org-use-speed-commands' is non-nil
  1093. and when the cursor is at the beginning of a headline.
  1094. The car if each entry is a string with a single letter, which must
  1095. be assigned to `self-insert-command' in the global map.
  1096. The cdr is either a command to be called interactively, a function
  1097. to be called, or a form to be evaluated.
  1098. An entry that is just a list with a single string will be interpreted
  1099. as a descriptive headline that will be added when listing the speed
  1100. commands in the Help buffer using the `?' speed command."
  1101. :group 'org-structure
  1102. :type '(repeat :value ("k" . ignore)
  1103. (choice :value ("k" . ignore)
  1104. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1105. (cons :tag "Letter and Command"
  1106. (string :tag "Command letter")
  1107. (choice
  1108. (function)
  1109. (sexp))))))
  1110. (defcustom org-bookmark-names-plist
  1111. '(:last-capture "org-capture-last-stored"
  1112. :last-refile "org-refile-last-stored"
  1113. :last-capture-marker "org-capture-last-stored-marker")
  1114. "Names for bookmarks automatically set by some Org commands.
  1115. This can provide strings as names for a number of bookmarks Org sets
  1116. automatically. The following keys are currently implemented:
  1117. :last-capture
  1118. :last-capture-marker
  1119. :last-refile
  1120. When a key does not show up in the property list, the corresponding bookmark
  1121. is not set."
  1122. :group 'org-structure
  1123. :type 'plist)
  1124. (defgroup org-cycle nil
  1125. "Options concerning visibility cycling in Org mode."
  1126. :tag "Org Cycle"
  1127. :group 'org-structure)
  1128. (defcustom org-cycle-skip-children-state-if-no-children t
  1129. "Non-nil means skip CHILDREN state in entries that don't have any."
  1130. :group 'org-cycle
  1131. :type 'boolean)
  1132. (defcustom org-cycle-max-level nil
  1133. "Maximum level which should still be subject to visibility cycling.
  1134. Levels higher than this will, for cycling, be treated as text, not a headline.
  1135. When `org-odd-levels-only' is set, a value of N in this variable actually
  1136. means 2N-1 stars as the limiting headline.
  1137. When nil, cycle all levels.
  1138. Note that the limiting level of cycling is also influenced by
  1139. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1140. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1141. than its value."
  1142. :group 'org-cycle
  1143. :type '(choice
  1144. (const :tag "No limit" nil)
  1145. (integer :tag "Maximum level")))
  1146. (defcustom org-hide-block-startup nil
  1147. "Non-nil means entering Org mode will fold all blocks.
  1148. This can also be set in on a per-file basis with
  1149. #+STARTUP: hideblocks
  1150. #+STARTUP: showblocks"
  1151. :group 'org-startup
  1152. :group 'org-cycle
  1153. :type 'boolean)
  1154. (defcustom org-cycle-global-at-bob nil
  1155. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1156. This makes it possible to do global cycling without having to use `S-TAB'
  1157. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1158. line of the buffer
  1159. must not be a headline -- it may be empty or some other text.
  1160. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1161. sure the cursor stays at the beginning of the buffer.
  1162. When this option is nil, don't do anything special at the beginning of
  1163. the buffer."
  1164. :group 'org-cycle
  1165. :type 'boolean)
  1166. (defcustom org-cycle-level-after-item/entry-creation t
  1167. "Non-nil means cycle entry level or item indentation in new empty entries.
  1168. When the cursor is at the end of an empty headline, i.e., with only stars
  1169. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1170. and then all possible ancestor states, before returning to the original state.
  1171. This makes data entry extremely fast: M-RET to create a new headline,
  1172. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1173. When the cursor is at the end of an empty plain list item, one TAB will
  1174. make it a subitem, two or more tabs will back up to make this an item
  1175. higher up in the item hierarchy."
  1176. :group 'org-cycle
  1177. :type 'boolean)
  1178. (defcustom org-cycle-emulate-tab t
  1179. "Where should `org-cycle' emulate TAB.
  1180. nil Never
  1181. white Only in completely white lines
  1182. whitestart Only at the beginning of lines, before the first non-white char
  1183. t Everywhere except in headlines
  1184. exc-hl-bol Everywhere except at the start of a headline
  1185. If TAB is used in a place where it does not emulate TAB, the current subtree
  1186. visibility is cycled."
  1187. :group 'org-cycle
  1188. :type '(choice (const :tag "Never" nil)
  1189. (const :tag "Only in completely white lines" white)
  1190. (const :tag "Before first char in a line" whitestart)
  1191. (const :tag "Everywhere except in headlines" t)
  1192. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1193. (defcustom org-cycle-separator-lines 2
  1194. "Number of empty lines needed to keep an empty line between collapsed trees.
  1195. If you leave an empty line between the end of a subtree and the following
  1196. headline, this empty line is hidden when the subtree is folded.
  1197. Org mode will leave (exactly) one empty line visible if the number of
  1198. empty lines is equal or larger to the number given in this variable.
  1199. So the default 2 means at least 2 empty lines after the end of a subtree
  1200. are needed to produce free space between a collapsed subtree and the
  1201. following headline.
  1202. If the number is negative, and the number of empty lines is at least -N,
  1203. all empty lines are shown.
  1204. Special case: when 0, never leave empty lines in collapsed view."
  1205. :group 'org-cycle
  1206. :type 'integer)
  1207. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1208. (defcustom org-pre-cycle-hook nil
  1209. "Hook that is run before visibility cycling is happening.
  1210. The function(s) in this hook must accept a single argument which indicates
  1211. the new state that will be set right after running this hook. The
  1212. argument is a symbol. Before a global state change, it can have the values
  1213. `overview', `content', or `all'. Before a local state change, it can have
  1214. the values `folded', `children', or `subtree'."
  1215. :group 'org-cycle
  1216. :type 'hook)
  1217. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1218. org-cycle-hide-drawers
  1219. org-cycle-show-empty-lines
  1220. org-optimize-window-after-visibility-change)
  1221. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1222. The function(s) in this hook must accept a single argument which indicates
  1223. the new state that was set by the most recent `org-cycle' command. The
  1224. argument is a symbol. After a global state change, it can have the values
  1225. `overview', `contents', or `all'. After a local state change, it can have
  1226. the values `folded', `children', or `subtree'."
  1227. :group 'org-cycle
  1228. :type 'hook
  1229. :version "25.2"
  1230. :package-version '(Org . "8.3"))
  1231. (defgroup org-edit-structure nil
  1232. "Options concerning structure editing in Org mode."
  1233. :tag "Org Edit Structure"
  1234. :group 'org-structure)
  1235. (defcustom org-odd-levels-only nil
  1236. "Non-nil means skip even levels and only use odd levels for the outline.
  1237. This has the effect that two stars are being added/taken away in
  1238. promotion/demotion commands. It also influences how levels are
  1239. handled by the exporters.
  1240. Changing it requires restart of `font-lock-mode' to become effective
  1241. for fontification also in regions already fontified.
  1242. You may also set this on a per-file basis by adding one of the following
  1243. lines to the buffer:
  1244. #+STARTUP: odd
  1245. #+STARTUP: oddeven"
  1246. :group 'org-edit-structure
  1247. :group 'org-appearance
  1248. :type 'boolean)
  1249. (defcustom org-adapt-indentation t
  1250. "Non-nil means adapt indentation to outline node level.
  1251. When this variable is set, Org assumes that you write outlines by
  1252. indenting text in each node to align with the headline (after the
  1253. stars). The following issues are influenced by this variable:
  1254. - The indentation is increased by one space in a demotion
  1255. command, and decreased by one in a promotion command. However,
  1256. in the latter case, if shifting some line in the entry body
  1257. would alter document structure (e.g., insert a new headline),
  1258. indentation is not changed at all.
  1259. - Property drawers and planning information is inserted indented
  1260. when this variable is set. When nil, they will not be indented.
  1261. - TAB indents a line relative to current level. The lines below
  1262. a headline will be indented when this variable is set.
  1263. Note that this is all about true indentation, by adding and
  1264. removing space characters. See also `org-indent.el' which does
  1265. level-dependent indentation in a virtual way, i.e. at display
  1266. time in Emacs."
  1267. :group 'org-edit-structure
  1268. :type 'boolean)
  1269. (defcustom org-special-ctrl-a/e nil
  1270. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1271. When t, `C-a' will bring back the cursor to the beginning of the
  1272. headline text, i.e. after the stars and after a possible TODO
  1273. keyword. In an item, this will be the position after bullet and
  1274. check-box, if any. When the cursor is already at that position,
  1275. another `C-a' will bring it to the beginning of the line.
  1276. `C-e' will jump to the end of the headline, ignoring the presence
  1277. of tags in the headline. A second `C-e' will then jump to the
  1278. true end of the line, after any tags. This also means that, when
  1279. this variable is non-nil, `C-e' also will never jump beyond the
  1280. end of the heading of a folded section, i.e. not after the
  1281. ellipses.
  1282. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1283. normally, going to the true line boundary first. Only a directly
  1284. following, identical keypress will bring the cursor to the
  1285. special positions.
  1286. This may also be a cons cell where the behavior for `C-a' and
  1287. `C-e' is set separately."
  1288. :group 'org-edit-structure
  1289. :type '(choice
  1290. (const :tag "off" nil)
  1291. (const :tag "on: after stars/bullet and before tags first" t)
  1292. (const :tag "reversed: true line boundary first" reversed)
  1293. (cons :tag "Set C-a and C-e separately"
  1294. (choice :tag "Special C-a"
  1295. (const :tag "off" nil)
  1296. (const :tag "on: after stars/bullet first" t)
  1297. (const :tag "reversed: before stars/bullet first" reversed))
  1298. (choice :tag "Special C-e"
  1299. (const :tag "off" nil)
  1300. (const :tag "on: before tags first" t)
  1301. (const :tag "reversed: after tags first" reversed)))))
  1302. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1303. (defcustom org-special-ctrl-k nil
  1304. "Non-nil means `C-k' will behave specially in headlines.
  1305. When nil, `C-k' will call the default `kill-line' command.
  1306. When t, the following will happen while the cursor is in the headline:
  1307. - When the cursor is at the beginning of a headline, kill the entire
  1308. line and possible the folded subtree below the line.
  1309. - When in the middle of the headline text, kill the headline up to the tags.
  1310. - When after the headline text, kill the tags."
  1311. :group 'org-edit-structure
  1312. :type 'boolean)
  1313. (defcustom org-ctrl-k-protect-subtree nil
  1314. "Non-nil means, do not delete a hidden subtree with C-k.
  1315. When set to the symbol `error', simply throw an error when C-k is
  1316. used to kill (part-of) a headline that has hidden text behind it.
  1317. Any other non-nil value will result in a query to the user, if it is
  1318. OK to kill that hidden subtree. When nil, kill without remorse."
  1319. :group 'org-edit-structure
  1320. :version "24.1"
  1321. :type '(choice
  1322. (const :tag "Do not protect hidden subtrees" nil)
  1323. (const :tag "Protect hidden subtrees with a security query" t)
  1324. (const :tag "Never kill a hidden subtree with C-k" error)))
  1325. (defcustom org-special-ctrl-o t
  1326. "Non-nil means, make `C-o' insert a row in tables."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-catch-invisible-edits nil
  1330. "Check if in invisible region before inserting or deleting a character.
  1331. Valid values are:
  1332. nil Do not check, so just do invisible edits.
  1333. error Throw an error and do nothing.
  1334. show Make point visible, and do the requested edit.
  1335. show-and-error Make point visible, then throw an error and abort the edit.
  1336. smart Make point visible, and do insertion/deletion if it is
  1337. adjacent to visible text and the change feels predictable.
  1338. Never delete a previously invisible character or add in the
  1339. middle or right after an invisible region. Basically, this
  1340. allows insertion and backward-delete right before ellipses.
  1341. FIXME: maybe in this case we should not even show?"
  1342. :group 'org-edit-structure
  1343. :version "24.1"
  1344. :type '(choice
  1345. (const :tag "Do not check" nil)
  1346. (const :tag "Throw error when trying to edit" error)
  1347. (const :tag "Unhide, but do not do the edit" show-and-error)
  1348. (const :tag "Show invisible part and do the edit" show)
  1349. (const :tag "Be smart and do the right thing" smart)))
  1350. (defcustom org-yank-folded-subtrees t
  1351. "Non-nil means when yanking subtrees, fold them.
  1352. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1353. it starts with a heading and all other headings in it are either children
  1354. or siblings, then fold all the subtrees. However, do this only if no
  1355. text after the yank would be swallowed into a folded tree by this action."
  1356. :group 'org-edit-structure
  1357. :type 'boolean)
  1358. (defcustom org-yank-adjusted-subtrees nil
  1359. "Non-nil means when yanking subtrees, adjust the level.
  1360. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1361. this function for details."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-M-RET-may-split-line '((default . t))
  1365. "Non-nil means M-RET will split the line at the cursor position.
  1366. When nil, it will go to the end of the line before making a
  1367. new line.
  1368. You may also set this option in a different way for different
  1369. contexts. Valid contexts are:
  1370. headline when creating a new headline
  1371. item when creating a new item
  1372. table in a table field
  1373. default the value to be used for all contexts not explicitly
  1374. customized"
  1375. :group 'org-structure
  1376. :group 'org-table
  1377. :type '(choice
  1378. (const :tag "Always" t)
  1379. (const :tag "Never" nil)
  1380. (repeat :greedy t :tag "Individual contexts"
  1381. (cons
  1382. (choice :tag "Context"
  1383. (const headline)
  1384. (const item)
  1385. (const table)
  1386. (const default))
  1387. (boolean)))))
  1388. (defcustom org-insert-heading-respect-content nil
  1389. "Non-nil means insert new headings after the current subtree.
  1390. \\<org-mode-map>
  1391. When nil, the new heading is created directly after the current line.
  1392. The commands `\\[org-insert-heading-respect-content]' and \
  1393. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1394. for the duration of the command."
  1395. :group 'org-structure
  1396. :type 'boolean)
  1397. (defcustom org-blank-before-new-entry '((heading . auto)
  1398. (plain-list-item . auto))
  1399. "Should `org-insert-heading' leave a blank line before new heading/item?
  1400. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1401. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1402. which case Org will look at the surrounding headings/items and try to
  1403. make an intelligent decision whether to insert a blank line or not."
  1404. :group 'org-edit-structure
  1405. :type '(list
  1406. (cons (const heading)
  1407. (choice (const :tag "Never" nil)
  1408. (const :tag "Always" t)
  1409. (const :tag "Auto" auto)))
  1410. (cons (const plain-list-item)
  1411. (choice (const :tag "Never" nil)
  1412. (const :tag "Always" t)
  1413. (const :tag "Auto" auto)))))
  1414. (defcustom org-insert-heading-hook nil
  1415. "Hook being run after inserting a new heading."
  1416. :group 'org-edit-structure
  1417. :type 'hook)
  1418. (defcustom org-enable-fixed-width-editor t
  1419. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1420. This currently only means they are never auto-wrapped.
  1421. When nil, such lines will be treated like ordinary lines."
  1422. :group 'org-edit-structure
  1423. :type 'boolean)
  1424. (defcustom org-goto-auto-isearch t
  1425. "Non-nil means typing characters in `org-goto' starts incremental search.
  1426. When nil, you can use these keybindings to navigate the buffer:
  1427. q Quit the org-goto interface
  1428. n Go to the next visible heading
  1429. p Go to the previous visible heading
  1430. f Go one heading forward on same level
  1431. b Go one heading backward on same level
  1432. u Go one heading up"
  1433. :group 'org-edit-structure
  1434. :type 'boolean)
  1435. (defgroup org-sparse-trees nil
  1436. "Options concerning sparse trees in Org mode."
  1437. :tag "Org Sparse Trees"
  1438. :group 'org-structure)
  1439. (defcustom org-highlight-sparse-tree-matches t
  1440. "Non-nil means highlight all matches that define a sparse tree.
  1441. The highlights will automatically disappear the next time the buffer is
  1442. changed by an edit command."
  1443. :group 'org-sparse-trees
  1444. :type 'boolean)
  1445. (defcustom org-remove-highlights-with-change t
  1446. "Non-nil means any change to the buffer will remove temporary highlights.
  1447. \\<org-mode-map>\
  1448. Such highlights are created by `org-occur' and `org-clock-display'.
  1449. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1450. to get rid of the highlights.
  1451. The highlights created by `org-toggle-latex-fragment' always need
  1452. `\\[org-toggle-latex-fragment]' to be removed."
  1453. :group 'org-sparse-trees
  1454. :group 'org-time
  1455. :type 'boolean)
  1456. (defcustom org-occur-case-fold-search t
  1457. "Non-nil means `org-occur' should be case-insensitive.
  1458. If set to `smart' the search will be case-insensitive only if it
  1459. doesn't specify any upper case character."
  1460. :group 'org-sparse-trees
  1461. :version "25.2"
  1462. :type '(choice
  1463. (const :tag "Case-sensitive" nil)
  1464. (const :tag "Case-insensitive" t)
  1465. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1466. (defcustom org-occur-hook '(org-first-headline-recenter)
  1467. "Hook that is run after `org-occur' has constructed a sparse tree.
  1468. This can be used to recenter the window to show as much of the structure
  1469. as possible."
  1470. :group 'org-sparse-trees
  1471. :type 'hook)
  1472. (defgroup org-imenu-and-speedbar nil
  1473. "Options concerning imenu and speedbar in Org mode."
  1474. :tag "Org Imenu and Speedbar"
  1475. :group 'org-structure)
  1476. (defcustom org-imenu-depth 2
  1477. "The maximum level for Imenu access to Org headlines.
  1478. This also applied for speedbar access."
  1479. :group 'org-imenu-and-speedbar
  1480. :type 'integer)
  1481. (defgroup org-table nil
  1482. "Options concerning tables in Org mode."
  1483. :tag "Org Table"
  1484. :group 'org)
  1485. (defcustom org-enable-table-editor 'optimized
  1486. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1487. When nil, such lines will be treated like ordinary lines.
  1488. When equal to the symbol `optimized', the table editor will be optimized to
  1489. do the following:
  1490. - Automatic overwrite mode in front of whitespace in table fields.
  1491. This makes the structure of the table stay in tact as long as the edited
  1492. field does not exceed the column width.
  1493. - Minimize the number of realigns. Normally, the table is aligned each time
  1494. TAB or RET are pressed to move to another field. With optimization this
  1495. happens only if changes to a field might have changed the column width.
  1496. Optimization requires replacing the functions `self-insert-command',
  1497. `delete-char', and `backward-delete-char' in Org buffers, with a
  1498. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1499. good at guessing when a re-align will be necessary, but you can always
  1500. force one with `\\[org-ctrl-c-ctrl-c]'.
  1501. If you would like to use the optimized version in Org mode, but the
  1502. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1503. This variable can be used to turn on and off the table editor during a session,
  1504. but in order to toggle optimization, a restart is required.
  1505. See also the variable `org-table-auto-blank-field'."
  1506. :group 'org-table
  1507. :type '(choice
  1508. (const :tag "off" nil)
  1509. (const :tag "on" t)
  1510. (const :tag "on, optimized" optimized)))
  1511. (defcustom org-self-insert-cluster-for-undo nil
  1512. "Non-nil means cluster self-insert commands for undo when possible.
  1513. If this is set, then, like in the Emacs command loop, 20 consecutive
  1514. characters will be undone together.
  1515. This is configurable, because there is some impact on typing performance."
  1516. :group 'org-table
  1517. :type 'boolean)
  1518. (defcustom org-table-tab-recognizes-table.el t
  1519. "Non-nil means TAB will automatically notice a table.el table.
  1520. When it sees such a table, it moves point into it and - if necessary -
  1521. calls `table-recognize-table'."
  1522. :group 'org-table-editing
  1523. :type 'boolean)
  1524. (defgroup org-link nil
  1525. "Options concerning links in Org mode."
  1526. :tag "Org Link"
  1527. :group 'org)
  1528. (defvar-local org-link-abbrev-alist-local nil
  1529. "Buffer-local version of `org-link-abbrev-alist', which see.
  1530. The value of this is taken from the #+LINK lines.")
  1531. (defcustom org-link-parameters
  1532. '(("doi" :follow org--open-doi-link)
  1533. ("elisp" :follow org--open-elisp-link)
  1534. ("file" :complete org-file-complete-link)
  1535. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1536. ("help" :follow org--open-help-link)
  1537. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1538. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1539. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1540. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1541. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1542. ("shell" :follow org--open-shell-link))
  1543. "An alist of properties that defines all the links in Org mode.
  1544. The key in each association is a string of the link type.
  1545. Subsequent optional elements make up a p-list of link properties.
  1546. :follow - A function that takes the link path as an argument.
  1547. :export - A function that takes the link path, description and
  1548. export-backend as arguments.
  1549. :store - A function responsible for storing the link. See the
  1550. function `org-store-link-functions'.
  1551. :complete - A function that inserts a link with completion. The
  1552. function takes one optional prefix arg.
  1553. :face - A face for the link, or a function that returns a face.
  1554. The function takes one argument which is the link path. The
  1555. default face is `org-link'.
  1556. :mouse-face - The mouse-face. The default is `highlight'.
  1557. :display - `full' will not fold the link in descriptive
  1558. display. Default is `org-link'.
  1559. :help-echo - A string or function that takes (window object position)
  1560. as arguments and returns a string.
  1561. :keymap - A keymap that is active on the link. The default is
  1562. `org-mouse-map'.
  1563. :htmlize-link - A function for the htmlize-link. Defaults
  1564. to (list :uri \"type:path\")
  1565. :activate-func - A function to run at the end of font-lock
  1566. activation. The function must accept (link-start link-end path bracketp)
  1567. as arguments."
  1568. :group 'org-link
  1569. :type '(alist :tag "Link display parameters"
  1570. :value-type plist))
  1571. (defun org-link-get-parameter (type key)
  1572. "Get TYPE link property for KEY.
  1573. TYPE is a string and KEY is a plist keyword."
  1574. (plist-get
  1575. (cdr (assoc type org-link-parameters))
  1576. key))
  1577. (defun org-link-set-parameters (type &rest parameters)
  1578. "Set link TYPE properties to PARAMETERS.
  1579. PARAMETERS should be :key val pairs."
  1580. (let ((data (assoc type org-link-parameters)))
  1581. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1582. (push (cons type parameters) org-link-parameters)
  1583. (org-make-link-regexps)
  1584. (org-element-update-syntax))))
  1585. (defun org-link-types ()
  1586. "Return a list of known link types."
  1587. (mapcar #'car org-link-parameters))
  1588. (defcustom org-link-abbrev-alist nil
  1589. "Alist of link abbreviations.
  1590. The car of each element is a string, to be replaced at the start of a link.
  1591. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1592. links in Org buffers can have an optional tag after a double colon, e.g.,
  1593. [[linkkey:tag][description]]
  1594. The `linkkey' must be a single word, starting with a letter, followed
  1595. by letters, numbers, `-' or `_'.
  1596. If REPLACE is a string, the tag will simply be appended to create the link.
  1597. If the string contains \"%s\", the tag will be inserted there. If the string
  1598. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1599. at that point (see the function `url-hexify-string'). If the string contains
  1600. the specifier \"%(my-function)\", then the custom function `my-function' will
  1601. be invoked: this function takes the tag as its only argument and must return
  1602. a string.
  1603. REPLACE may also be a function that will be called with the tag as the
  1604. only argument to create the link, which should be returned as a string.
  1605. See the manual for examples."
  1606. :group 'org-link
  1607. :type '(repeat
  1608. (cons
  1609. (string :tag "Protocol")
  1610. (choice
  1611. (string :tag "Format")
  1612. (function)))))
  1613. (defcustom org-descriptive-links t
  1614. "Non-nil means Org will display descriptive links.
  1615. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1616. \"Org Website\", hiding the link itself and just displaying its
  1617. description. When set to nil, Org will display the full links
  1618. literally.
  1619. You can interactively set the value of this variable by calling
  1620. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1621. :group 'org-link
  1622. :type 'boolean)
  1623. (defcustom org-link-file-path-type 'adaptive
  1624. "How the path name in file links should be stored.
  1625. Valid values are:
  1626. relative Relative to the current directory, i.e. the directory of the file
  1627. into which the link is being inserted.
  1628. absolute Absolute path, if possible with ~ for home directory.
  1629. noabbrev Absolute path, no abbreviation of home directory.
  1630. adaptive Use relative path for files in the current directory and sub-
  1631. directories of it. For other files, use an absolute path."
  1632. :group 'org-link
  1633. :type '(choice
  1634. (const relative)
  1635. (const absolute)
  1636. (const noabbrev)
  1637. (const adaptive)))
  1638. (defvaralias 'org-activate-links 'org-highlight-links)
  1639. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1640. "Types of links that should be highlighted in Org files.
  1641. This is a list of symbols, each one of them leading to the
  1642. highlighting of a certain link type.
  1643. You can still open links that are not highlighted.
  1644. In principle, it does not hurt to turn on highlighting for all
  1645. link types. There may be a small gain when turning off unused
  1646. link types. The types are:
  1647. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1648. angle Links in angular brackets that may contain whitespace like
  1649. <bbdb:Carsten Dominik>.
  1650. plain Plain links in normal text, no whitespace, like http://google.com.
  1651. radio Text that is matched by a radio target, see manual for details.
  1652. tag Tag settings in a headline (link to tag search).
  1653. date Time stamps (link to calendar).
  1654. footnote Footnote labels.
  1655. If you set this variable during an Emacs session, use `org-mode-restart'
  1656. in the Org buffer so that the change takes effect."
  1657. :group 'org-link
  1658. :group 'org-appearance
  1659. :type '(set :greedy t
  1660. (const :tag "Double bracket links" bracket)
  1661. (const :tag "Angular bracket links" angle)
  1662. (const :tag "Plain text links" plain)
  1663. (const :tag "Radio target matches" radio)
  1664. (const :tag "Tags" tag)
  1665. (const :tag "Timestamps" date)
  1666. (const :tag "Footnotes" footnote)))
  1667. (defcustom org-make-link-description-function nil
  1668. "Function to use for generating link descriptions from links.
  1669. When nil, the link location will be used. This function must take
  1670. two parameters: the first one is the link, the second one is the
  1671. description generated by `org-insert-link'. The function should
  1672. return the description to use."
  1673. :group 'org-link
  1674. :type '(choice (const nil) (function)))
  1675. (defgroup org-link-store nil
  1676. "Options concerning storing links in Org mode."
  1677. :tag "Org Store Link"
  1678. :group 'org-link)
  1679. (defcustom org-url-hexify-p t
  1680. "When non-nil, hexify URL when creating a link."
  1681. :type 'boolean
  1682. :version "24.3"
  1683. :group 'org-link-store)
  1684. (defcustom org-email-link-description-format "Email %c: %.30s"
  1685. "Format of the description part of a link to an email or usenet message.
  1686. The following %-escapes will be replaced by corresponding information:
  1687. %F full \"From\" field
  1688. %f name, taken from \"From\" field, address if no name
  1689. %T full \"To\" field
  1690. %t first name in \"To\" field, address if no name
  1691. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1692. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1693. %s subject
  1694. %d date
  1695. %m message-id.
  1696. You may use normal field width specification between the % and the letter.
  1697. This is for example useful to limit the length of the subject.
  1698. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1699. :group 'org-link-store
  1700. :type 'string)
  1701. (defcustom org-from-is-user-regexp
  1702. (let (r1 r2)
  1703. (when (and user-mail-address (not (string= user-mail-address "")))
  1704. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1705. (when (and user-full-name (not (string= user-full-name "")))
  1706. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1707. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1708. "Regexp matched against the \"From:\" header of an email or usenet message.
  1709. It should match if the message is from the user him/herself."
  1710. :group 'org-link-store
  1711. :type 'regexp)
  1712. (defcustom org-context-in-file-links t
  1713. "Non-nil means file links from `org-store-link' contain context.
  1714. \\<org-mode-map>
  1715. A search string will be added to the file name with :: as separator
  1716. and used to find the context when the link is activated by the command
  1717. `org-open-at-point'. When this option is t, the entire active region
  1718. will be placed in the search string of the file link. If set to a
  1719. positive integer, only the first n lines of context will be stored.
  1720. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1721. \\[org-store-link]')
  1722. negates this setting for the duration of the command."
  1723. :group 'org-link-store
  1724. :type '(choice boolean integer))
  1725. (defcustom org-keep-stored-link-after-insertion nil
  1726. "Non-nil means keep link in list for entire session.
  1727. \\<org-mode-map>
  1728. The command `org-store-link' adds a link pointing to the current
  1729. location to an internal list. These links accumulate during a session.
  1730. The command `org-insert-link' can be used to insert links into any
  1731. Org file (offering completion for all stored links).
  1732. When this option is nil, every link which has been inserted once using
  1733. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1734. unused
  1735. links more efficient."
  1736. :group 'org-link-store
  1737. :type 'boolean)
  1738. (defgroup org-link-follow nil
  1739. "Options concerning following links in Org mode."
  1740. :tag "Org Follow Link"
  1741. :group 'org-link)
  1742. (defcustom org-link-translation-function nil
  1743. "Function to translate links with different syntax to Org syntax.
  1744. This can be used to translate links created for example by the Planner
  1745. or emacs-wiki packages to Org syntax.
  1746. The function must accept two parameters, a TYPE containing the link
  1747. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1748. which is everything after the link protocol. It should return a cons
  1749. with possibly modified values of type and path.
  1750. Org contains a function for this, so if you set this variable to
  1751. `org-translate-link-from-planner', you should be able follow many
  1752. links created by planner."
  1753. :group 'org-link-follow
  1754. :type '(choice (const nil) (function)))
  1755. (defcustom org-follow-link-hook nil
  1756. "Hook that is run after a link has been followed."
  1757. :group 'org-link-follow
  1758. :type 'hook)
  1759. (defcustom org-tab-follows-link nil
  1760. "Non-nil means on links TAB will follow the link.
  1761. Needs to be set before org.el is loaded.
  1762. This really should not be used, it does not make sense, and the
  1763. implementation is bad."
  1764. :group 'org-link-follow
  1765. :type 'boolean)
  1766. (defcustom org-return-follows-link nil
  1767. "Non-nil means on links RET will follow the link.
  1768. In tables, the special behavior of RET has precedence."
  1769. :group 'org-link-follow
  1770. :type 'boolean)
  1771. (defcustom org-mouse-1-follows-link
  1772. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1773. "Non-nil means mouse-1 on a link will follow the link.
  1774. A longer mouse click will still set point. Needs to be set
  1775. before org.el is loaded."
  1776. :group 'org-link-follow
  1777. :version "24.4"
  1778. :package-version '(Org . "8.3")
  1779. :type '(choice
  1780. (const :tag "A double click follows the link" double)
  1781. (const :tag "Unconditionally follow the link with mouse-1" t)
  1782. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1783. (defcustom org-mark-ring-length 4
  1784. "Number of different positions to be recorded in the ring.
  1785. Changing this requires a restart of Emacs to work correctly."
  1786. :group 'org-link-follow
  1787. :type 'integer)
  1788. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1789. "Non-nil means internal fuzzy links can only match headlines.
  1790. When nil, the a fuzzy link may point to a target or a named
  1791. construct in the document. When set to the special value
  1792. `query-to-create', offer to create a new headline when none
  1793. matched.
  1794. Spaces and statistics cookies are ignored during heading searches."
  1795. :group 'org-link-follow
  1796. :version "24.1"
  1797. :type '(choice
  1798. (const :tag "Use fuzzy text search" nil)
  1799. (const :tag "Match only exact headline" t)
  1800. (const :tag "Match exact headline or query to create it"
  1801. query-to-create))
  1802. :safe #'symbolp)
  1803. (defcustom org-link-frame-setup
  1804. '((vm . vm-visit-folder-other-frame)
  1805. (vm-imap . vm-visit-imap-folder-other-frame)
  1806. (gnus . org-gnus-no-new-news)
  1807. (file . find-file-other-window)
  1808. (wl . wl-other-frame))
  1809. "Setup the frame configuration for following links.
  1810. When following a link with Emacs, it may often be useful to display
  1811. this link in another window or frame. This variable can be used to
  1812. set this up for the different types of links.
  1813. For VM, use any of
  1814. `vm-visit-folder'
  1815. `vm-visit-folder-other-window'
  1816. `vm-visit-folder-other-frame'
  1817. For Gnus, use any of
  1818. `gnus'
  1819. `gnus-other-frame'
  1820. `org-gnus-no-new-news'
  1821. For FILE, use any of
  1822. `find-file'
  1823. `find-file-other-window'
  1824. `find-file-other-frame'
  1825. For Wanderlust use any of
  1826. `wl'
  1827. `wl-other-frame'
  1828. For the calendar, use the variable `calendar-setup'.
  1829. For BBDB, it is currently only possible to display the matches in
  1830. another window."
  1831. :group 'org-link-follow
  1832. :type '(list
  1833. (cons (const vm)
  1834. (choice
  1835. (const vm-visit-folder)
  1836. (const vm-visit-folder-other-window)
  1837. (const vm-visit-folder-other-frame)))
  1838. (cons (const vm-imap)
  1839. (choice
  1840. (const vm-visit-imap-folder)
  1841. (const vm-visit-imap-folder-other-window)
  1842. (const vm-visit-imap-folder-other-frame)))
  1843. (cons (const gnus)
  1844. (choice
  1845. (const gnus)
  1846. (const gnus-other-frame)
  1847. (const org-gnus-no-new-news)))
  1848. (cons (const file)
  1849. (choice
  1850. (const find-file)
  1851. (const find-file-other-window)
  1852. (const find-file-other-frame)))
  1853. (cons (const wl)
  1854. (choice
  1855. (const wl)
  1856. (const wl-other-frame)))))
  1857. (defcustom org-display-internal-link-with-indirect-buffer nil
  1858. "Non-nil means use indirect buffer to display infile links.
  1859. Activating internal links (from one location in a file to another location
  1860. in the same file) normally just jumps to the location. When the link is
  1861. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1862. is displayed in
  1863. another window. When this option is set, the other window actually displays
  1864. an indirect buffer clone of the current buffer, to avoid any visibility
  1865. changes to the current buffer."
  1866. :group 'org-link-follow
  1867. :type 'boolean)
  1868. (defcustom org-open-non-existing-files nil
  1869. "Non-nil means `org-open-file' will open non-existing files.
  1870. When nil, an error will be generated.
  1871. This variable applies only to external applications because they
  1872. might choke on non-existing files. If the link is to a file that
  1873. will be opened in Emacs, the variable is ignored."
  1874. :group 'org-link-follow
  1875. :type 'boolean)
  1876. (defcustom org-open-directory-means-index-dot-org nil
  1877. "Non-nil means a link to a directory really means to index.org.
  1878. When nil, following a directory link will run dired or open a finder/explorer
  1879. window on that directory."
  1880. :group 'org-link-follow
  1881. :type 'boolean)
  1882. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1883. "Non-nil means ask for confirmation before executing shell links.
  1884. Shell links can be dangerous: just think about a link
  1885. [[shell:rm -rf ~/*][Google Search]]
  1886. This link would show up in your Org document as \"Google Search\",
  1887. but really it would remove your entire home directory.
  1888. Therefore we advise against setting this variable to nil.
  1889. Just change it to `y-or-n-p' if you want to confirm with a
  1890. single keystroke rather than having to type \"yes\"."
  1891. :group 'org-link-follow
  1892. :type '(choice
  1893. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1894. (const :tag "with y-or-n (faster)" y-or-n-p)
  1895. (const :tag "no confirmation (dangerous)" nil)))
  1896. (put 'org-confirm-shell-link-function
  1897. 'safe-local-variable
  1898. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1899. (defcustom org-confirm-shell-link-not-regexp ""
  1900. "A regexp to skip confirmation for shell links."
  1901. :group 'org-link-follow
  1902. :version "24.1"
  1903. :type 'regexp)
  1904. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1905. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1906. Elisp links can be dangerous: just think about a link
  1907. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1908. This link would show up in your Org document as \"Google Search\",
  1909. but really it would remove your entire home directory.
  1910. Therefore we advise against setting this variable to nil.
  1911. Just change it to `y-or-n-p' if you want to confirm with a
  1912. single keystroke rather than having to type \"yes\"."
  1913. :group 'org-link-follow
  1914. :type '(choice
  1915. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1916. (const :tag "with y-or-n (faster)" y-or-n-p)
  1917. (const :tag "no confirmation (dangerous)" nil)))
  1918. (put 'org-confirm-shell-link-function
  1919. 'safe-local-variable
  1920. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1921. (defcustom org-confirm-elisp-link-not-regexp ""
  1922. "A regexp to skip confirmation for Elisp links."
  1923. :group 'org-link-follow
  1924. :version "24.1"
  1925. :type 'regexp)
  1926. (defconst org-file-apps-defaults-gnu
  1927. '((remote . emacs)
  1928. (system . mailcap)
  1929. (t . mailcap))
  1930. "Default file applications on a UNIX or GNU/Linux system.
  1931. See `org-file-apps'.")
  1932. (defconst org-file-apps-defaults-macosx
  1933. '((remote . emacs)
  1934. (system . "open %s")
  1935. ("ps.gz" . "gv %s")
  1936. ("eps.gz" . "gv %s")
  1937. ("dvi" . "xdvi %s")
  1938. ("fig" . "xfig %s")
  1939. (t . "open %s"))
  1940. "Default file applications on a macOS system.
  1941. The system \"open\" is known as a default, but we use X11 applications
  1942. for some files for which the OS does not have a good default.
  1943. See `org-file-apps'.")
  1944. (defconst org-file-apps-defaults-windowsnt
  1945. (list '(remote . emacs)
  1946. (cons 'system (lambda (file _path)
  1947. (with-no-warnings (w32-shell-execute "open" file))))
  1948. (cons t (lambda (file _path)
  1949. (with-no-warnings (w32-shell-execute "open" file)))))
  1950. "Default file applications on a Windows NT system.
  1951. The system \"open\" is used for most files.
  1952. See `org-file-apps'.")
  1953. (defcustom org-file-apps
  1954. '((auto-mode . emacs)
  1955. ("\\.mm\\'" . default)
  1956. ("\\.x?html?\\'" . default)
  1957. ("\\.pdf\\'" . default))
  1958. "External applications for opening `file:path' items in a document.
  1959. \\<org-mode-map>\
  1960. Org mode uses system defaults for different file types, but
  1961. you can use this variable to set the application for a given file
  1962. extension. The entries in this list are cons cells where the car identifies
  1963. files and the cdr the corresponding command.
  1964. Possible values for the file identifier are:
  1965. \"string\" A string as a file identifier can be interpreted in different
  1966. ways, depending on its contents:
  1967. - Alphanumeric characters only:
  1968. Match links with this file extension.
  1969. Example: (\"pdf\" . \"evince %s\")
  1970. to open PDFs with evince.
  1971. - Regular expression: Match links where the
  1972. filename matches the regexp. If you want to
  1973. use groups here, use shy groups.
  1974. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1975. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1976. to open *.html and *.xhtml with firefox.
  1977. - Regular expression which contains (non-shy) groups:
  1978. Match links where the whole link, including \"::\", and
  1979. anything after that, matches the regexp.
  1980. In a custom command string, %1, %2, etc. are replaced with
  1981. the parts of the link that were matched by the groups.
  1982. For backwards compatibility, if a command string is given
  1983. that does not use any of the group matches, this case is
  1984. handled identically to the second one (i.e. match against
  1985. file name only).
  1986. In a custom function, you can access the group matches with
  1987. (match-string n link).
  1988. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1989. \"evince -p %1 %s\")
  1990. to open [[file:document.pdf::5]] with evince at page 5.
  1991. `directory' Matches a directory
  1992. `remote' Matches a remote file, accessible through tramp or efs.
  1993. Remote files most likely should be visited through Emacs
  1994. because external applications cannot handle such paths.
  1995. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1996. so all files Emacs knows how to handle. Using this with
  1997. command `emacs' will open most files in Emacs. Beware that this
  1998. will also open html files inside Emacs, unless you add
  1999. (\"html\" . default) to the list as well.
  2000. `system' The system command to open files, like `open' on Windows
  2001. and macOS, and mailcap under GNU/Linux. This is the command
  2002. that will be selected if you call `org-open-at-point' with a
  2003. double prefix argument (`\\[universal-argument] \
  2004. \\[universal-argument] \\[org-open-at-point]').
  2005. t Default for files not matched by any of the other options.
  2006. Possible values for the command are:
  2007. `emacs' The file will be visited by the current Emacs process.
  2008. `default' Use the default application for this file type, which is the
  2009. association for t in the list, most likely in the system-specific
  2010. part. This can be used to overrule an unwanted setting in the
  2011. system-specific variable.
  2012. `system' Use the system command for opening files, like \"open\".
  2013. This command is specified by the entry whose car is `system'.
  2014. Most likely, the system-specific version of this variable
  2015. does define this command, but you can overrule/replace it
  2016. here.
  2017. `mailcap' Use command specified in the mailcaps.
  2018. string A command to be executed by a shell; %s will be replaced
  2019. by the path to the file.
  2020. function A Lisp function, which will be called with two arguments:
  2021. the file path and the original link string, without the
  2022. \"file:\" prefix.
  2023. For more examples, see the system specific constants
  2024. `org-file-apps-defaults-macosx'
  2025. `org-file-apps-defaults-windowsnt'
  2026. `org-file-apps-defaults-gnu'."
  2027. :group 'org-link-follow
  2028. :type '(repeat
  2029. (cons (choice :value ""
  2030. (string :tag "Extension")
  2031. (const :tag "System command to open files" system)
  2032. (const :tag "Default for unrecognized files" t)
  2033. (const :tag "Remote file" remote)
  2034. (const :tag "Links to a directory" directory)
  2035. (const :tag "Any files that have Emacs modes"
  2036. auto-mode))
  2037. (choice :value ""
  2038. (const :tag "Visit with Emacs" emacs)
  2039. (const :tag "Use default" default)
  2040. (const :tag "Use the system command" system)
  2041. (string :tag "Command")
  2042. (function :tag "Function")))))
  2043. (defcustom org-doi-server-url "http://dx.doi.org/"
  2044. "The URL of the DOI server."
  2045. :type 'string
  2046. :version "24.3"
  2047. :group 'org-link-follow)
  2048. (defgroup org-refile nil
  2049. "Options concerning refiling entries in Org mode."
  2050. :tag "Org Refile"
  2051. :group 'org)
  2052. (defcustom org-directory "~/org"
  2053. "Directory with Org files.
  2054. This is just a default location to look for Org files. There is no need
  2055. at all to put your files into this directory. It is used in the
  2056. following situations:
  2057. 1. When a capture template specifies a target file that is not an
  2058. absolute path. The path will then be interpreted relative to
  2059. `org-directory'
  2060. 2. When the value of variable `org-agenda-files' is a single file, any
  2061. relative paths in this file will be taken as relative to
  2062. `org-directory'."
  2063. :group 'org-refile
  2064. :group 'org-capture
  2065. :type 'directory)
  2066. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2067. "Default target for storing notes.
  2068. Used as a fall back file for org-capture.el, for templates that
  2069. do not specify a target file."
  2070. :group 'org-refile
  2071. :group 'org-capture
  2072. :type 'file)
  2073. (defcustom org-goto-interface 'outline
  2074. "The default interface to be used for `org-goto'.
  2075. Allowed values are:
  2076. outline The interface shows an outline of the relevant file
  2077. and the correct heading is found by moving through
  2078. the outline or by searching with incremental search.
  2079. outline-path-completion Headlines in the current buffer are offered via
  2080. completion. This is the interface also used by
  2081. the refile command."
  2082. :group 'org-refile
  2083. :type '(choice
  2084. (const :tag "Outline" outline)
  2085. (const :tag "Outline-path-completion" outline-path-completion)))
  2086. (defcustom org-goto-max-level 5
  2087. "Maximum target level when running `org-goto' with refile interface."
  2088. :group 'org-refile
  2089. :type 'integer)
  2090. (defcustom org-reverse-note-order nil
  2091. "Non-nil means store new notes at the beginning of a file or entry.
  2092. When nil, new notes will be filed to the end of a file or entry.
  2093. This can also be a list with cons cells of regular expressions that
  2094. are matched against file names, and values."
  2095. :group 'org-capture
  2096. :group 'org-refile
  2097. :type '(choice
  2098. (const :tag "Reverse always" t)
  2099. (const :tag "Reverse never" nil)
  2100. (repeat :tag "By file name regexp"
  2101. (cons regexp boolean))))
  2102. (defcustom org-log-refile nil
  2103. "Information to record when a task is refiled.
  2104. Possible values are:
  2105. nil Don't add anything
  2106. time Add a time stamp to the task
  2107. note Prompt for a note and add it with template `org-log-note-headings'
  2108. This option can also be set with on a per-file-basis with
  2109. #+STARTUP: nologrefile
  2110. #+STARTUP: logrefile
  2111. #+STARTUP: lognoterefile
  2112. You can have local logging settings for a subtree by setting the LOGGING
  2113. property to one or more of these keywords.
  2114. When bulk-refiling from the agenda, the value `note' is forbidden and
  2115. will temporarily be changed to `time'."
  2116. :group 'org-refile
  2117. :group 'org-progress
  2118. :version "24.1"
  2119. :type '(choice
  2120. (const :tag "No logging" nil)
  2121. (const :tag "Record timestamp" time)
  2122. (const :tag "Record timestamp with note." note)))
  2123. (defcustom org-refile-targets nil
  2124. "Targets for refiling entries with `\\[org-refile]'.
  2125. This is a list of cons cells. Each cell contains:
  2126. - a specification of the files to be considered, either a list of files,
  2127. or a symbol whose function or variable value will be used to retrieve
  2128. a file name or a list of file names. If you use `org-agenda-files' for
  2129. that, all agenda files will be scanned for targets. Nil means consider
  2130. headings in the current buffer.
  2131. - A specification of how to find candidate refile targets. This may be
  2132. any of:
  2133. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2134. This tag has to be present in all target headlines, inheritance will
  2135. not be considered.
  2136. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2137. todo keyword.
  2138. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2139. headlines that are refiling targets.
  2140. - a cons cell (:level . N). Any headline of level N is considered a target.
  2141. Note that, when `org-odd-levels-only' is set, level corresponds to
  2142. order in hierarchy, not to the number of stars.
  2143. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2144. Note that, when `org-odd-levels-only' is set, level corresponds to
  2145. order in hierarchy, not to the number of stars.
  2146. Each element of this list generates a set of possible targets.
  2147. The union of these sets is presented (with completion) to
  2148. the user by `org-refile'.
  2149. You can set the variable `org-refile-target-verify-function' to a function
  2150. to verify each headline found by the simple criteria above.
  2151. When this variable is nil, all top-level headlines in the current buffer
  2152. are used, equivalent to the value `((nil . (:level . 1))'."
  2153. :group 'org-refile
  2154. :type '(repeat
  2155. (cons
  2156. (choice :value org-agenda-files
  2157. (const :tag "All agenda files" org-agenda-files)
  2158. (const :tag "Current buffer" nil)
  2159. (function) (variable) (file))
  2160. (choice :tag "Identify target headline by"
  2161. (cons :tag "Specific tag" (const :value :tag) (string))
  2162. (cons :tag "TODO keyword" (const :value :todo) (string))
  2163. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2164. (cons :tag "Level number" (const :value :level) (integer))
  2165. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2166. (defcustom org-refile-target-verify-function nil
  2167. "Function to verify if the headline at point should be a refile target.
  2168. The function will be called without arguments, with point at the
  2169. beginning of the headline. It should return t and leave point
  2170. where it is if the headline is a valid target for refiling.
  2171. If the target should not be selected, the function must return nil.
  2172. In addition to this, it may move point to a place from where the search
  2173. should be continued. For example, the function may decide that the entire
  2174. subtree of the current entry should be excluded and move point to the end
  2175. of the subtree."
  2176. :group 'org-refile
  2177. :type '(choice
  2178. (const nil)
  2179. (function)))
  2180. (defcustom org-refile-use-cache nil
  2181. "Non-nil means cache refile targets to speed up the process.
  2182. \\<org-mode-map>\
  2183. The cache for a particular file will be updated automatically when
  2184. the buffer has been killed, or when any of the marker used for flagging
  2185. refile targets no longer points at a live buffer.
  2186. If you have added new entries to a buffer that might themselves be targets,
  2187. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2188. if you find that easier, \
  2189. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2190. \\[org-refile]'."
  2191. :group 'org-refile
  2192. :version "24.1"
  2193. :type 'boolean)
  2194. (defcustom org-refile-use-outline-path nil
  2195. "Non-nil means provide refile targets as paths.
  2196. So a level 3 headline will be available as level1/level2/level3.
  2197. When the value is `file', also include the file name (without directory)
  2198. into the path. In this case, you can also stop the completion after
  2199. the file name, to get entries inserted as top level in the file.
  2200. When `full-file-path', include the full file path."
  2201. :group 'org-refile
  2202. :type '(choice
  2203. (const :tag "Not" nil)
  2204. (const :tag "Yes" t)
  2205. (const :tag "Start with file name" file)
  2206. (const :tag "Start with full file path" full-file-path)))
  2207. (defcustom org-outline-path-complete-in-steps t
  2208. "Non-nil means complete the outline path in hierarchical steps.
  2209. When Org uses the refile interface to select an outline path (see
  2210. `org-refile-use-outline-path'), the completion of the path can be
  2211. done in a single go, or it can be done in steps down the headline
  2212. hierarchy. Going in steps is probably the best if you do not use
  2213. a special completion package like `ido' or `icicles'. However,
  2214. when using these packages, going in one step can be very fast,
  2215. while still showing the whole path to the entry."
  2216. :group 'org-refile
  2217. :type 'boolean)
  2218. (defcustom org-refile-allow-creating-parent-nodes nil
  2219. "Non-nil means allow the creation of new nodes as refile targets.
  2220. New nodes are then created by adding \"/new node name\" to the completion
  2221. of an existing node. When the value of this variable is `confirm',
  2222. new node creation must be confirmed by the user (recommended).
  2223. When nil, the completion must match an existing entry.
  2224. Note that, if the new heading is not seen by the criteria
  2225. listed in `org-refile-targets', multiple instances of the same
  2226. heading would be created by trying again to file under the new
  2227. heading."
  2228. :group 'org-refile
  2229. :type '(choice
  2230. (const :tag "Never" nil)
  2231. (const :tag "Always" t)
  2232. (const :tag "Prompt for confirmation" confirm)))
  2233. (defcustom org-refile-active-region-within-subtree nil
  2234. "Non-nil means also refile active region within a subtree.
  2235. By default `org-refile' doesn't allow refiling regions if they
  2236. don't contain a set of subtrees, but it might be convenient to
  2237. do so sometimes: in that case, the first line of the region is
  2238. converted to a headline before refiling."
  2239. :group 'org-refile
  2240. :version "24.1"
  2241. :type 'boolean)
  2242. (defgroup org-todo nil
  2243. "Options concerning TODO items in Org mode."
  2244. :tag "Org TODO"
  2245. :group 'org)
  2246. (defgroup org-progress nil
  2247. "Options concerning Progress logging in Org mode."
  2248. :tag "Org Progress"
  2249. :group 'org-time)
  2250. (defvar org-todo-interpretation-widgets
  2251. '((:tag "Sequence (cycling hits every state)" sequence)
  2252. (:tag "Type (cycling directly to DONE)" type))
  2253. "The available interpretation symbols for customizing `org-todo-keywords'.
  2254. Interested libraries should add to this list.")
  2255. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2256. "List of TODO entry keyword sequences and their interpretation.
  2257. \\<org-mode-map>This is a list of sequences.
  2258. Each sequence starts with a symbol, either `sequence' or `type',
  2259. indicating if the keywords should be interpreted as a sequence of
  2260. action steps, or as different types of TODO items. The first
  2261. keywords are states requiring action - these states will select a headline
  2262. for inclusion into the global TODO list Org produces. If one of the
  2263. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2264. signify that no further action is necessary. If \"|\" is not found,
  2265. the last keyword is treated as the only DONE state of the sequence.
  2266. The command `\\[org-todo]' cycles an entry through these states, and one
  2267. additional state where no keyword is present. For details about this
  2268. cycling, see the manual.
  2269. TODO keywords and interpretation can also be set on a per-file basis with
  2270. the special #+SEQ_TODO and #+TYP_TODO lines.
  2271. Each keyword can optionally specify a character for fast state selection
  2272. \(in combination with the variable `org-use-fast-todo-selection')
  2273. and specifiers for state change logging, using the same syntax that
  2274. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2275. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2276. indicates to record a time stamp each time this state is selected.
  2277. Each keyword may also specify if a timestamp or a note should be
  2278. recorded when entering or leaving the state, by adding additional
  2279. characters in the parenthesis after the keyword. This looks like this:
  2280. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2281. record only the time of the state change. With X and Y being either
  2282. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2283. Y when leaving the state if and only if the *target* state does not
  2284. define X. You may omit any of the fast-selection key or X or /Y,
  2285. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2286. For backward compatibility, this variable may also be just a list
  2287. of keywords. In this case the interpretation (sequence or type) will be
  2288. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2289. :group 'org-todo
  2290. :group 'org-keywords
  2291. :type '(choice
  2292. (repeat :tag "Old syntax, just keywords"
  2293. (string :tag "Keyword"))
  2294. (repeat :tag "New syntax"
  2295. (cons
  2296. (choice
  2297. :tag "Interpretation"
  2298. ;;Quick and dirty way to see
  2299. ;;`org-todo-interpretations'. This takes the
  2300. ;;place of item arguments
  2301. :convert-widget
  2302. (lambda (widget)
  2303. (widget-put widget
  2304. :args (mapcar
  2305. (lambda (x)
  2306. (widget-convert
  2307. (cons 'const x)))
  2308. org-todo-interpretation-widgets))
  2309. widget))
  2310. (repeat
  2311. (string :tag "Keyword"))))))
  2312. (defvar-local org-todo-keywords-1 nil
  2313. "All TODO and DONE keywords active in a buffer.")
  2314. (defvar org-todo-keywords-for-agenda nil)
  2315. (defvar org-done-keywords-for-agenda nil)
  2316. (defvar org-todo-keyword-alist-for-agenda nil)
  2317. (defvar org-tag-alist-for-agenda nil
  2318. "Alist of all tags from all agenda files.")
  2319. (defvar org-tag-groups-alist-for-agenda nil
  2320. "Alist of all groups tags from all current agenda files.")
  2321. (defvar-local org-tag-groups-alist nil)
  2322. (defvar org-agenda-contributing-files nil)
  2323. (defvar-local org-current-tag-alist nil
  2324. "Alist of all tag groups in current buffer.
  2325. This variable takes into consideration `org-tag-alist',
  2326. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2327. (defvar-local org-not-done-keywords nil)
  2328. (defvar-local org-done-keywords nil)
  2329. (defvar-local org-todo-heads nil)
  2330. (defvar-local org-todo-sets nil)
  2331. (defvar-local org-todo-log-states nil)
  2332. (defvar-local org-todo-kwd-alist nil)
  2333. (defvar-local org-todo-key-alist nil)
  2334. (defvar-local org-todo-key-trigger nil)
  2335. (defcustom org-todo-interpretation 'sequence
  2336. "Controls how TODO keywords are interpreted.
  2337. This variable is in principle obsolete and is only used for
  2338. backward compatibility, if the interpretation of todo keywords is
  2339. not given already in `org-todo-keywords'. See that variable for
  2340. more information."
  2341. :group 'org-todo
  2342. :group 'org-keywords
  2343. :type '(choice (const sequence)
  2344. (const type)))
  2345. (defcustom org-use-fast-todo-selection t
  2346. "\\<org-mode-map>\
  2347. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2348. This variable describes if and under what circumstances the cycling
  2349. mechanism for TODO keywords will be replaced by a single-key, direct
  2350. selection scheme.
  2351. When nil, fast selection is never used.
  2352. When the symbol `prefix', it will be used when `org-todo' is called
  2353. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2354. in an Org buffer, and
  2355. `\\[universal-argument] t' in an agenda buffer.
  2356. When t, fast selection is used by default. In this case, the prefix
  2357. argument forces cycling instead.
  2358. In all cases, the special interface is only used if access keys have
  2359. actually been assigned by the user, i.e. if keywords in the configuration
  2360. are followed by a letter in parenthesis, like TODO(t)."
  2361. :group 'org-todo
  2362. :type '(choice
  2363. (const :tag "Never" nil)
  2364. (const :tag "By default" t)
  2365. (const :tag "Only with C-u C-c C-t" prefix)))
  2366. (defcustom org-provide-todo-statistics t
  2367. "Non-nil means update todo statistics after insert and toggle.
  2368. ALL-HEADLINES means update todo statistics by including headlines
  2369. with no TODO keyword as well, counting them as not done.
  2370. A list of TODO keywords means the same, but skip keywords that are
  2371. not in this list.
  2372. When set to a list of two lists, the first list contains keywords
  2373. to consider as TODO keywords, the second list contains keywords
  2374. to consider as DONE keywords.
  2375. When this is set, todo statistics is updated in the parent of the
  2376. current entry each time a todo state is changed."
  2377. :group 'org-todo
  2378. :type '(choice
  2379. (const :tag "Yes, only for TODO entries" t)
  2380. (const :tag "Yes, including all entries" all-headlines)
  2381. (repeat :tag "Yes, for TODOs in this list"
  2382. (string :tag "TODO keyword"))
  2383. (list :tag "Yes, for TODOs and DONEs in these lists"
  2384. (repeat (string :tag "TODO keyword"))
  2385. (repeat (string :tag "DONE keyword")))
  2386. (other :tag "No TODO statistics" nil)))
  2387. (defcustom org-hierarchical-todo-statistics t
  2388. "Non-nil means TODO statistics covers just direct children.
  2389. When nil, all entries in the subtree are considered.
  2390. This has only an effect if `org-provide-todo-statistics' is set.
  2391. To set this to nil for only a single subtree, use a COOKIE_DATA
  2392. property and include the word \"recursive\" into the value."
  2393. :group 'org-todo
  2394. :type 'boolean)
  2395. (defcustom org-after-todo-state-change-hook nil
  2396. "Hook which is run after the state of a TODO item was changed.
  2397. The new state (a string with a TODO keyword, or nil) is available in the
  2398. Lisp variable `org-state'."
  2399. :group 'org-todo
  2400. :type 'hook)
  2401. (defvar org-blocker-hook nil
  2402. "Hook for functions that are allowed to block a state change.
  2403. Functions in this hook should not modify the buffer.
  2404. Each function gets as its single argument a property list,
  2405. see `org-trigger-hook' for more information about this list.
  2406. If any of the functions in this hook returns nil, the state change
  2407. is blocked.")
  2408. (defvar org-trigger-hook nil
  2409. "Hook for functions that are triggered by a state change.
  2410. Each function gets as its single argument a property list with at
  2411. least the following elements:
  2412. (:type type-of-change :position pos-at-entry-start
  2413. :from old-state :to new-state)
  2414. Depending on the type, more properties may be present.
  2415. This mechanism is currently implemented for:
  2416. TODO state changes
  2417. ------------------
  2418. :type todo-state-change
  2419. :from previous state (keyword as a string), or nil, or a symbol
  2420. `todo' or `done', to indicate the general type of state.
  2421. :to new state, like in :from")
  2422. (defcustom org-enforce-todo-dependencies nil
  2423. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2424. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2425. be blocked if any prior sibling is not yet done.
  2426. Finally, if the parent is blocked because of ordered siblings of its own,
  2427. the child will also be blocked."
  2428. :set (lambda (var val)
  2429. (set var val)
  2430. (if val
  2431. (add-hook 'org-blocker-hook
  2432. 'org-block-todo-from-children-or-siblings-or-parent)
  2433. (remove-hook 'org-blocker-hook
  2434. 'org-block-todo-from-children-or-siblings-or-parent)))
  2435. :group 'org-todo
  2436. :type 'boolean)
  2437. (defcustom org-enforce-todo-checkbox-dependencies nil
  2438. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2439. When this is nil, checkboxes have no influence on switching TODO states.
  2440. When non-nil, you first need to check off all check boxes before the TODO
  2441. entry can be switched to DONE.
  2442. This variable needs to be set before org.el is loaded, and you need to
  2443. restart Emacs after a change to make the change effective. The only way
  2444. to change is while Emacs is running is through the customize interface."
  2445. :set (lambda (var val)
  2446. (set var val)
  2447. (if val
  2448. (add-hook 'org-blocker-hook
  2449. 'org-block-todo-from-checkboxes)
  2450. (remove-hook 'org-blocker-hook
  2451. 'org-block-todo-from-checkboxes)))
  2452. :group 'org-todo
  2453. :type 'boolean)
  2454. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2455. "Non-nil means inserting a TODO heading is treated as state change.
  2456. So when the command `\\[org-insert-todo-heading]' is used, state change
  2457. logging will apply if appropriate. When nil, the new TODO item will
  2458. be inserted directly, and no logging will take place."
  2459. :group 'org-todo
  2460. :type 'boolean)
  2461. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2462. "Non-nil means switching TODO states with S-cursor counts as state change.
  2463. This is the default behavior. However, setting this to nil allows a
  2464. convenient way to select a TODO state and bypass any logging associated
  2465. with that."
  2466. :group 'org-todo
  2467. :type 'boolean)
  2468. (defcustom org-todo-state-tags-triggers nil
  2469. "Tag changes that should be triggered by TODO state changes.
  2470. This is a list. Each entry is
  2471. (state-change (tag . flag) .......)
  2472. State-change can be a string with a state, and empty string to indicate the
  2473. state that has no TODO keyword, or it can be one of the symbols `todo'
  2474. or `done', meaning any not-done or done state, respectively."
  2475. :group 'org-todo
  2476. :group 'org-tags
  2477. :type '(repeat
  2478. (cons (choice :tag "When changing to"
  2479. (const :tag "Not-done state" todo)
  2480. (const :tag "Done state" done)
  2481. (string :tag "State"))
  2482. (repeat
  2483. (cons :tag "Tag action"
  2484. (string :tag "Tag")
  2485. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2486. (defcustom org-log-done nil
  2487. "Information to record when a task moves to the DONE state.
  2488. Possible values are:
  2489. nil Don't add anything, just change the keyword
  2490. time Add a time stamp to the task
  2491. note Prompt for a note and add it with template `org-log-note-headings'
  2492. This option can also be set with on a per-file-basis with
  2493. #+STARTUP: nologdone
  2494. #+STARTUP: logdone
  2495. #+STARTUP: lognotedone
  2496. You can have local logging settings for a subtree by setting the LOGGING
  2497. property to one or more of these keywords."
  2498. :group 'org-todo
  2499. :group 'org-progress
  2500. :type '(choice
  2501. (const :tag "No logging" nil)
  2502. (const :tag "Record CLOSED timestamp" time)
  2503. (const :tag "Record CLOSED timestamp with note." note)))
  2504. ;; Normalize old uses of org-log-done.
  2505. (cond
  2506. ((eq org-log-done t) (setq org-log-done 'time))
  2507. ((and (listp org-log-done) (memq 'done org-log-done))
  2508. (setq org-log-done 'note)))
  2509. (defcustom org-log-reschedule nil
  2510. "Information to record when the scheduling date of a tasks is modified.
  2511. Possible values are:
  2512. nil Don't add anything, just change the date
  2513. time Add a time stamp to the task
  2514. note Prompt for a note and add it with template `org-log-note-headings'
  2515. This option can also be set with on a per-file-basis with
  2516. #+STARTUP: nologreschedule
  2517. #+STARTUP: logreschedule
  2518. #+STARTUP: lognotereschedule"
  2519. :group 'org-todo
  2520. :group 'org-progress
  2521. :type '(choice
  2522. (const :tag "No logging" nil)
  2523. (const :tag "Record timestamp" time)
  2524. (const :tag "Record timestamp with note." note)))
  2525. (defcustom org-log-redeadline nil
  2526. "Information to record when the deadline date of a tasks is modified.
  2527. Possible values are:
  2528. nil Don't add anything, just change the date
  2529. time Add a time stamp to the task
  2530. note Prompt for a note and add it with template `org-log-note-headings'
  2531. This option can also be set with on a per-file-basis with
  2532. #+STARTUP: nologredeadline
  2533. #+STARTUP: logredeadline
  2534. #+STARTUP: lognoteredeadline
  2535. You can have local logging settings for a subtree by setting the LOGGING
  2536. property to one or more of these keywords."
  2537. :group 'org-todo
  2538. :group 'org-progress
  2539. :type '(choice
  2540. (const :tag "No logging" nil)
  2541. (const :tag "Record timestamp" time)
  2542. (const :tag "Record timestamp with note." note)))
  2543. (defcustom org-log-note-clock-out nil
  2544. "Non-nil means record a note when clocking out of an item.
  2545. This can also be configured on a per-file basis by adding one of
  2546. the following lines anywhere in the buffer:
  2547. #+STARTUP: lognoteclock-out
  2548. #+STARTUP: nolognoteclock-out"
  2549. :group 'org-todo
  2550. :group 'org-progress
  2551. :type 'boolean)
  2552. (defcustom org-log-done-with-time t
  2553. "Non-nil means the CLOSED time stamp will contain date and time.
  2554. When nil, only the date will be recorded."
  2555. :group 'org-progress
  2556. :type 'boolean)
  2557. (defcustom org-log-note-headings
  2558. '((done . "CLOSING NOTE %t")
  2559. (state . "State %-12s from %-12S %t")
  2560. (note . "Note taken on %t")
  2561. (reschedule . "Rescheduled from %S on %t")
  2562. (delschedule . "Not scheduled, was %S on %t")
  2563. (redeadline . "New deadline from %S on %t")
  2564. (deldeadline . "Removed deadline, was %S on %t")
  2565. (refile . "Refiled on %t")
  2566. (clock-out . ""))
  2567. "Headings for notes added to entries.
  2568. The value is an alist, with the car being a symbol indicating the
  2569. note context, and the cdr is the heading to be used. The heading
  2570. may also be the empty string. The following placeholders can be
  2571. used:
  2572. %t a time stamp.
  2573. %T an active time stamp instead the default inactive one
  2574. %d a short-format time stamp.
  2575. %D an active short-format time stamp.
  2576. %s the new TODO state or time stamp (inactive), in double quotes.
  2577. %S the old TODO state or time stamp (inactive), in double quotes.
  2578. %u the user name.
  2579. %U full user name.
  2580. In fact, it is not a good idea to change the `state' entry,
  2581. because Agenda Log mode depends on the format of these entries."
  2582. :group 'org-todo
  2583. :group 'org-progress
  2584. :type '(list :greedy t
  2585. (cons (const :tag "Heading when closing an item" done) string)
  2586. (cons (const :tag
  2587. "Heading when changing todo state (todo sequence only)"
  2588. state) string)
  2589. (cons (const :tag "Heading when just taking a note" note) string)
  2590. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2591. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2592. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2593. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2594. (cons (const :tag "Heading when refiling" refile) string)
  2595. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2596. (unless (assq 'note org-log-note-headings)
  2597. (push '(note . "%t") org-log-note-headings))
  2598. (defcustom org-log-into-drawer nil
  2599. "Non-nil means insert state change notes and time stamps into a drawer.
  2600. When nil, state changes notes will be inserted after the headline and
  2601. any scheduling and clock lines, but not inside a drawer.
  2602. The value of this variable should be the name of the drawer to use.
  2603. LOGBOOK is proposed as the default drawer for this purpose, you can
  2604. also set this to a string to define the drawer of your choice.
  2605. A value of t is also allowed, representing \"LOGBOOK\".
  2606. A value of t or nil can also be set with on a per-file-basis with
  2607. #+STARTUP: logdrawer
  2608. #+STARTUP: nologdrawer
  2609. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2610. will be ignored.
  2611. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2612. a subtree.
  2613. Do not check directly this variable in a Lisp program. Call
  2614. function `org-log-into-drawer' instead."
  2615. :group 'org-todo
  2616. :group 'org-progress
  2617. :type '(choice
  2618. (const :tag "Not into a drawer" nil)
  2619. (const :tag "LOGBOOK" t)
  2620. (string :tag "Other")))
  2621. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2622. (defun org-log-into-drawer ()
  2623. "Name of the log drawer, as a string, or nil.
  2624. This is the value of `org-log-into-drawer'. However, if the
  2625. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2626. be used instead of the default value."
  2627. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2628. (cond ((equal p "nil") nil)
  2629. ((equal p "t") "LOGBOOK")
  2630. ((stringp p) p)
  2631. (p "LOGBOOK")
  2632. ((stringp org-log-into-drawer) org-log-into-drawer)
  2633. (org-log-into-drawer "LOGBOOK"))))
  2634. (defcustom org-log-state-notes-insert-after-drawers nil
  2635. "Non-nil means insert state change notes after any drawers in entry.
  2636. Only the drawers that *immediately* follow the headline and the
  2637. deadline/scheduled line are skipped.
  2638. When nil, insert notes right after the heading and perhaps the line
  2639. with deadline/scheduling if present.
  2640. This variable will have no effect if `org-log-into-drawer' is
  2641. set."
  2642. :group 'org-todo
  2643. :group 'org-progress
  2644. :type 'boolean)
  2645. (defcustom org-log-states-order-reversed t
  2646. "Non-nil means the latest state note will be directly after heading.
  2647. When nil, the state change notes will be ordered according to time.
  2648. This option can also be set with on a per-file-basis with
  2649. #+STARTUP: logstatesreversed
  2650. #+STARTUP: nologstatesreversed"
  2651. :group 'org-todo
  2652. :group 'org-progress
  2653. :type 'boolean)
  2654. (defcustom org-todo-repeat-to-state nil
  2655. "The TODO state to which a repeater should return the repeating task.
  2656. By default this is the first task in a TODO sequence, or the previous state
  2657. in a TODO_TYP set. But you can specify another task here.
  2658. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2659. :group 'org-todo
  2660. :version "24.1"
  2661. :type '(choice (const :tag "Head of sequence" nil)
  2662. (string :tag "Specific state")))
  2663. (defcustom org-log-repeat 'time
  2664. "Non-nil means record moving through the DONE state when triggering repeat.
  2665. An auto-repeating task is immediately switched back to TODO when
  2666. marked DONE. If you are not logging state changes (by adding \"@\"
  2667. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2668. record a closing note, there will be no record of the task moving
  2669. through DONE. This variable forces taking a note anyway.
  2670. nil Don't force a record
  2671. time Record a time stamp
  2672. note Prompt for a note and add it with template `org-log-note-headings'
  2673. This option can also be set with on a per-file-basis with
  2674. #+STARTUP: nologrepeat
  2675. #+STARTUP: logrepeat
  2676. #+STARTUP: lognoterepeat
  2677. You can have local logging settings for a subtree by setting the LOGGING
  2678. property to one or more of these keywords."
  2679. :group 'org-todo
  2680. :group 'org-progress
  2681. :type '(choice
  2682. (const :tag "Don't force a record" nil)
  2683. (const :tag "Force recording the DONE state" time)
  2684. (const :tag "Force recording a note with the DONE state" note)))
  2685. (defgroup org-priorities nil
  2686. "Priorities in Org mode."
  2687. :tag "Org Priorities"
  2688. :group 'org-todo)
  2689. (defcustom org-enable-priority-commands t
  2690. "Non-nil means priority commands are active.
  2691. When nil, these commands will be disabled, so that you never accidentally
  2692. set a priority."
  2693. :group 'org-priorities
  2694. :type 'boolean)
  2695. (defcustom org-highest-priority ?A
  2696. "The highest priority of TODO items. A character like ?A, ?B etc.
  2697. Must have a smaller ASCII number than `org-lowest-priority'."
  2698. :group 'org-priorities
  2699. :type 'character)
  2700. (defcustom org-lowest-priority ?C
  2701. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2702. Must have a larger ASCII number than `org-highest-priority'."
  2703. :group 'org-priorities
  2704. :type 'character)
  2705. (defcustom org-default-priority ?B
  2706. "The default priority of TODO items.
  2707. This is the priority an item gets if no explicit priority is given.
  2708. When starting to cycle on an empty priority the first step in the cycle
  2709. depends on `org-priority-start-cycle-with-default'. The resulting first
  2710. step priority must not exceed the range from `org-highest-priority' to
  2711. `org-lowest-priority' which means that `org-default-priority' has to be
  2712. in this range exclusive or inclusive the range boundaries. Else the
  2713. first step refuses to set the default and the second will fall back
  2714. to (depending on the command used) the highest or lowest priority."
  2715. :group 'org-priorities
  2716. :type 'character)
  2717. (defcustom org-priority-start-cycle-with-default t
  2718. "Non-nil means start with default priority when starting to cycle.
  2719. When this is nil, the first step in the cycle will be (depending on the
  2720. command used) one higher or lower than the default priority.
  2721. See also `org-default-priority'."
  2722. :group 'org-priorities
  2723. :type 'boolean)
  2724. (defcustom org-get-priority-function nil
  2725. "Function to extract the priority from a string.
  2726. The string is normally the headline. If this is nil Org computes the
  2727. priority from the priority cookie like [#A] in the headline. It returns
  2728. an integer, increasing by 1000 for each priority level.
  2729. The user can set a different function here, which should take a string
  2730. as an argument and return the numeric priority."
  2731. :group 'org-priorities
  2732. :version "24.1"
  2733. :type '(choice
  2734. (const nil)
  2735. (function)))
  2736. (defgroup org-time nil
  2737. "Options concerning time stamps and deadlines in Org mode."
  2738. :tag "Org Time"
  2739. :group 'org)
  2740. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2741. "Number of minutes to round time stamps to.
  2742. \\<org-mode-map>\
  2743. These are two values, the first applies when first creating a time stamp.
  2744. The second applies when changing it with the commands `S-up' and `S-down'.
  2745. When changing the time stamp, this means that it will change in steps
  2746. of N minutes, as given by the second value.
  2747. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2748. numbers should be factors of 60, so for example 5, 10, 15.
  2749. When this is larger than 1, you can still force an exact time stamp by using
  2750. a double prefix argument to a time stamp command like \
  2751. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2752. and by using a prefix arg to `S-up/down' to specify the exact number
  2753. of minutes to shift."
  2754. :group 'org-time
  2755. :get (lambda (var) ; Make sure both elements are there
  2756. (if (integerp (default-value var))
  2757. (list (default-value var) 5)
  2758. (default-value var)))
  2759. :type '(list
  2760. (integer :tag "when inserting times")
  2761. (integer :tag "when modifying times")))
  2762. ;; Normalize old customizations of this variable.
  2763. (when (integerp org-time-stamp-rounding-minutes)
  2764. (setq org-time-stamp-rounding-minutes
  2765. (list org-time-stamp-rounding-minutes
  2766. org-time-stamp-rounding-minutes)))
  2767. (defcustom org-display-custom-times nil
  2768. "Non-nil means overlay custom formats over all time stamps.
  2769. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2770. To turn this on on a per-file basis, insert anywhere in the file:
  2771. #+STARTUP: customtime"
  2772. :group 'org-time
  2773. :set 'set-default
  2774. :type 'sexp)
  2775. (make-variable-buffer-local 'org-display-custom-times)
  2776. (defcustom org-time-stamp-custom-formats
  2777. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2778. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2779. These are overlaid over the default ISO format if the variable
  2780. `org-display-custom-times' is set. Time like %H:%M should be at the
  2781. end of the second format. The custom formats are also honored by export
  2782. commands, if custom time display is turned on at the time of export."
  2783. :group 'org-time
  2784. :type 'sexp)
  2785. (defun org-time-stamp-format (&optional long inactive)
  2786. "Get the right format for a time string."
  2787. (let ((f (if long (cdr org-time-stamp-formats)
  2788. (car org-time-stamp-formats))))
  2789. (if inactive
  2790. (concat "[" (substring f 1 -1) "]")
  2791. f)))
  2792. (defcustom org-time-clocksum-format
  2793. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2794. "The format string used when creating CLOCKSUM lines.
  2795. This is also used when Org mode generates a time duration.
  2796. The value can be a single format string containing two
  2797. %-sequences, which will be filled with the number of hours and
  2798. minutes in that order.
  2799. Alternatively, the value can be a plist associating any of the
  2800. keys :years, :months, :weeks, :days, :hours or :minutes with
  2801. format strings. The time duration is formatted using only the
  2802. time components that are needed and concatenating the results.
  2803. If a time unit in absent, it falls back to the next smallest
  2804. unit.
  2805. The keys :require-years, :require-months, :require-days,
  2806. :require-weeks, :require-hours, :require-minutes are also
  2807. meaningful. A non-nil value for these keys indicates that the
  2808. corresponding time component should always be included, even if
  2809. its value is 0.
  2810. For example,
  2811. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2812. :require-minutes t)
  2813. means durations longer than a day will be expressed in days,
  2814. hours and minutes, and durations less than a day will always be
  2815. expressed in hours and minutes (even for durations less than an
  2816. hour).
  2817. The value
  2818. (:days \"%dd\" :minutes \"%dm\")
  2819. means durations longer than a day will be expressed in days and
  2820. minutes, and durations less than a day will be expressed entirely
  2821. in minutes (even for durations longer than an hour)."
  2822. :group 'org-time
  2823. :group 'org-clock
  2824. :version "24.4"
  2825. :package-version '(Org . "8.0")
  2826. :type '(choice (string :tag "Format string")
  2827. (set :tag "Plist"
  2828. (group :inline t (const :tag "Years" :years)
  2829. (string :tag "Format string"))
  2830. (group :inline t
  2831. (const :tag "Always show years" :require-years)
  2832. (const t))
  2833. (group :inline t (const :tag "Months" :months)
  2834. (string :tag "Format string"))
  2835. (group :inline t
  2836. (const :tag "Always show months" :require-months)
  2837. (const t))
  2838. (group :inline t (const :tag "Weeks" :weeks)
  2839. (string :tag "Format string"))
  2840. (group :inline t
  2841. (const :tag "Always show weeks" :require-weeks)
  2842. (const t))
  2843. (group :inline t (const :tag "Days" :days)
  2844. (string :tag "Format string"))
  2845. (group :inline t
  2846. (const :tag "Always show days" :require-days)
  2847. (const t))
  2848. (group :inline t (const :tag "Hours" :hours)
  2849. (string :tag "Format string"))
  2850. (group :inline t
  2851. (const :tag "Always show hours" :require-hours)
  2852. (const t))
  2853. (group :inline t (const :tag "Minutes" :minutes)
  2854. (string :tag "Format string"))
  2855. (group :inline t
  2856. (const :tag "Always show minutes" :require-minutes)
  2857. (const t)))))
  2858. (defcustom org-time-clocksum-use-fractional nil
  2859. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2860. See `org-time-clocksum-format' for more on time clock formats."
  2861. :group 'org-time
  2862. :group 'org-clock
  2863. :version "24.3"
  2864. :type 'boolean)
  2865. (defcustom org-time-clocksum-use-effort-durations nil
  2866. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2867. E.g. by default, one day is considered to be a 8 hours effort,
  2868. so a task that has been clocked for 16 hours will be displayed
  2869. as during 2 days in the clock display or in the clocktable.
  2870. See `org-effort-durations' on how to set effort durations
  2871. and `org-time-clocksum-format' for more on time clock formats."
  2872. :group 'org-time
  2873. :group 'org-clock
  2874. :version "24.4"
  2875. :package-version '(Org . "8.0")
  2876. :type 'boolean)
  2877. (defcustom org-time-clocksum-fractional-format "%.2f"
  2878. "The format string used when creating CLOCKSUM lines,
  2879. or when Org mode generates a time duration, if
  2880. `org-time-clocksum-use-fractional' is enabled.
  2881. The value can be a single format string containing one
  2882. %-sequence, which will be filled with the number of hours as
  2883. a float.
  2884. Alternatively, the value can be a plist associating any of the
  2885. keys :years, :months, :weeks, :days, :hours or :minutes with
  2886. a format string. The time duration is formatted using the
  2887. largest time unit which gives a non-zero integer part. If all
  2888. specified formats have zero integer part, the smallest time unit
  2889. is used."
  2890. :group 'org-time
  2891. :type '(choice (string :tag "Format string")
  2892. (set (group :inline t (const :tag "Years" :years)
  2893. (string :tag "Format string"))
  2894. (group :inline t (const :tag "Months" :months)
  2895. (string :tag "Format string"))
  2896. (group :inline t (const :tag "Weeks" :weeks)
  2897. (string :tag "Format string"))
  2898. (group :inline t (const :tag "Days" :days)
  2899. (string :tag "Format string"))
  2900. (group :inline t (const :tag "Hours" :hours)
  2901. (string :tag "Format string"))
  2902. (group :inline t (const :tag "Minutes" :minutes)
  2903. (string :tag "Format string")))))
  2904. (defcustom org-deadline-warning-days 14
  2905. "Number of days before expiration during which a deadline becomes active.
  2906. This variable governs the display in sparse trees and in the agenda.
  2907. When 0 or negative, it means use this number (the absolute value of it)
  2908. even if a deadline has a different individual lead time specified.
  2909. Custom commands can set this variable in the options section."
  2910. :group 'org-time
  2911. :group 'org-agenda-daily/weekly
  2912. :type 'integer)
  2913. (defcustom org-scheduled-delay-days 0
  2914. "Number of days before a scheduled item becomes active.
  2915. This variable governs the display in sparse trees and in the agenda.
  2916. The default value (i.e. 0) means: don't delay scheduled item.
  2917. When negative, it means use this number (the absolute value of it)
  2918. even if a scheduled item has a different individual delay time
  2919. specified.
  2920. Custom commands can set this variable in the options section."
  2921. :group 'org-time
  2922. :group 'org-agenda-daily/weekly
  2923. :version "24.4"
  2924. :package-version '(Org . "8.0")
  2925. :type 'integer)
  2926. (defcustom org-read-date-prefer-future t
  2927. "Non-nil means assume future for incomplete date input from user.
  2928. This affects the following situations:
  2929. 1. The user gives a month but not a year.
  2930. For example, if it is April and you enter \"feb 2\", this will be read
  2931. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2932. 2. The user gives a day, but no month.
  2933. For example, if today is the 15th, and you enter \"3\", Org will read
  2934. this as the third of *next* month. However, if you enter \"17\",
  2935. it will be considered as *this* month.
  2936. If you set this variable to the symbol `time', then also the following
  2937. will work:
  2938. 3. If the user gives a time.
  2939. If the time is before now, it will be interpreted as tomorrow.
  2940. Currently none of this works for ISO week specifications.
  2941. When this option is nil, the current day, month and year will always be
  2942. used as defaults.
  2943. See also `org-agenda-jump-prefer-future'."
  2944. :group 'org-time
  2945. :type '(choice
  2946. (const :tag "Never" nil)
  2947. (const :tag "Check month and day" t)
  2948. (const :tag "Check month, day, and time" time)))
  2949. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2950. "Should the agenda jump command prefer the future for incomplete dates?
  2951. The default is to do the same as configured in `org-read-date-prefer-future'.
  2952. But you can also set a deviating value here.
  2953. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2954. :group 'org-agenda
  2955. :group 'org-time
  2956. :version "24.1"
  2957. :type '(choice
  2958. (const :tag "Use org-read-date-prefer-future"
  2959. org-read-date-prefer-future)
  2960. (const :tag "Never" nil)
  2961. (const :tag "Always" t)))
  2962. (defcustom org-read-date-force-compatible-dates t
  2963. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2964. Depending on the system Emacs is running on, certain dates cannot
  2965. be represented with the type used internally to represent time.
  2966. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2967. correctly. Some systems allow for earlier dates, some for later,
  2968. some for both. One way to find out it to insert any date into an
  2969. Org buffer, putting the cursor on the year and hitting S-up and
  2970. S-down to test the range.
  2971. When this variable is set to t, the date/time prompt will not let
  2972. you specify dates outside the 1970-2037 range, so it is certain that
  2973. these dates will work in whatever version of Emacs you are
  2974. running, and also that you can move a file from one Emacs implementation
  2975. to another. WHenever Org is forcing the year for you, it will display
  2976. a message and beep.
  2977. When this variable is nil, Org will check if the date is
  2978. representable in the specific Emacs implementation you are using.
  2979. If not, it will force a year, usually the current year, and beep
  2980. to remind you. Currently this setting is not recommended because
  2981. the likelihood that you will open your Org files in an Emacs that
  2982. has limited date range is not negligible.
  2983. A workaround for this problem is to use diary sexp dates for time
  2984. stamps outside of this range."
  2985. :group 'org-time
  2986. :version "24.1"
  2987. :type 'boolean)
  2988. (defcustom org-read-date-display-live t
  2989. "Non-nil means display current interpretation of date prompt live.
  2990. This display will be in an overlay, in the minibuffer."
  2991. :group 'org-time
  2992. :type 'boolean)
  2993. (defcustom org-read-date-popup-calendar t
  2994. "Non-nil means pop up a calendar when prompting for a date.
  2995. In the calendar, the date can be selected with mouse-1. However, the
  2996. minibuffer will also be active, and you can simply enter the date as well.
  2997. When nil, only the minibuffer will be available."
  2998. :group 'org-time
  2999. :type 'boolean)
  3000. (defvaralias 'org-popup-calendar-for-date-prompt
  3001. 'org-read-date-popup-calendar)
  3002. (defcustom org-extend-today-until 0
  3003. "The hour when your day really ends. Must be an integer.
  3004. This has influence for the following applications:
  3005. - When switching the agenda to \"today\". It it is still earlier than
  3006. the time given here, the day recognized as TODAY is actually yesterday.
  3007. - When a date is read from the user and it is still before the time given
  3008. here, the current date and time will be assumed to be yesterday, 23:59.
  3009. Also, timestamps inserted in capture templates follow this rule.
  3010. IMPORTANT: This is a feature whose implementation is and likely will
  3011. remain incomplete. Really, it is only here because past midnight seems to
  3012. be the favorite working time of John Wiegley :-)"
  3013. :group 'org-time
  3014. :type 'integer)
  3015. (defcustom org-use-effective-time nil
  3016. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3017. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3018. \"effective time\" of any timestamps between midnight and 8am will be
  3019. 23:59 of the previous day."
  3020. :group 'org-time
  3021. :version "24.1"
  3022. :type 'boolean)
  3023. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3024. "When non-nil, use the last clock out time for `org-todo'.
  3025. Note that this option has precedence over the combined use of
  3026. `org-use-effective-time' and `org-extend-today-until'."
  3027. :group 'org-time
  3028. :version "24.4"
  3029. :package-version '(Org . "8.0")
  3030. :type 'boolean)
  3031. (defcustom org-edit-timestamp-down-means-later nil
  3032. "Non-nil means S-down will increase the time in a time stamp.
  3033. When nil, S-up will increase."
  3034. :group 'org-time
  3035. :type 'boolean)
  3036. (defcustom org-calendar-follow-timestamp-change t
  3037. "Non-nil means make the calendar window follow timestamp changes.
  3038. When a timestamp is modified and the calendar window is visible, it will be
  3039. moved to the new date."
  3040. :group 'org-time
  3041. :type 'boolean)
  3042. (defgroup org-tags nil
  3043. "Options concerning tags in Org mode."
  3044. :tag "Org Tags"
  3045. :group 'org)
  3046. (defcustom org-tag-alist nil
  3047. "Default tags available in Org files.
  3048. The value of this variable is an alist. Associations either:
  3049. (TAG)
  3050. (TAG . SELECT)
  3051. (SPECIAL)
  3052. where TAG is a tag as a string, SELECT is character, used to
  3053. select that tag through the fast tag selection interface, and
  3054. SPECIAL is one of the following keywords: `:startgroup',
  3055. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3056. `:newline'. These keywords are used to define a hierarchy of
  3057. tags. See manual for details.
  3058. When this variable is nil, Org mode bases tag input on what is
  3059. already in the buffer. The value can be overridden locally by
  3060. using a TAGS keyword, e.g.,
  3061. #+TAGS: tag1 tag2
  3062. See also `org-tag-persistent-alist' to sidestep this behavior."
  3063. :group 'org-tags
  3064. :type '(repeat
  3065. (choice
  3066. (cons (string :tag "Tag name")
  3067. (character :tag "Access char"))
  3068. (const :tag "Start radio group" (:startgroup))
  3069. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3070. (const :tag "Group tags delimiter" (:grouptags))
  3071. (const :tag "End radio group" (:endgroup))
  3072. (const :tag "End tag group, non distinct" (:endgrouptag))
  3073. (const :tag "New line" (:newline)))))
  3074. (defcustom org-tag-persistent-alist nil
  3075. "Tags always available in Org files.
  3076. The value of this variable is an alist. Associations either:
  3077. (TAG)
  3078. (TAG . SELECT)
  3079. (SPECIAL)
  3080. where TAG is a tag as a string, SELECT is a character, used to
  3081. select that tag through the fast tag selection interface, and
  3082. SPECIAL is one of the following keywords: `:startgroup',
  3083. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3084. `:newline'. These keywords are used to define a hierarchy of
  3085. tags. See manual for details.
  3086. Unlike to `org-tag-alist', tags defined in this variable do not
  3087. depend on a local TAGS keyword. Instead, to disable these tags
  3088. on a per-file basis, insert anywhere in the file:
  3089. #+STARTUP: noptag"
  3090. :group 'org-tags
  3091. :type '(repeat
  3092. (choice
  3093. (cons (string :tag "Tag name")
  3094. (character :tag "Access char"))
  3095. (const :tag "Start radio group" (:startgroup))
  3096. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3097. (const :tag "Group tags delimiter" (:grouptags))
  3098. (const :tag "End radio group" (:endgroup))
  3099. (const :tag "End tag group, non distinct" (:endgrouptag))
  3100. (const :tag "New line" (:newline)))))
  3101. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3102. "If non-nil, always offer completion for all tags of all agenda files.
  3103. Instead of customizing this variable directly, you might want to
  3104. set it locally for capture buffers, because there no list of
  3105. tags in that file can be created dynamically (there are none).
  3106. (add-hook \\='org-capture-mode-hook
  3107. (lambda ()
  3108. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3109. :group 'org-tags
  3110. :version "24.1"
  3111. :type 'boolean)
  3112. (defvar org-file-tags nil
  3113. "List of tags that can be inherited by all entries in the file.
  3114. The tags will be inherited if the variable `org-use-tag-inheritance'
  3115. says they should be.
  3116. This variable is populated from #+FILETAGS lines.")
  3117. (defcustom org-use-fast-tag-selection 'auto
  3118. "Non-nil means use fast tag selection scheme.
  3119. This is a special interface to select and deselect tags with single keys.
  3120. When nil, fast selection is never used.
  3121. When the symbol `auto', fast selection is used if and only if selection
  3122. characters for tags have been configured, either through the variable
  3123. `org-tag-alist' or through a #+TAGS line in the buffer.
  3124. When t, fast selection is always used and selection keys are assigned
  3125. automatically if necessary."
  3126. :group 'org-tags
  3127. :type '(choice
  3128. (const :tag "Always" t)
  3129. (const :tag "Never" nil)
  3130. (const :tag "When selection characters are configured" auto)))
  3131. (defcustom org-fast-tag-selection-single-key nil
  3132. "Non-nil means fast tag selection exits after first change.
  3133. When nil, you have to press RET to exit it.
  3134. During fast tag selection, you can toggle this flag with `C-c'.
  3135. This variable can also have the value `expert'. In this case, the window
  3136. displaying the tags menu is not even shown, until you press C-c again."
  3137. :group 'org-tags
  3138. :type '(choice
  3139. (const :tag "No" nil)
  3140. (const :tag "Yes" t)
  3141. (const :tag "Expert" expert)))
  3142. (defvar org-fast-tag-selection-include-todo nil
  3143. "Non-nil means fast tags selection interface will also offer TODO states.
  3144. This is an undocumented feature, you should not rely on it.")
  3145. (defcustom org-tags-column -77
  3146. "The column to which tags should be indented in a headline.
  3147. If this number is positive, it specifies the column. If it is negative,
  3148. it means that the tags should be flushright to that column. For example,
  3149. -80 works well for a normal 80 character screen.
  3150. When 0, place tags directly after headline text, with only one space in
  3151. between."
  3152. :group 'org-tags
  3153. :type 'integer)
  3154. (defcustom org-auto-align-tags t
  3155. "Non-nil keeps tags aligned when modifying headlines.
  3156. Some operations (i.e. demoting) change the length of a headline and
  3157. therefore shift the tags around. With this option turned on, after
  3158. each such operation the tags are again aligned to `org-tags-column'."
  3159. :group 'org-tags
  3160. :type 'boolean)
  3161. (defcustom org-use-tag-inheritance t
  3162. "Non-nil means tags in levels apply also for sublevels.
  3163. When nil, only the tags directly given in a specific line apply there.
  3164. This may also be a list of tags that should be inherited, or a regexp that
  3165. matches tags that should be inherited. Additional control is possible
  3166. with the variable `org-tags-exclude-from-inheritance' which gives an
  3167. explicit list of tags to be excluded from inheritance, even if the value of
  3168. `org-use-tag-inheritance' would select it for inheritance.
  3169. If this option is t, a match early-on in a tree can lead to a large
  3170. number of matches in the subtree when constructing the agenda or creating
  3171. a sparse tree. If you only want to see the first match in a tree during
  3172. a search, check out the variable `org-tags-match-list-sublevels'."
  3173. :group 'org-tags
  3174. :type '(choice
  3175. (const :tag "Not" nil)
  3176. (const :tag "Always" t)
  3177. (repeat :tag "Specific tags" (string :tag "Tag"))
  3178. (regexp :tag "Tags matched by regexp")))
  3179. (defcustom org-tags-exclude-from-inheritance nil
  3180. "List of tags that should never be inherited.
  3181. This is a way to exclude a few tags from inheritance. For way to do
  3182. the opposite, to actively allow inheritance for selected tags,
  3183. see the variable `org-use-tag-inheritance'."
  3184. :group 'org-tags
  3185. :type '(repeat (string :tag "Tag")))
  3186. (defun org-tag-inherit-p (tag)
  3187. "Check if TAG is one that should be inherited."
  3188. (cond
  3189. ((member tag org-tags-exclude-from-inheritance) nil)
  3190. ((eq org-use-tag-inheritance t) t)
  3191. ((not org-use-tag-inheritance) nil)
  3192. ((stringp org-use-tag-inheritance)
  3193. (string-match org-use-tag-inheritance tag))
  3194. ((listp org-use-tag-inheritance)
  3195. (member tag org-use-tag-inheritance))
  3196. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3197. (defcustom org-tags-match-list-sublevels t
  3198. "Non-nil means list also sublevels of headlines matching a search.
  3199. This variable applies to tags/property searches, and also to stuck
  3200. projects because this search is based on a tags match as well.
  3201. When set to the symbol `indented', sublevels are indented with
  3202. leading dots.
  3203. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3204. the sublevels of a headline matching a tag search often also match
  3205. the same search. Listing all of them can create very long lists.
  3206. Setting this variable to nil causes subtrees of a match to be skipped.
  3207. This variable is semi-obsolete and probably should always be true. It
  3208. is better to limit inheritance to certain tags using the variables
  3209. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3210. :group 'org-tags
  3211. :type '(choice
  3212. (const :tag "No, don't list them" nil)
  3213. (const :tag "Yes, do list them" t)
  3214. (const :tag "List them, indented with leading dots" indented)))
  3215. (defcustom org-tags-sort-function nil
  3216. "When set, tags are sorted using this function as a comparator."
  3217. :group 'org-tags
  3218. :type '(choice
  3219. (const :tag "No sorting" nil)
  3220. (const :tag "Alphabetical" string<)
  3221. (const :tag "Reverse alphabetical" string>)
  3222. (function :tag "Custom function" nil)))
  3223. (defvar org-tags-history nil
  3224. "History of minibuffer reads for tags.")
  3225. (defvar org-last-tags-completion-table nil
  3226. "The last used completion table for tags.")
  3227. (defvar org-after-tags-change-hook nil
  3228. "Hook that is run after the tags in a line have changed.")
  3229. (defgroup org-properties nil
  3230. "Options concerning properties in Org mode."
  3231. :tag "Org Properties"
  3232. :group 'org)
  3233. (defcustom org-property-format "%-10s %s"
  3234. "How property key/value pairs should be formatted by `indent-line'.
  3235. When `indent-line' hits a property definition, it will format the line
  3236. according to this format, mainly to make sure that the values are
  3237. lined-up with respect to each other."
  3238. :group 'org-properties
  3239. :type 'string)
  3240. (defcustom org-properties-postprocess-alist nil
  3241. "Alist of properties and functions to adjust inserted values.
  3242. Elements of this alist must be of the form
  3243. ([string] [function])
  3244. where [string] must be a property name and [function] must be a
  3245. lambda expression: this lambda expression must take one argument,
  3246. the value to adjust, and return the new value as a string.
  3247. For example, this element will allow the property \"Remaining\"
  3248. to be updated wrt the relation between the \"Effort\" property
  3249. and the clock summary:
  3250. ((\"Remaining\" (lambda(value)
  3251. (let ((clocksum (org-clock-sum-current-item))
  3252. (effort (org-duration-string-to-minutes
  3253. (org-entry-get (point) \"Effort\"))))
  3254. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3255. :group 'org-properties
  3256. :version "24.1"
  3257. :type '(alist :key-type (string :tag "Property")
  3258. :value-type (function :tag "Function")))
  3259. (defcustom org-use-property-inheritance nil
  3260. "Non-nil means properties apply also for sublevels.
  3261. This setting is chiefly used during property searches. Turning it on can
  3262. cause significant overhead when doing a search, which is why it is not
  3263. on by default.
  3264. When nil, only the properties directly given in the current entry count.
  3265. When t, every property is inherited. The value may also be a list of
  3266. properties that should have inheritance, or a regular expression matching
  3267. properties that should be inherited.
  3268. However, note that some special properties use inheritance under special
  3269. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3270. and the properties ending in \"_ALL\" when they are used as descriptor
  3271. for valid values of a property.
  3272. Note for programmers:
  3273. When querying an entry with `org-entry-get', you can control if inheritance
  3274. should be used. By default, `org-entry-get' looks only at the local
  3275. properties. You can request inheritance by setting the inherit argument
  3276. to t (to force inheritance) or to `selective' (to respect the setting
  3277. in this variable)."
  3278. :group 'org-properties
  3279. :type '(choice
  3280. (const :tag "Not" nil)
  3281. (const :tag "Always" t)
  3282. (repeat :tag "Specific properties" (string :tag "Property"))
  3283. (regexp :tag "Properties matched by regexp")))
  3284. (defun org-property-inherit-p (property)
  3285. "Check if PROPERTY is one that should be inherited."
  3286. (cond
  3287. ((eq org-use-property-inheritance t) t)
  3288. ((not org-use-property-inheritance) nil)
  3289. ((stringp org-use-property-inheritance)
  3290. (string-match org-use-property-inheritance property))
  3291. ((listp org-use-property-inheritance)
  3292. (member property org-use-property-inheritance))
  3293. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3294. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3295. "The default column format, if no other format has been defined.
  3296. This variable can be set on the per-file basis by inserting a line
  3297. #+COLUMNS: %25ITEM ....."
  3298. :group 'org-properties
  3299. :type 'string)
  3300. (defcustom org-columns-ellipses ".."
  3301. "The ellipses to be used when a field in column view is truncated.
  3302. When this is the empty string, as many characters as possible are shown,
  3303. but then there will be no visual indication that the field has been truncated.
  3304. When this is a string of length N, the last N characters of a truncated
  3305. field are replaced by this string. If the column is narrower than the
  3306. ellipses string, only part of the ellipses string will be shown."
  3307. :group 'org-properties
  3308. :type 'string)
  3309. (defconst org-global-properties-fixed
  3310. '(("VISIBILITY_ALL" . "folded children content all")
  3311. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3312. "List of property/value pairs that can be inherited by any entry.
  3313. These are fixed values, for the preset properties. The user variable
  3314. that can be used to add to this list is `org-global-properties'.
  3315. The entries in this list are cons cells where the car is a property
  3316. name and cdr is a string with the value. If the value represents
  3317. multiple items like an \"_ALL\" property, separate the items by
  3318. spaces.")
  3319. (defcustom org-global-properties nil
  3320. "List of property/value pairs that can be inherited by any entry.
  3321. This list will be combined with the constant `org-global-properties-fixed'.
  3322. The entries in this list are cons cells where the car is a property
  3323. name and cdr is a string with the value.
  3324. You can set buffer-local values for the same purpose in the variable
  3325. `org-file-properties' this by adding lines like
  3326. #+PROPERTY: NAME VALUE"
  3327. :group 'org-properties
  3328. :type '(repeat
  3329. (cons (string :tag "Property")
  3330. (string :tag "Value"))))
  3331. (defvar-local org-file-properties nil
  3332. "List of property/value pairs that can be inherited by any entry.
  3333. Valid for the current buffer.
  3334. This variable is populated from #+PROPERTY lines.")
  3335. (defgroup org-agenda nil
  3336. "Options concerning agenda views in Org mode."
  3337. :tag "Org Agenda"
  3338. :group 'org)
  3339. (defvar-local org-category nil
  3340. "Variable used by org files to set a category for agenda display.
  3341. Such files should use a file variable to set it, for example
  3342. # -*- mode: org; org-category: \"ELisp\"
  3343. or contain a special line
  3344. #+CATEGORY: ELisp
  3345. If the file does not specify a category, then file's base name
  3346. is used instead.")
  3347. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3348. (defcustom org-agenda-files nil
  3349. "The files to be used for agenda display.
  3350. If an entry is a directory, all files in that directory that are matched
  3351. by `org-agenda-file-regexp' will be part of the file list.
  3352. If the value of the variable is not a list but a single file name, then
  3353. the list of agenda files is actually stored and maintained in that file,
  3354. one agenda file per line. In this file paths can be given relative to
  3355. `org-directory'. Tilde expansion and environment variable substitution
  3356. are also made.
  3357. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3358. and removed with `\\[org-remove-file]'."
  3359. :group 'org-agenda
  3360. :type '(choice
  3361. (repeat :tag "List of files and directories" file)
  3362. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3363. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3364. "Regular expression to match files for `org-agenda-files'.
  3365. If any element in the list in that variable contains a directory instead
  3366. of a normal file, all files in that directory that are matched by this
  3367. regular expression will be included."
  3368. :group 'org-agenda
  3369. :type 'regexp)
  3370. (defcustom org-agenda-text-search-extra-files nil
  3371. "List of extra files to be searched by text search commands.
  3372. These files will be searched in addition to the agenda files by the
  3373. commands `org-search-view' (`\\[org-agenda] s') \
  3374. and `org-occur-in-agenda-files'.
  3375. Note that these files will only be searched for text search commands,
  3376. not for the other agenda views like todo lists, tag searches or the weekly
  3377. agenda. This variable is intended to list notes and possibly archive files
  3378. that should also be searched by these two commands.
  3379. In fact, if the first element in the list is the symbol `agenda-archives',
  3380. then all archive files of all agenda files will be added to the search
  3381. scope."
  3382. :group 'org-agenda
  3383. :type '(set :greedy t
  3384. (const :tag "Agenda Archives" agenda-archives)
  3385. (repeat :inline t (file))))
  3386. (defvaralias 'org-agenda-multi-occur-extra-files
  3387. 'org-agenda-text-search-extra-files)
  3388. (defcustom org-agenda-skip-unavailable-files nil
  3389. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3390. A nil value means to remove them, after a query, from the list."
  3391. :group 'org-agenda
  3392. :type 'boolean)
  3393. (defcustom org-calendar-to-agenda-key [?c]
  3394. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3395. The command `org-calendar-goto-agenda' will be bound to this key. The
  3396. default is the character `c' because then `c' can be used to switch back and
  3397. forth between agenda and calendar."
  3398. :group 'org-agenda
  3399. :type 'sexp)
  3400. (defcustom org-calendar-insert-diary-entry-key [?i]
  3401. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3402. This option is irrelevant until `org-agenda-diary-file' has been configured
  3403. to point to an Org file. When that is the case, the command
  3404. `org-agenda-diary-entry' will be bound to the key given here, by default
  3405. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3406. if you want to continue doing this, you need to change this to a different
  3407. key."
  3408. :group 'org-agenda
  3409. :type 'sexp)
  3410. (defcustom org-agenda-diary-file 'diary-file
  3411. "File to which to add new entries with the `i' key in agenda and calendar.
  3412. When this is the symbol `diary-file', the functionality in the Emacs
  3413. calendar will be used to add entries to the `diary-file'. But when this
  3414. points to a file, `org-agenda-diary-entry' will be used instead."
  3415. :group 'org-agenda
  3416. :type '(choice
  3417. (const :tag "The standard Emacs diary file" diary-file)
  3418. (file :tag "Special Org file diary entries")))
  3419. (eval-after-load "calendar"
  3420. '(progn
  3421. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3422. 'org-calendar-goto-agenda)
  3423. (add-hook 'calendar-mode-hook
  3424. (lambda ()
  3425. (unless (eq org-agenda-diary-file 'diary-file)
  3426. (define-key calendar-mode-map
  3427. org-calendar-insert-diary-entry-key
  3428. 'org-agenda-diary-entry))))))
  3429. (defgroup org-latex nil
  3430. "Options for embedding LaTeX code into Org mode."
  3431. :tag "Org LaTeX"
  3432. :group 'org)
  3433. (defcustom org-format-latex-options
  3434. '(:foreground default :background default :scale 1.0
  3435. :html-foreground "Black" :html-background "Transparent"
  3436. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3437. "Options for creating images from LaTeX fragments.
  3438. This is a property list with the following properties:
  3439. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3440. `default' means use the foreground of the default face.
  3441. `auto' means use the foreground from the text face.
  3442. :background the background color, or \"Transparent\".
  3443. `default' means use the background of the default face.
  3444. `auto' means use the background from the text face.
  3445. :scale a scaling factor for the size of the images, to get more pixels
  3446. :html-foreground, :html-background, :html-scale
  3447. the same numbers for HTML export.
  3448. :matchers a list indicating which matchers should be used to
  3449. find LaTeX fragments. Valid members of this list are:
  3450. \"begin\" find environments
  3451. \"$1\" find single characters surrounded by $.$
  3452. \"$\" find math expressions surrounded by $...$
  3453. \"$$\" find math expressions surrounded by $$....$$
  3454. \"\\(\" find math expressions surrounded by \\(...\\)
  3455. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3456. :group 'org-latex
  3457. :type 'plist)
  3458. (defcustom org-format-latex-signal-error t
  3459. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3460. When nil, just push out a message."
  3461. :group 'org-latex
  3462. :version "24.1"
  3463. :type 'boolean)
  3464. (defcustom org-latex-to-mathml-jar-file nil
  3465. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3466. Use this to specify additional executable file say a jar file.
  3467. When using MathToWeb as the converter, specify the full-path to
  3468. your mathtoweb.jar file."
  3469. :group 'org-latex
  3470. :version "24.1"
  3471. :type '(choice
  3472. (const :tag "None" nil)
  3473. (file :tag "JAR file" :must-match t)))
  3474. (defcustom org-latex-to-mathml-convert-command nil
  3475. "Command to convert LaTeX fragments to MathML.
  3476. Replace format-specifiers in the command as noted below and use
  3477. `shell-command' to convert LaTeX to MathML.
  3478. %j: Executable file in fully expanded form as specified by
  3479. `org-latex-to-mathml-jar-file'.
  3480. %I: Input LaTeX file in fully expanded form.
  3481. %i: The latex fragment to be converted.
  3482. %o: Output MathML file.
  3483. This command is used by `org-create-math-formula'.
  3484. When using MathToWeb as the converter, set this option to
  3485. \"java -jar %j -unicode -force -df %o %I\".
  3486. When using LaTeXML set this option to
  3487. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3488. :group 'org-latex
  3489. :version "24.1"
  3490. :type '(choice
  3491. (const :tag "None" nil)
  3492. (string :tag "\nShell command")))
  3493. (defcustom org-preview-latex-default-process 'dvipng
  3494. "The default process to convert LaTeX fragments to image files.
  3495. All available processes and theirs documents can be found in
  3496. `org-preview-latex-process-alist', which see."
  3497. :group 'org-latex
  3498. :version "25.2"
  3499. :package-version '(Org . "9.0")
  3500. :type 'symbol)
  3501. (defcustom org-preview-latex-process-alist
  3502. '((dvipng
  3503. :programs ("latex" "dvipng")
  3504. :description "dvi > png"
  3505. :message "you need to install the programs: latex and dvipng."
  3506. :image-input-type "dvi"
  3507. :image-output-type "png"
  3508. :image-size-adjust (1.0 . 1.0)
  3509. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3510. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %o%b.png %f"))
  3511. (dvisvgm
  3512. :programs ("latex" "dvisvgm")
  3513. :description "dvi > svg"
  3514. :message "you need to install the programs: latex and dvisvgm."
  3515. :use-xcolor t
  3516. :image-input-type "dvi"
  3517. :image-output-type "svg"
  3518. :image-size-adjust (1.7 . 1.5)
  3519. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3520. :image-converter ("dvisvgm %f -n -b min -c %S -o %o%b.svg"))
  3521. (imagemagick
  3522. :programs ("latex" "convert")
  3523. :description "pdf > png"
  3524. :message "you need to install the programs: latex and imagemagick."
  3525. :use-xcolor t
  3526. :image-input-type "pdf"
  3527. :image-output-type "png"
  3528. :image-size-adjust (1.0 . 1.0)
  3529. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3530. :image-converter
  3531. ("convert -density %D -trim -antialias %f -quality 100 %o%b.png")))
  3532. "Definitions of external processes for LaTeX previewing.
  3533. Org mode can use some external commands to generate TeX snippet's images for
  3534. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3535. `org-create-formula-image' how to call them.
  3536. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3537. PROPERTIES accepts the following attributes:
  3538. :programs list of strings, required programs.
  3539. :description string, describe the process.
  3540. :message string, message it when required programs cannot be found.
  3541. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3542. :image-output-type string, output file type of image converter (e.g., \"png\").
  3543. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3544. deal with background and foreground color of image.
  3545. Otherwise, dvipng style background and foregroud color
  3546. format are generated. You may then refer to them in
  3547. command options with \"%F\" and \"%B\".
  3548. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3549. image size showed in buffer and the cdr element is for
  3550. HTML file. This option is only useful for process
  3551. developers, users should use variable
  3552. `org-format-latex-options' instead.
  3553. :post-clean list of strings, files matched are to be cleaned up once
  3554. the image is generated. When nil, the files with \".dvi\",
  3555. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3556. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3557. be cleaned up.
  3558. :latex-header list of strings, the LaTeX header of the snippet file.
  3559. When nil, the fallback value is used instead, which is
  3560. controlled by `org-format-latex-header',
  3561. `org-latex-default-packages-alist' and
  3562. `org-latex-packages-alist', which see.
  3563. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3564. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3565. replaced with values defined below.
  3566. :image-converter list of image converter commands strings. Each of them is
  3567. given to the shell and supports any of the following
  3568. place-holders defined below.
  3569. Place-holders used by `:image-converter' and `:latex-compiler':
  3570. %f input file name.
  3571. %b base name of input file.
  3572. %o base directory of input file.
  3573. Place-holders only used by `:image-converter':
  3574. %F foreground of image
  3575. %B background of image
  3576. %D dpi, which is used to adjust image size by some processing commands.
  3577. %S the image size scale ratio, which is used to adjust image size by some
  3578. processing commands."
  3579. :group 'org-latex
  3580. :version "25.2"
  3581. :package-version '(Org . "9.0")
  3582. :type '(alist :tag "LaTeX to image backends"
  3583. :value-type (plist)))
  3584. (defcustom org-preview-latex-image-directory "ltximg/"
  3585. "Path to store latex preview images.
  3586. A relative path here creates many directories relative to the
  3587. processed org files paths. An absolute path puts all preview
  3588. images at the same place."
  3589. :group 'org-latex
  3590. :version "25.2"
  3591. :package-version '(Org . "9.0")
  3592. :type 'string)
  3593. (defun org-format-latex-mathml-available-p ()
  3594. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3595. (save-match-data
  3596. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3597. org-latex-to-mathml-convert-command)
  3598. (let ((executable (car (split-string
  3599. org-latex-to-mathml-convert-command))))
  3600. (when (executable-find executable)
  3601. (if (string-match
  3602. "%j" org-latex-to-mathml-convert-command)
  3603. (file-readable-p org-latex-to-mathml-jar-file)
  3604. t))))))
  3605. (defcustom org-format-latex-header "\\documentclass{article}
  3606. \\usepackage[usenames]{color}
  3607. \[PACKAGES]
  3608. \[DEFAULT-PACKAGES]
  3609. \\pagestyle{empty} % do not remove
  3610. % The settings below are copied from fullpage.sty
  3611. \\setlength{\\textwidth}{\\paperwidth}
  3612. \\addtolength{\\textwidth}{-3cm}
  3613. \\setlength{\\oddsidemargin}{1.5cm}
  3614. \\addtolength{\\oddsidemargin}{-2.54cm}
  3615. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3616. \\setlength{\\textheight}{\\paperheight}
  3617. \\addtolength{\\textheight}{-\\headheight}
  3618. \\addtolength{\\textheight}{-\\headsep}
  3619. \\addtolength{\\textheight}{-\\footskip}
  3620. \\addtolength{\\textheight}{-3cm}
  3621. \\setlength{\\topmargin}{1.5cm}
  3622. \\addtolength{\\topmargin}{-2.54cm}"
  3623. "The document header used for processing LaTeX fragments.
  3624. It is imperative that this header make sure that no page number
  3625. appears on the page. The package defined in the variables
  3626. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3627. will either replace the placeholder \"[PACKAGES]\" in this
  3628. header, or they will be appended."
  3629. :group 'org-latex
  3630. :type 'string)
  3631. (defun org-set-packages-alist (var val)
  3632. "Set the packages alist and make sure it has 3 elements per entry."
  3633. (set var (mapcar (lambda (x)
  3634. (if (and (consp x) (= (length x) 2))
  3635. (list (car x) (nth 1 x) t)
  3636. x))
  3637. val)))
  3638. (defun org-get-packages-alist (var)
  3639. "Get the packages alist and make sure it has 3 elements per entry."
  3640. (mapcar (lambda (x)
  3641. (if (and (consp x) (= (length x) 2))
  3642. (list (car x) (nth 1 x) t)
  3643. x))
  3644. (default-value var)))
  3645. (defcustom org-latex-default-packages-alist
  3646. '(("AUTO" "inputenc" t ("pdflatex"))
  3647. ("T1" "fontenc" t ("pdflatex"))
  3648. ("" "graphicx" t)
  3649. ("" "grffile" t)
  3650. ("" "longtable" nil)
  3651. ("" "wrapfig" nil)
  3652. ("" "rotating" nil)
  3653. ("normalem" "ulem" t)
  3654. ("" "amsmath" t)
  3655. ("" "textcomp" t)
  3656. ("" "amssymb" t)
  3657. ("" "capt-of" nil)
  3658. ("" "hyperref" nil))
  3659. "Alist of default packages to be inserted in the header.
  3660. Change this only if one of the packages here causes an
  3661. incompatibility with another package you are using.
  3662. The packages in this list are needed by one part or another of
  3663. Org mode to function properly:
  3664. - inputenc, fontenc: for basic font and character selection
  3665. - graphicx: for including images
  3666. - grffile: allow periods and spaces in graphics file names
  3667. - longtable: For multipage tables
  3668. - wrapfig: for figure placement
  3669. - rotating: for sideways figures and tables
  3670. - ulem: for underline and strike-through
  3671. - amsmath: for subscript and superscript and math environments
  3672. - textcomp, amssymb: for various symbols used
  3673. for interpreting the entities in `org-entities'. You can skip
  3674. some of these packages if you don't use any of their symbols.
  3675. - capt-of: for captions outside of floats
  3676. - hyperref: for cross references
  3677. Therefore you should not modify this variable unless you know
  3678. what you are doing. The one reason to change it anyway is that
  3679. you might be loading some other package that conflicts with one
  3680. of the default packages. Each element is either a cell or
  3681. a string.
  3682. A cell is of the format
  3683. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3684. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3685. when compiling LaTeX snippets into images for inclusion into
  3686. non-LaTeX output. COMPILERS is a list of compilers that should
  3687. include the package, see `org-latex-compiler'. If the document
  3688. compiler is not in the list, and the list is non-nil, the package
  3689. will not be inserted in the final document.
  3690. A string will be inserted as-is in the header of the document."
  3691. :group 'org-latex
  3692. :group 'org-export-latex
  3693. :set 'org-set-packages-alist
  3694. :get 'org-get-packages-alist
  3695. :version "25.2"
  3696. :package-version '(Org . "8.3")
  3697. :type '(repeat
  3698. (choice
  3699. (list :tag "options/package pair"
  3700. (string :tag "options")
  3701. (string :tag "package")
  3702. (boolean :tag "Snippet"))
  3703. (string :tag "A line of LaTeX"))))
  3704. (defcustom org-latex-packages-alist nil
  3705. "Alist of packages to be inserted in every LaTeX header.
  3706. These will be inserted after `org-latex-default-packages-alist'.
  3707. Each element is either a cell or a string.
  3708. A cell is of the format:
  3709. (\"options\" \"package\" SNIPPET-FLAG)
  3710. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3711. needed when turning LaTeX snippets into images for inclusion into
  3712. non-LaTeX output.
  3713. A string will be inserted as-is in the header of the document.
  3714. Make sure that you only list packages here which:
  3715. - you want in every file;
  3716. - do not conflict with the setup in `org-format-latex-header';
  3717. - do not conflict with the default packages in
  3718. `org-latex-default-packages-alist'."
  3719. :group 'org-latex
  3720. :group 'org-export-latex
  3721. :set 'org-set-packages-alist
  3722. :get 'org-get-packages-alist
  3723. :type '(repeat
  3724. (choice
  3725. (list :tag "options/package pair"
  3726. (string :tag "options")
  3727. (string :tag "package")
  3728. (boolean :tag "Snippet"))
  3729. (string :tag "A line of LaTeX"))))
  3730. (defgroup org-appearance nil
  3731. "Settings for Org mode appearance."
  3732. :tag "Org Appearance"
  3733. :group 'org)
  3734. (defcustom org-level-color-stars-only nil
  3735. "Non-nil means fontify only the stars in each headline.
  3736. When nil, the entire headline is fontified.
  3737. Changing it requires restart of `font-lock-mode' to become effective
  3738. also in regions already fontified."
  3739. :group 'org-appearance
  3740. :type 'boolean)
  3741. (defcustom org-hide-leading-stars nil
  3742. "Non-nil means hide the first N-1 stars in a headline.
  3743. This works by using the face `org-hide' for these stars. This
  3744. face is white for a light background, and black for a dark
  3745. background. You may have to customize the face `org-hide' to
  3746. make this work.
  3747. Changing it requires restart of `font-lock-mode' to become effective
  3748. also in regions already fontified.
  3749. You may also set this on a per-file basis by adding one of the following
  3750. lines to the buffer:
  3751. #+STARTUP: hidestars
  3752. #+STARTUP: showstars"
  3753. :group 'org-appearance
  3754. :type 'boolean)
  3755. (defcustom org-hidden-keywords nil
  3756. "List of symbols corresponding to keywords to be hidden the org buffer.
  3757. For example, a value \\='(title) for this list will make the document's title
  3758. appear in the buffer without the initial #+TITLE: keyword."
  3759. :group 'org-appearance
  3760. :version "24.1"
  3761. :type '(set (const :tag "#+AUTHOR" author)
  3762. (const :tag "#+DATE" date)
  3763. (const :tag "#+EMAIL" email)
  3764. (const :tag "#+TITLE" title)))
  3765. (defcustom org-custom-properties nil
  3766. "List of properties (as strings) with a special meaning.
  3767. The default use of these custom properties is to let the user
  3768. hide them with `org-toggle-custom-properties-visibility'."
  3769. :group 'org-properties
  3770. :group 'org-appearance
  3771. :version "24.3"
  3772. :type '(repeat (string :tag "Property Name")))
  3773. (defcustom org-fontify-done-headline nil
  3774. "Non-nil means change the face of a headline if it is marked DONE.
  3775. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3776. When this is non-nil, the headline after the keyword is set to the
  3777. `org-headline-done' as an additional indication."
  3778. :group 'org-appearance
  3779. :type 'boolean)
  3780. (defcustom org-fontify-emphasized-text t
  3781. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3782. Changing this variable requires a restart of Emacs to take effect."
  3783. :group 'org-appearance
  3784. :type 'boolean)
  3785. (defcustom org-fontify-whole-heading-line nil
  3786. "Non-nil means fontify the whole line for headings.
  3787. This is useful when setting a background color for the
  3788. org-level-* faces."
  3789. :group 'org-appearance
  3790. :type 'boolean)
  3791. (defcustom org-highlight-latex-and-related nil
  3792. "Non-nil means highlight LaTeX related syntax in the buffer.
  3793. When non nil, the value should be a list containing any of the
  3794. following symbols:
  3795. `latex' Highlight LaTeX snippets and environments.
  3796. `script' Highlight subscript and superscript.
  3797. `entities' Highlight entities."
  3798. :group 'org-appearance
  3799. :version "24.4"
  3800. :package-version '(Org . "8.0")
  3801. :type '(choice
  3802. (const :tag "No highlighting" nil)
  3803. (set :greedy t :tag "Highlight"
  3804. (const :tag "LaTeX snippets and environments" latex)
  3805. (const :tag "Subscript and superscript" script)
  3806. (const :tag "Entities" entities))))
  3807. (defcustom org-hide-emphasis-markers nil
  3808. "Non-nil mean font-lock should hide the emphasis marker characters."
  3809. :group 'org-appearance
  3810. :type 'boolean)
  3811. (defcustom org-hide-macro-markers nil
  3812. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3813. :group 'org-appearance
  3814. :type 'boolean)
  3815. (defcustom org-pretty-entities nil
  3816. "Non-nil means show entities as UTF8 characters.
  3817. When nil, the \\name form remains in the buffer."
  3818. :group 'org-appearance
  3819. :version "24.1"
  3820. :type 'boolean)
  3821. (defcustom org-pretty-entities-include-sub-superscripts t
  3822. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3823. :group 'org-appearance
  3824. :version "24.1"
  3825. :type 'boolean)
  3826. (defvar org-emph-re nil
  3827. "Regular expression for matching emphasis.
  3828. After a match, the match groups contain these elements:
  3829. 0 The match of the full regular expression, including the characters
  3830. before and after the proper match
  3831. 1 The character before the proper match, or empty at beginning of line
  3832. 2 The proper match, including the leading and trailing markers
  3833. 3 The leading marker like * or /, indicating the type of highlighting
  3834. 4 The text between the emphasis markers, not including the markers
  3835. 5 The character after the match, empty at the end of a line")
  3836. (defvar org-verbatim-re nil
  3837. "Regular expression for matching verbatim text.")
  3838. (defvar org-emphasis-regexp-components) ; defined just below
  3839. (defvar org-emphasis-alist) ; defined just below
  3840. (defun org-set-emph-re (var val)
  3841. "Set variable and compute the emphasis regular expression."
  3842. (set var val)
  3843. (when (and (boundp 'org-emphasis-alist)
  3844. (boundp 'org-emphasis-regexp-components)
  3845. org-emphasis-alist org-emphasis-regexp-components)
  3846. (let* ((e org-emphasis-regexp-components)
  3847. (pre (car e))
  3848. (post (nth 1 e))
  3849. (border (nth 2 e))
  3850. (body (nth 3 e))
  3851. (nl (nth 4 e))
  3852. (body1 (concat body "*?"))
  3853. (markers (mapconcat 'car org-emphasis-alist ""))
  3854. (vmarkers (mapconcat
  3855. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3856. org-emphasis-alist "")))
  3857. ;; make sure special characters appear at the right position in the class
  3858. (if (string-match "\\^" markers)
  3859. (setq markers (concat (replace-match "" t t markers) "^")))
  3860. (if (string-match "-" markers)
  3861. (setq markers (concat (replace-match "" t t markers) "-")))
  3862. (if (string-match "\\^" vmarkers)
  3863. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3864. (if (string-match "-" vmarkers)
  3865. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3866. (if (> nl 0)
  3867. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3868. (int-to-string nl) "\\}")))
  3869. ;; Make the regexp
  3870. (setq org-emph-re
  3871. (concat "\\([" pre "]\\|^\\)"
  3872. "\\("
  3873. "\\([" markers "]\\)"
  3874. "\\("
  3875. "[^" border "]\\|"
  3876. "[^" border "]"
  3877. body1
  3878. "[^" border "]"
  3879. "\\)"
  3880. "\\3\\)"
  3881. "\\([" post "]\\|$\\)"))
  3882. (setq org-verbatim-re
  3883. (concat "\\([" pre "]\\|^\\)"
  3884. "\\("
  3885. "\\([" vmarkers "]\\)"
  3886. "\\("
  3887. "[^" border "]\\|"
  3888. "[^" border "]"
  3889. body1
  3890. "[^" border "]"
  3891. "\\)"
  3892. "\\3\\)"
  3893. "\\([" post "]\\|$\\)")))))
  3894. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3895. ;; set this option proved cumbersome. See this message/thread:
  3896. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3897. (defvar org-emphasis-regexp-components
  3898. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3899. "Components used to build the regular expression for emphasis.
  3900. This is a list with five entries. Terminology: In an emphasis string
  3901. like \" *strong word* \", we call the initial space PREMATCH, the final
  3902. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3903. and \"trong wor\" is the body. The different components in this variable
  3904. specify what is allowed/forbidden in each part:
  3905. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3906. post Chars allowed as postmatch. End of line will be allowed too.
  3907. border The chars *forbidden* as border characters.
  3908. body-regexp A regexp like \".\" to match a body character. Don't use
  3909. non-shy groups here, and don't allow newline here.
  3910. newline The maximum number of newlines allowed in an emphasis exp.
  3911. You need to reload Org or to restart Emacs after customizing this.")
  3912. (defcustom org-emphasis-alist
  3913. '(("*" bold)
  3914. ("/" italic)
  3915. ("_" underline)
  3916. ("=" org-verbatim verbatim)
  3917. ("~" org-code verbatim)
  3918. ("+" (:strike-through t)))
  3919. "Alist of characters and faces to emphasize text.
  3920. Text starting and ending with a special character will be emphasized,
  3921. for example *bold*, _underlined_ and /italic/. This variable sets the
  3922. marker characters and the face to be used by font-lock for highlighting
  3923. in Org buffers.
  3924. You need to reload Org or to restart Emacs after customizing this."
  3925. :group 'org-appearance
  3926. :set 'org-set-emph-re
  3927. :version "24.4"
  3928. :package-version '(Org . "8.0")
  3929. :type '(repeat
  3930. (list
  3931. (string :tag "Marker character")
  3932. (choice
  3933. (face :tag "Font-lock-face")
  3934. (plist :tag "Face property list"))
  3935. (option (const verbatim)))))
  3936. (defvar org-protecting-blocks '("src" "example" "export")
  3937. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3938. This is needed for font-lock setup.")
  3939. ;;; Functions and variables from their packages
  3940. ;; Declared here to avoid compiler warnings
  3941. (defvar mark-active)
  3942. ;; Various packages
  3943. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3944. (declare-function calendar-forward-day "cal-move" (arg))
  3945. (declare-function calendar-goto-date "cal-move" (date))
  3946. (declare-function calendar-goto-today "cal-move" ())
  3947. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3948. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3949. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3950. (declare-function cdlatex-tab "ext:cdlatex" ())
  3951. (declare-function dired-get-filename
  3952. "dired"
  3953. (&optional localp no-error-if-not-filep))
  3954. (declare-function iswitchb-read-buffer
  3955. "iswitchb"
  3956. (prompt &optional
  3957. default require-match _predicate start matches-set))
  3958. (declare-function org-agenda-change-all-lines
  3959. "org-agenda"
  3960. (newhead hdmarker &optional fixface just-this))
  3961. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3962. "org-agenda"
  3963. (&optional end))
  3964. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3965. (declare-function org-agenda-format-item
  3966. "org-agenda"
  3967. (extra txt &optional level category tags dotime
  3968. remove-re habitp))
  3969. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3970. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3971. (declare-function org-agenda-save-markers-for-cut-and-paste
  3972. "org-agenda"
  3973. (beg end))
  3974. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3975. (declare-function org-agenda-skip "org-agenda" ())
  3976. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3977. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3978. (declare-function org-indent-mode "org-indent" (&optional arg))
  3979. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3980. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3981. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3982. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3983. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3984. (declare-function parse-time-string "parse-time" (string))
  3985. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3986. (defvar align-mode-rules-list)
  3987. (defvar calc-embedded-close-formula)
  3988. (defvar calc-embedded-open-formula)
  3989. (defvar calc-embedded-open-mode)
  3990. (defvar font-lock-unfontify-region-function)
  3991. (defvar iswitchb-temp-buflist)
  3992. (defvar org-agenda-tags-todo-honor-ignore-options)
  3993. (defvar remember-data-file)
  3994. (defvar texmathp-why)
  3995. ;;;###autoload
  3996. (defun turn-on-orgtbl ()
  3997. "Unconditionally turn on `orgtbl-mode'."
  3998. (require 'org-table)
  3999. (orgtbl-mode 1))
  4000. (defun org-at-table-p (&optional table-type)
  4001. "Non-nil if the cursor is inside an Org table.
  4002. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  4003. If `org-enable-table-editor' is nil, return nil unconditionally."
  4004. (and
  4005. org-enable-table-editor
  4006. (save-excursion
  4007. (beginning-of-line)
  4008. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  4009. (or (not (derived-mode-p 'org-mode))
  4010. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  4011. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  4012. (defun org-at-table.el-p ()
  4013. "Non-nil when point is at a table.el table."
  4014. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4015. (let ((element (org-element-at-point)))
  4016. (and (eq (org-element-type element) 'table)
  4017. (eq (org-element-property :type element) 'table.el)))))
  4018. (defun org-at-table-hline-p ()
  4019. "Non-nil when point is inside a hline in a table.
  4020. Assume point is already in a table. If `org-enable-table-editor'
  4021. is nil, return nil unconditionally."
  4022. (and org-enable-table-editor
  4023. (save-excursion
  4024. (beginning-of-line)
  4025. (looking-at org-table-hline-regexp))))
  4026. (defun org-table-map-tables (function &optional quietly)
  4027. "Apply FUNCTION to the start of all tables in the buffer."
  4028. (org-with-wide-buffer
  4029. (goto-char (point-min))
  4030. (while (re-search-forward org-table-any-line-regexp nil t)
  4031. (unless quietly
  4032. (message "Mapping tables: %d%%"
  4033. (floor (* 100.0 (point)) (buffer-size))))
  4034. (beginning-of-line 1)
  4035. (when (and (looking-at org-table-line-regexp)
  4036. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4037. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4038. (save-excursion (funcall function))
  4039. (or (looking-at org-table-line-regexp)
  4040. (forward-char 1)))
  4041. (re-search-forward org-table-any-border-regexp nil 1)))
  4042. (unless quietly (message "Mapping tables: done")))
  4043. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4044. (declare-function org-clock-update-mode-line "org-clock" ())
  4045. (declare-function org-resolve-clocks "org-clock"
  4046. (&optional also-non-dangling-p prompt last-valid))
  4047. (defun org-at-TBLFM-p (&optional pos)
  4048. "Non-nil when point (or POS) is in #+TBLFM line."
  4049. (save-excursion
  4050. (goto-char (or pos (point)))
  4051. (beginning-of-line)
  4052. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4053. (eq (org-element-type (org-element-at-point)) 'table))))
  4054. (defvar org-clock-start-time)
  4055. (defvar org-clock-marker (make-marker)
  4056. "Marker recording the last clock-in.")
  4057. (defvar org-clock-hd-marker (make-marker)
  4058. "Marker recording the last clock-in, but the headline position.")
  4059. (defvar org-clock-heading ""
  4060. "The heading of the current clock entry.")
  4061. (defun org-clock-is-active ()
  4062. "Return the buffer where the clock is currently running.
  4063. Return nil if no clock is running."
  4064. (marker-buffer org-clock-marker))
  4065. (defun org-check-running-clock ()
  4066. "Check if the current buffer contains the running clock.
  4067. If yes, offer to stop it and to save the buffer with the changes."
  4068. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4069. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4070. (buffer-name))))
  4071. (org-clock-out)
  4072. (when (y-or-n-p "Save changed buffer?")
  4073. (save-buffer))))
  4074. (defun org-clocktable-try-shift (dir n)
  4075. "Check if this line starts a clock table, if yes, shift the time block."
  4076. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4077. (org-clocktable-shift dir n)))
  4078. ;;;###autoload
  4079. (defun org-clock-persistence-insinuate ()
  4080. "Set up hooks for clock persistence."
  4081. (require 'org-clock)
  4082. (add-hook 'org-mode-hook 'org-clock-load)
  4083. (add-hook 'kill-emacs-hook 'org-clock-save))
  4084. (defgroup org-archive nil
  4085. "Options concerning archiving in Org mode."
  4086. :tag "Org Archive"
  4087. :group 'org-structure)
  4088. (defcustom org-archive-location "%s_archive::"
  4089. "The location where subtrees should be archived.
  4090. The value of this variable is a string, consisting of two parts,
  4091. separated by a double-colon. The first part is a filename and
  4092. the second part is a headline.
  4093. When the filename is omitted, archiving happens in the same file.
  4094. %s in the filename will be replaced by the current file
  4095. name (without the directory part). Archiving to a different file
  4096. is useful to keep archived entries from contributing to the
  4097. Org Agenda.
  4098. The archived entries will be filed as subtrees of the specified
  4099. headline. When the headline is omitted, the subtrees are simply
  4100. filed away at the end of the file, as top-level entries. Also in
  4101. the heading you can use %s to represent the file name, this can be
  4102. useful when using the same archive for a number of different files.
  4103. Here are a few examples:
  4104. \"%s_archive::\"
  4105. If the current file is Projects.org, archive in file
  4106. Projects.org_archive, as top-level trees. This is the default.
  4107. \"::* Archived Tasks\"
  4108. Archive in the current file, under the top-level headline
  4109. \"* Archived Tasks\".
  4110. \"~/org/archive.org::\"
  4111. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4112. \"~/org/archive.org::* From %s\"
  4113. Archive in file ~/org/archive.org (absolute path), under headlines
  4114. \"From FILENAME\" where file name is the current file name.
  4115. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4116. The \"datetree/\" string is special, signifying to archive
  4117. items to the datetree. Items are placed in either the CLOSED
  4118. date of the item, or the current date if there is no CLOSED date.
  4119. The heading will be a subentry to the current date. There doesn't
  4120. need to be a heading, but there always needs to be a slash after
  4121. datetree. For example, to store archived items directly in the
  4122. datetree, use \"~/org/datetree.org::datetree/\".
  4123. \"basement::** Finished Tasks\"
  4124. Archive in file ./basement (relative path), as level 3 trees
  4125. below the level 2 heading \"** Finished Tasks\".
  4126. You may set this option on a per-file basis by adding to the buffer a
  4127. line like
  4128. #+ARCHIVE: basement::** Finished Tasks
  4129. You may also define it locally for a subtree by setting an ARCHIVE property
  4130. in the entry. If such a property is found in an entry, or anywhere up
  4131. the hierarchy, it will be used."
  4132. :group 'org-archive
  4133. :type 'string)
  4134. (defcustom org-agenda-skip-archived-trees t
  4135. "Non-nil means the agenda will skip any items located in archived trees.
  4136. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4137. variable is no longer recommended, you should leave it at the value t.
  4138. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4139. :group 'org-archive
  4140. :group 'org-agenda-skip
  4141. :type 'boolean)
  4142. (defcustom org-columns-skip-archived-trees t
  4143. "Non-nil means ignore archived trees when creating column view."
  4144. :group 'org-archive
  4145. :group 'org-properties
  4146. :type 'boolean)
  4147. (defcustom org-cycle-open-archived-trees nil
  4148. "Non-nil means `org-cycle' will open archived trees.
  4149. An archived tree is a tree marked with the tag ARCHIVE.
  4150. When nil, archived trees will stay folded. You can still open them with
  4151. normal outline commands like `show-all', but not with the cycling commands."
  4152. :group 'org-archive
  4153. :group 'org-cycle
  4154. :type 'boolean)
  4155. (defcustom org-sparse-tree-open-archived-trees nil
  4156. "Non-nil means sparse tree construction shows matches in archived trees.
  4157. When nil, matches in these trees are highlighted, but the trees are kept in
  4158. collapsed state."
  4159. :group 'org-archive
  4160. :group 'org-sparse-trees
  4161. :type 'boolean)
  4162. (defcustom org-sparse-tree-default-date-type nil
  4163. "The default date type when building a sparse tree.
  4164. When this is nil, a date is a scheduled or a deadline timestamp.
  4165. Otherwise, these types are allowed:
  4166. all: all timestamps
  4167. active: only active timestamps (<...>)
  4168. inactive: only inactive timestamps ([...])
  4169. scheduled: only scheduled timestamps
  4170. deadline: only deadline timestamps"
  4171. :type '(choice (const :tag "Scheduled or deadline" nil)
  4172. (const :tag "All timestamps" all)
  4173. (const :tag "Only active timestamps" active)
  4174. (const :tag "Only inactive timestamps" inactive)
  4175. (const :tag "Only scheduled timestamps" scheduled)
  4176. (const :tag "Only deadline timestamps" deadline)
  4177. (const :tag "Only closed timestamps" closed))
  4178. :version "25.2"
  4179. :package-version '(Org . "8.3")
  4180. :group 'org-sparse-trees)
  4181. (defun org-cycle-hide-archived-subtrees (state)
  4182. "Re-hide all archived subtrees after a visibility state change."
  4183. (when (and (not org-cycle-open-archived-trees)
  4184. (not (memq state '(overview folded))))
  4185. (save-excursion
  4186. (let* ((globalp (memq state '(contents all)))
  4187. (beg (if globalp (point-min) (point)))
  4188. (end (if globalp (point-max) (org-end-of-subtree t))))
  4189. (org-hide-archived-subtrees beg end)
  4190. (goto-char beg)
  4191. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4192. (message "%s" (substitute-command-keys
  4193. "Subtree is archived and stays closed. Use \
  4194. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4195. (defun org-force-cycle-archived ()
  4196. "Cycle subtree even if it is archived."
  4197. (interactive)
  4198. (setq this-command 'org-cycle)
  4199. (let ((org-cycle-open-archived-trees t))
  4200. (call-interactively 'org-cycle)))
  4201. (defun org-hide-archived-subtrees (beg end)
  4202. "Re-hide all archived subtrees after a visibility state change."
  4203. (org-with-wide-buffer
  4204. (let ((case-fold-search nil)
  4205. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4206. (goto-char beg)
  4207. ;; Include headline point is currently on.
  4208. (beginning-of-line)
  4209. (while (and (< (point) end) (re-search-forward re end t))
  4210. (when (member org-archive-tag (org-get-tags))
  4211. (org-flag-subtree t)
  4212. (org-end-of-subtree t))))))
  4213. (declare-function outline-end-of-heading "outline" ())
  4214. (declare-function outline-flag-region "outline" (from to flag))
  4215. (defun org-flag-subtree (flag)
  4216. (save-excursion
  4217. (org-back-to-heading t)
  4218. (outline-end-of-heading)
  4219. (outline-flag-region (point)
  4220. (progn (org-end-of-subtree t) (point))
  4221. flag)))
  4222. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4223. ;; Declare Column View Code
  4224. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4225. (declare-function org-columns-compute "org-colview" (property))
  4226. ;; Declare ID code
  4227. (declare-function org-id-store-link "org-id")
  4228. (declare-function org-id-locations-load "org-id")
  4229. (declare-function org-id-locations-save "org-id")
  4230. (defvar org-id-track-globally)
  4231. ;;; Variables for pre-computed regular expressions, all buffer local
  4232. (defvar-local org-todo-regexp nil
  4233. "Matches any of the TODO state keywords.
  4234. Since TODO keywords are case-sensitive, `case-fold-search' is
  4235. expected to be bound to nil when matching against this regexp.")
  4236. (defvar-local org-not-done-regexp nil
  4237. "Matches any of the TODO state keywords except the last one.
  4238. Since TODO keywords are case-sensitive, `case-fold-search' is
  4239. expected to be bound to nil when matching against this regexp.")
  4240. (defvar-local org-not-done-heading-regexp nil
  4241. "Matches a TODO headline that is not done.
  4242. Since TODO keywords are case-sensitive, `case-fold-search' is
  4243. expected to be bound to nil when matching against this regexp.")
  4244. (defvar-local org-todo-line-regexp nil
  4245. "Matches a headline and puts TODO state into group 2 if present.
  4246. Since TODO keywords are case-sensitive, `case-fold-search' is
  4247. expected to be bound to nil when matching against this regexp.")
  4248. (defvar-local org-complex-heading-regexp nil
  4249. "Matches a headline and puts everything into groups:
  4250. group 1: Stars
  4251. group 2: The TODO keyword, maybe
  4252. group 3: Priority cookie
  4253. group 4: True headline
  4254. group 5: Tags
  4255. Since TODO keywords are case-sensitive, `case-fold-search' is
  4256. expected to be bound to nil when matching against this regexp.")
  4257. (defvar-local org-complex-heading-regexp-format nil
  4258. "Printf format to make regexp to match an exact headline.
  4259. This regexp will match the headline of any node which has the
  4260. exact headline text that is put into the format, but may have any
  4261. TODO state, priority and tags.")
  4262. (defvar-local org-todo-line-tags-regexp nil
  4263. "Matches a headline and puts TODO state into group 2 if present.
  4264. Also put tags into group 4 if tags are present.")
  4265. (defconst org-plain-time-of-day-regexp
  4266. (concat
  4267. "\\(\\<[012]?[0-9]"
  4268. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4269. "\\(--?"
  4270. "\\(\\<[012]?[0-9]"
  4271. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4272. "\\)?")
  4273. "Regular expression to match a plain time or time range.
  4274. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4275. groups carry important information:
  4276. 0 the full match
  4277. 1 the first time, range or not
  4278. 8 the second time, if it is a range.")
  4279. (defconst org-plain-time-extension-regexp
  4280. (concat
  4281. "\\(\\<[012]?[0-9]"
  4282. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4283. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4284. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4285. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4286. groups carry important information:
  4287. 0 the full match
  4288. 7 hours of duration
  4289. 9 minutes of duration")
  4290. (defconst org-stamp-time-of-day-regexp
  4291. (concat
  4292. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4293. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4294. "\\(--?"
  4295. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4296. "Regular expression to match a timestamp time or time range.
  4297. After a match, the following groups carry important information:
  4298. 0 the full match
  4299. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4300. 2 the first time, range or not
  4301. 4 the second time, if it is a range.")
  4302. (defconst org-startup-options
  4303. '(("fold" org-startup-folded t)
  4304. ("overview" org-startup-folded t)
  4305. ("nofold" org-startup-folded nil)
  4306. ("showall" org-startup-folded nil)
  4307. ("showeverything" org-startup-folded showeverything)
  4308. ("content" org-startup-folded content)
  4309. ("indent" org-startup-indented t)
  4310. ("noindent" org-startup-indented nil)
  4311. ("hidestars" org-hide-leading-stars t)
  4312. ("showstars" org-hide-leading-stars nil)
  4313. ("odd" org-odd-levels-only t)
  4314. ("oddeven" org-odd-levels-only nil)
  4315. ("align" org-startup-align-all-tables t)
  4316. ("noalign" org-startup-align-all-tables nil)
  4317. ("inlineimages" org-startup-with-inline-images t)
  4318. ("noinlineimages" org-startup-with-inline-images nil)
  4319. ("latexpreview" org-startup-with-latex-preview t)
  4320. ("nolatexpreview" org-startup-with-latex-preview nil)
  4321. ("customtime" org-display-custom-times t)
  4322. ("logdone" org-log-done time)
  4323. ("lognotedone" org-log-done note)
  4324. ("nologdone" org-log-done nil)
  4325. ("lognoteclock-out" org-log-note-clock-out t)
  4326. ("nolognoteclock-out" org-log-note-clock-out nil)
  4327. ("logrepeat" org-log-repeat state)
  4328. ("lognoterepeat" org-log-repeat note)
  4329. ("logdrawer" org-log-into-drawer t)
  4330. ("nologdrawer" org-log-into-drawer nil)
  4331. ("logstatesreversed" org-log-states-order-reversed t)
  4332. ("nologstatesreversed" org-log-states-order-reversed nil)
  4333. ("nologrepeat" org-log-repeat nil)
  4334. ("logreschedule" org-log-reschedule time)
  4335. ("lognotereschedule" org-log-reschedule note)
  4336. ("nologreschedule" org-log-reschedule nil)
  4337. ("logredeadline" org-log-redeadline time)
  4338. ("lognoteredeadline" org-log-redeadline note)
  4339. ("nologredeadline" org-log-redeadline nil)
  4340. ("logrefile" org-log-refile time)
  4341. ("lognoterefile" org-log-refile note)
  4342. ("nologrefile" org-log-refile nil)
  4343. ("fninline" org-footnote-define-inline t)
  4344. ("nofninline" org-footnote-define-inline nil)
  4345. ("fnlocal" org-footnote-section nil)
  4346. ("fnauto" org-footnote-auto-label t)
  4347. ("fnprompt" org-footnote-auto-label nil)
  4348. ("fnconfirm" org-footnote-auto-label confirm)
  4349. ("fnplain" org-footnote-auto-label plain)
  4350. ("fnadjust" org-footnote-auto-adjust t)
  4351. ("nofnadjust" org-footnote-auto-adjust nil)
  4352. ("constcgs" constants-unit-system cgs)
  4353. ("constSI" constants-unit-system SI)
  4354. ("noptag" org-tag-persistent-alist nil)
  4355. ("hideblocks" org-hide-block-startup t)
  4356. ("nohideblocks" org-hide-block-startup nil)
  4357. ("beamer" org-startup-with-beamer-mode t)
  4358. ("entitiespretty" org-pretty-entities t)
  4359. ("entitiesplain" org-pretty-entities nil))
  4360. "Variable associated with STARTUP options for org-mode.
  4361. Each element is a list of three items: the startup options (as written
  4362. in the #+STARTUP line), the corresponding variable, and the value to set
  4363. this variable to if the option is found. An optional forth element PUSH
  4364. means to push this value onto the list in the variable.")
  4365. (defcustom org-group-tags t
  4366. "When non-nil (the default), use group tags.
  4367. This can be turned on/off through `org-toggle-tags-groups'."
  4368. :group 'org-tags
  4369. :group 'org-startup
  4370. :type 'boolean)
  4371. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4372. (defun org-toggle-tags-groups ()
  4373. "Toggle support for group tags.
  4374. Support for group tags is controlled by the option
  4375. `org-group-tags', which is non-nil by default."
  4376. (interactive)
  4377. (setq org-group-tags (not org-group-tags))
  4378. (cond ((and (derived-mode-p 'org-agenda-mode)
  4379. org-group-tags)
  4380. (org-agenda-redo))
  4381. ((derived-mode-p 'org-mode)
  4382. (let ((org-inhibit-startup t)) (org-mode))))
  4383. (message "Groups tags support has been turned %s"
  4384. (if org-group-tags "on" "off")))
  4385. (defun org-set-regexps-and-options (&optional tags-only)
  4386. "Precompute regular expressions used in the current buffer.
  4387. When optional argument TAGS-ONLY is non-nil, only compute tags
  4388. related expressions."
  4389. (when (derived-mode-p 'org-mode)
  4390. (let ((alist (org--setup-collect-keywords
  4391. (org-make-options-regexp
  4392. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4393. (and (not tags-only)
  4394. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4395. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4396. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4397. ;; Startup options. Get this early since it does change
  4398. ;; behavior for other options (e.g., tags).
  4399. (let ((startup (cdr (assq 'startup alist))))
  4400. (dolist (option startup)
  4401. (let ((entry (assoc-string option org-startup-options t)))
  4402. (when entry
  4403. (let ((var (nth 1 entry))
  4404. (val (nth 2 entry)))
  4405. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4406. (unless (listp (symbol-value var))
  4407. (set (make-local-variable var) nil))
  4408. (add-to-list var val)))))))
  4409. (setq-local org-file-tags
  4410. (mapcar #'org-add-prop-inherited
  4411. (cdr (assq 'filetags alist))))
  4412. (setq org-current-tag-alist
  4413. (append org-tag-persistent-alist
  4414. (let ((tags (cdr (assq 'tags alist))))
  4415. (if tags (org-tag-string-to-alist tags)
  4416. org-tag-alist))))
  4417. (setq org-tag-groups-alist
  4418. (org-tag-alist-to-groups org-current-tag-alist))
  4419. (unless tags-only
  4420. ;; File properties.
  4421. (setq-local org-file-properties (cdr (assq 'property alist)))
  4422. ;; Archive location.
  4423. (let ((archive (cdr (assq 'archive alist))))
  4424. (when archive (setq-local org-archive-location archive)))
  4425. ;; Category.
  4426. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4427. (when cat
  4428. (setq-local org-category (intern cat))
  4429. (setq-local org-file-properties
  4430. (org--update-property-plist
  4431. "CATEGORY" cat org-file-properties))))
  4432. ;; Columns.
  4433. (let ((column (cdr (assq 'columns alist))))
  4434. (when column (setq-local org-columns-default-format column)))
  4435. ;; Constants.
  4436. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4437. ;; Link abbreviations.
  4438. (let ((links (cdr (assq 'link alist))))
  4439. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4440. ;; Priorities.
  4441. (let ((priorities (cdr (assq 'priorities alist))))
  4442. (when priorities
  4443. (setq-local org-highest-priority (nth 0 priorities))
  4444. (setq-local org-lowest-priority (nth 1 priorities))
  4445. (setq-local org-default-priority (nth 2 priorities))))
  4446. ;; Scripts.
  4447. (let ((scripts (assq 'scripts alist)))
  4448. (when scripts
  4449. (setq-local org-use-sub-superscripts (cdr scripts))))
  4450. ;; TODO keywords.
  4451. (setq-local org-todo-kwd-alist nil)
  4452. (setq-local org-todo-key-alist nil)
  4453. (setq-local org-todo-key-trigger nil)
  4454. (setq-local org-todo-keywords-1 nil)
  4455. (setq-local org-done-keywords nil)
  4456. (setq-local org-todo-heads nil)
  4457. (setq-local org-todo-sets nil)
  4458. (setq-local org-todo-log-states nil)
  4459. (let ((todo-sequences
  4460. (or (nreverse (cdr (assq 'todo alist)))
  4461. (let ((d (default-value 'org-todo-keywords)))
  4462. (if (not (stringp (car d))) d
  4463. ;; XXX: Backward compatibility code.
  4464. (list (cons org-todo-interpretation d)))))))
  4465. (dolist (sequence todo-sequences)
  4466. (let* ((sequence (or (run-hook-with-args-until-success
  4467. 'org-todo-setup-filter-hook sequence)
  4468. sequence))
  4469. (sequence-type (car sequence))
  4470. (keywords (cdr sequence))
  4471. (sep (member "|" keywords))
  4472. names alist)
  4473. (dolist (k (remove "|" keywords))
  4474. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4475. k)
  4476. (error "Invalid TODO keyword %s" k))
  4477. (let ((name (match-string 1 k))
  4478. (key (match-string 2 k))
  4479. (log (org-extract-log-state-settings k)))
  4480. (push name names)
  4481. (push (cons name (and key (string-to-char key))) alist)
  4482. (when log (push log org-todo-log-states))))
  4483. (let* ((names (nreverse names))
  4484. (done (if sep (org-remove-keyword-keys (cdr sep))
  4485. (last names)))
  4486. (head (car names))
  4487. (tail (list sequence-type head (car done) (org-last done))))
  4488. (add-to-list 'org-todo-heads head 'append)
  4489. (push names org-todo-sets)
  4490. (setq org-done-keywords (append org-done-keywords done nil))
  4491. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4492. (setq org-todo-key-alist
  4493. (append org-todo-key-alist
  4494. (and alist
  4495. (append '((:startgroup))
  4496. (nreverse alist)
  4497. '((:endgroup))))))
  4498. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4499. (setq org-todo-sets (nreverse org-todo-sets)
  4500. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4501. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4502. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4503. ;; Compute the regular expressions and other local variables.
  4504. ;; Using `org-outline-regexp-bol' would complicate them much,
  4505. ;; because of the fixed white space at the end of that string.
  4506. (unless org-done-keywords
  4507. (setq org-done-keywords
  4508. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4509. (setq org-not-done-keywords
  4510. (org-delete-all org-done-keywords
  4511. (copy-sequence org-todo-keywords-1))
  4512. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4513. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4514. org-not-done-heading-regexp
  4515. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4516. org-todo-line-regexp
  4517. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4518. org-complex-heading-regexp
  4519. (concat "^\\(\\*+\\)"
  4520. "\\(?: +" org-todo-regexp "\\)?"
  4521. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4522. "\\(?: +\\(.*?\\)\\)??"
  4523. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4524. "[ \t]*$")
  4525. org-complex-heading-regexp-format
  4526. (concat "^\\(\\*+\\)"
  4527. "\\(?: +" org-todo-regexp "\\)?"
  4528. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4529. "\\(?: +"
  4530. ;; Stats cookies can be stuck to body.
  4531. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4532. "\\(%s\\)"
  4533. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4534. "\\)"
  4535. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4536. "[ \t]*$")
  4537. org-todo-line-tags-regexp
  4538. (concat "^\\(\\*+\\)"
  4539. "\\(?: +" org-todo-regexp "\\)?"
  4540. "\\(?: +\\(.*?\\)\\)??"
  4541. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4542. "[ \t]*$"))
  4543. (org-compute-latex-and-related-regexp)))))
  4544. (defun org--setup-collect-keywords (regexp &optional files alist)
  4545. "Return setup keywords values as an alist.
  4546. REGEXP matches a subset of setup keywords. FILES is a list of
  4547. file names already visited. It is used to avoid circular setup
  4548. files. ALIST, when non-nil, is the alist computed so far.
  4549. Return value contains the following keys: `archive', `category',
  4550. `columns', `constants', `filetags', `link', `priorities',
  4551. `property', `scripts', `startup', `tags' and `todo'."
  4552. (org-with-wide-buffer
  4553. (goto-char (point-min))
  4554. (let ((case-fold-search t))
  4555. (while (re-search-forward regexp nil t)
  4556. (let ((element (org-element-at-point)))
  4557. (when (eq (org-element-type element) 'keyword)
  4558. (let ((key (org-element-property :key element))
  4559. (value (org-element-property :value element)))
  4560. (cond
  4561. ((equal key "ARCHIVE")
  4562. (when (org-string-nw-p value)
  4563. (push (cons 'archive value) alist)))
  4564. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4565. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4566. ((equal key "CONSTANTS")
  4567. (let* ((constants (assq 'constants alist))
  4568. (store (cdr constants)))
  4569. (dolist (pair (org-split-string value))
  4570. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4571. pair)
  4572. (let* ((name (match-string 1 pair))
  4573. (value (match-string 2 pair))
  4574. (old (assoc name store)))
  4575. (if old (setcdr old value)
  4576. (push (cons name value) store)))))
  4577. (if constants (setcdr constants store)
  4578. (push (cons 'constants store) alist))))
  4579. ((equal key "FILETAGS")
  4580. (when (org-string-nw-p value)
  4581. (let ((old (assq 'filetags alist))
  4582. (new (apply #'nconc
  4583. (mapcar (lambda (x) (org-split-string x ":"))
  4584. (org-split-string value)))))
  4585. (if old (setcdr old (append new (cdr old)))
  4586. (push (cons 'filetags new) alist)))))
  4587. ((equal key "LINK")
  4588. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4589. (let ((links (assq 'link alist))
  4590. (pair (cons (match-string-no-properties 1 value)
  4591. (match-string-no-properties 2 value))))
  4592. (if links (push pair (cdr links))
  4593. (push (list 'link pair) alist)))))
  4594. ((equal key "OPTIONS")
  4595. (when (and (org-string-nw-p value)
  4596. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4597. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4598. ((equal key "PRIORITIES")
  4599. (push (cons 'priorities
  4600. (let ((prio (org-split-string value)))
  4601. (if (< (length prio) 3) '(?A ?C ?B)
  4602. (mapcar #'string-to-char prio))))
  4603. alist))
  4604. ((equal key "PROPERTY")
  4605. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4606. (let* ((property (assq 'property alist))
  4607. (value (org--update-property-plist
  4608. (match-string-no-properties 1 value)
  4609. (match-string-no-properties 2 value)
  4610. (cdr property))))
  4611. (if property (setcdr property value)
  4612. (push (cons 'property value) alist)))))
  4613. ((equal key "STARTUP")
  4614. (let ((startup (assq 'startup alist)))
  4615. (if startup
  4616. (setcdr startup
  4617. (append (cdr startup) (org-split-string value)))
  4618. (push (cons 'startup (org-split-string value)) alist))))
  4619. ((equal key "TAGS")
  4620. (let ((tag-cell (assq 'tags alist)))
  4621. (if tag-cell
  4622. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4623. (push (cons 'tags value) alist))))
  4624. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4625. (let ((todo (assq 'todo alist))
  4626. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4627. (org-split-string value))))
  4628. (if todo (push value (cdr todo))
  4629. (push (list 'todo value) alist))))
  4630. ((equal key "SETUPFILE")
  4631. (unless buffer-read-only ; Do not check in Gnus messages.
  4632. (let ((f (and (org-string-nw-p value)
  4633. (expand-file-name
  4634. (org-unbracket-string "\"" "\"" value)))))
  4635. (when (and f (file-readable-p f) (not (member f files)))
  4636. (with-temp-buffer
  4637. (setq default-directory (file-name-directory f))
  4638. (insert-file-contents f)
  4639. (setq alist
  4640. ;; Fake Org mode to benefit from cache
  4641. ;; without recurring needlessly.
  4642. (let ((major-mode 'org-mode))
  4643. (org--setup-collect-keywords
  4644. regexp (cons f files) alist)))))))))))))))
  4645. alist)
  4646. (defun org-tag-string-to-alist (s)
  4647. "Return tag alist associated to string S.
  4648. S is a value for TAGS keyword or produced with
  4649. `org-tag-alist-to-string'. Return value is an alist suitable for
  4650. `org-tag-alist' or `org-tag-persistent-alist'."
  4651. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4652. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4653. "\\|{.+?}\\)" ; regular expression
  4654. "\\(?:(\\(.\\))\\)?\\'"))
  4655. alist group-flag)
  4656. (dolist (tokens lines (cdr (nreverse alist)))
  4657. (push '(:newline) alist)
  4658. (while tokens
  4659. (let ((token (pop tokens)))
  4660. (pcase token
  4661. ("{"
  4662. (push '(:startgroup) alist)
  4663. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4664. ("}"
  4665. (push '(:endgroup) alist)
  4666. (setq group-flag nil))
  4667. ("["
  4668. (push '(:startgrouptag) alist)
  4669. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4670. ("]"
  4671. (push '(:endgrouptag) alist)
  4672. (setq group-flag nil))
  4673. (":"
  4674. (push '(:grouptags) alist))
  4675. ((guard (string-match tag-re token))
  4676. (let ((tag (match-string 1 token))
  4677. (key (and (match-beginning 2)
  4678. (string-to-char (match-string 2 token)))))
  4679. ;; Push all tags in groups, no matter if they already
  4680. ;; appear somewhere else in the list.
  4681. (when (or group-flag (not (assoc tag alist)))
  4682. (push (cons tag key) alist))))))))))
  4683. (defun org-tag-alist-to-string (alist &optional skip-key)
  4684. "Return tag string associated to ALIST.
  4685. ALIST is an alist, as defined in `org-tag-alist' or
  4686. `org-tag-persistent-alist', or produced with
  4687. `org-tag-string-to-alist'.
  4688. Return value is a string suitable as a value for \"TAGS\"
  4689. keyword.
  4690. When optional argument SKIP-KEY is non-nil, skip selection keys
  4691. next to tags."
  4692. (mapconcat (lambda (token)
  4693. (pcase token
  4694. (`(:startgroup) "{")
  4695. (`(:endgroup) "}")
  4696. (`(:startgrouptag) "[")
  4697. (`(:endgrouptag) "]")
  4698. (`(:grouptags) ":")
  4699. (`(:newline) "\\n")
  4700. ((and
  4701. (guard (not skip-key))
  4702. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4703. (format "%s(%c)" tag key))
  4704. (`(,(and tag (pred stringp)) . ,_) tag)
  4705. (_ (user-error "Invalid tag token: %S" token))))
  4706. alist
  4707. " "))
  4708. (defun org-tag-alist-to-groups (alist)
  4709. "Return group alist from tag ALIST.
  4710. ALIST is an alist, as defined in `org-tag-alist' or
  4711. `org-tag-persistent-alist', or produced with
  4712. `org-tag-string-to-alist'. Return value is an alist following
  4713. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4714. a string, summarizing TAGS, as a list of strings."
  4715. (let (groups group-status current-group)
  4716. (dolist (token alist (nreverse groups))
  4717. (pcase token
  4718. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4719. (`(,(or :endgroup :endgrouptag))
  4720. (when (eq group-status 'append)
  4721. (push (nreverse current-group) groups))
  4722. (setq group-status nil))
  4723. (`(:grouptags) (setq group-status 'append))
  4724. ((and `(,tag . ,_) (guard group-status))
  4725. (if (eq group-status 'append) (push tag current-group)
  4726. (setq current-group (list tag))))
  4727. (_ nil)))))
  4728. (defun org-file-contents (file &optional noerror)
  4729. "Return the contents of FILE, as a string."
  4730. (if (and file (file-readable-p file))
  4731. (with-temp-buffer
  4732. (insert-file-contents file)
  4733. (buffer-string))
  4734. (funcall (if noerror 'message 'error)
  4735. "Cannot read file \"%s\"%s"
  4736. file
  4737. (let ((from (buffer-file-name (buffer-base-buffer))))
  4738. (if from (concat " (referenced in file \"" from "\")") "")))))
  4739. (defun org-extract-log-state-settings (x)
  4740. "Extract the log state setting from a TODO keyword string.
  4741. This will extract info from a string like \"WAIT(w@/!)\"."
  4742. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4743. (let ((kw (match-string 1 x))
  4744. (log1 (and (match-end 3) (match-string 3 x)))
  4745. (log2 (and (match-end 4) (match-string 4 x))))
  4746. (and (or log1 log2)
  4747. (list kw
  4748. (and log1 (if (equal log1 "!") 'time 'note))
  4749. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4750. (defun org-remove-keyword-keys (list)
  4751. "Remove a pair of parenthesis at the end of each string in LIST."
  4752. (mapcar (lambda (x)
  4753. (if (string-match "(.*)$" x)
  4754. (substring x 0 (match-beginning 0))
  4755. x))
  4756. list))
  4757. (defun org-assign-fast-keys (alist)
  4758. "Assign fast keys to a keyword-key alist.
  4759. Respect keys that are already there."
  4760. (let (new e (alt ?0))
  4761. (while (setq e (pop alist))
  4762. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4763. (cdr e)) ;; Key already assigned.
  4764. (push e new)
  4765. (let ((clist (string-to-list (downcase (car e))))
  4766. (used (append new alist)))
  4767. (when (= (car clist) ?@)
  4768. (pop clist))
  4769. (while (and clist (rassoc (car clist) used))
  4770. (pop clist))
  4771. (unless clist
  4772. (while (rassoc alt used)
  4773. (cl-incf alt)))
  4774. (push (cons (car e) (or (car clist) alt)) new))))
  4775. (nreverse new)))
  4776. ;;; Some variables used in various places
  4777. (defvar org-window-configuration nil
  4778. "Used in various places to store a window configuration.")
  4779. (defvar org-selected-window nil
  4780. "Used in various places to store a window configuration.")
  4781. (defvar org-finish-function nil
  4782. "Function to be called when `C-c C-c' is used.
  4783. This is for getting out of special buffers like capture.")
  4784. (defvar org-last-state)
  4785. ;; Defined somewhere in this file, but used before definition.
  4786. (defvar org-entities) ;; defined in org-entities.el
  4787. (defvar org-struct-menu)
  4788. (defvar org-org-menu)
  4789. (defvar org-tbl-menu)
  4790. ;;;; Define the Org mode
  4791. ;; We use a before-change function to check if a table might need
  4792. ;; an update.
  4793. (defvar org-table-may-need-update t
  4794. "Indicates that a table might need an update.
  4795. This variable is set by `org-before-change-function'.
  4796. `org-table-align' sets it back to nil.")
  4797. (defun org-before-change-function (_beg _end)
  4798. "Every change indicates that a table might need an update."
  4799. (setq org-table-may-need-update t))
  4800. (defvar org-mode-map)
  4801. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4802. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4803. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4804. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4805. (defvar org-table-buffer-is-an nil)
  4806. (defvar bidi-paragraph-direction)
  4807. (defvar buffer-face-mode-face)
  4808. (require 'outline)
  4809. ;; Other stuff we need.
  4810. (require 'time-date)
  4811. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4812. (require 'easymenu)
  4813. (autoload 'easy-menu-add "easymenu")
  4814. (require 'overlay)
  4815. ;; (require 'org-macs) moved higher up in the file before it is first used
  4816. (require 'org-entities)
  4817. ;; (require 'org-compat) moved higher up in the file before it is first used
  4818. (require 'org-faces)
  4819. (require 'org-list)
  4820. (require 'org-pcomplete)
  4821. (require 'org-src)
  4822. (require 'org-footnote)
  4823. (require 'org-macro)
  4824. ;; babel
  4825. (require 'ob)
  4826. ;;;###autoload
  4827. (define-derived-mode org-mode outline-mode "Org"
  4828. "Outline-based notes management and organizer, alias
  4829. \"Carsten's outline-mode for keeping track of everything.\"
  4830. Org mode develops organizational tasks around a NOTES file which
  4831. contains information about projects as plain text. Org mode is
  4832. implemented on top of Outline mode, which is ideal to keep the content
  4833. of large files well structured. It supports ToDo items, deadlines and
  4834. time stamps, which magically appear in the diary listing of the Emacs
  4835. calendar. Tables are easily created with a built-in table editor.
  4836. Plain text URL-like links connect to websites, emails (VM), Usenet
  4837. messages (Gnus), BBDB entries, and any files related to the project.
  4838. For printing and sharing of notes, an Org file (or a part of it)
  4839. can be exported as a structured ASCII or HTML file.
  4840. The following commands are available:
  4841. \\{org-mode-map}"
  4842. ;; Get rid of Outline menus, they are not needed
  4843. ;; Need to do this here because define-derived-mode sets up
  4844. ;; the keymap so late. Still, it is a waste to call this each time
  4845. ;; we switch another buffer into Org mode.
  4846. (define-key org-mode-map [menu-bar headings] 'undefined)
  4847. (define-key org-mode-map [menu-bar hide] 'undefined)
  4848. (define-key org-mode-map [menu-bar show] 'undefined)
  4849. (org-load-modules-maybe)
  4850. (org-install-agenda-files-menu)
  4851. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4852. (add-to-invisibility-spec '(org-cwidth))
  4853. (add-to-invisibility-spec '(org-hide-block . t))
  4854. (setq-local outline-regexp org-outline-regexp)
  4855. (setq-local outline-level 'org-outline-level)
  4856. (setq bidi-paragraph-direction 'left-to-right)
  4857. (when (and org-ellipsis
  4858. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4859. (fboundp 'make-glyph-code))
  4860. (unless org-display-table
  4861. (setq org-display-table (make-display-table)))
  4862. (set-display-table-slot
  4863. org-display-table 4
  4864. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4865. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4866. (setq buffer-display-table org-display-table))
  4867. (org-set-regexps-and-options)
  4868. (org-set-font-lock-defaults)
  4869. (when (and org-tag-faces (not org-tags-special-faces-re))
  4870. ;; tag faces set outside customize.... force initialization.
  4871. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4872. ;; Calc embedded
  4873. (setq-local calc-embedded-open-mode "# ")
  4874. ;; Modify a few syntax entries
  4875. (modify-syntax-entry ?@ "w")
  4876. (modify-syntax-entry ?\" "\"")
  4877. (modify-syntax-entry ?\\ "_")
  4878. (modify-syntax-entry ?~ "_")
  4879. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4880. ;; Activate before-change-function
  4881. (setq-local org-table-may-need-update t)
  4882. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4883. ;; Check for running clock before killing a buffer
  4884. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4885. ;; Initialize macros templates.
  4886. (org-macro-initialize-templates)
  4887. ;; Initialize radio targets.
  4888. (org-update-radio-target-regexp)
  4889. ;; Indentation.
  4890. (setq-local indent-line-function 'org-indent-line)
  4891. (setq-local indent-region-function 'org-indent-region)
  4892. ;; Filling and auto-filling.
  4893. (org-setup-filling)
  4894. ;; Comments.
  4895. (org-setup-comments-handling)
  4896. ;; Initialize cache.
  4897. (org-element-cache-reset)
  4898. ;; Beginning/end of defun
  4899. (setq-local beginning-of-defun-function 'org-backward-element)
  4900. (setq-local end-of-defun-function
  4901. (lambda ()
  4902. (if (not (org-at-heading-p))
  4903. (org-forward-element)
  4904. (org-forward-element)
  4905. (forward-char -1))))
  4906. ;; Next error for sparse trees
  4907. (setq-local next-error-function 'org-occur-next-match)
  4908. ;; Make sure dependence stuff works reliably, even for users who set it
  4909. ;; too late :-(
  4910. (if org-enforce-todo-dependencies
  4911. (add-hook 'org-blocker-hook
  4912. 'org-block-todo-from-children-or-siblings-or-parent)
  4913. (remove-hook 'org-blocker-hook
  4914. 'org-block-todo-from-children-or-siblings-or-parent))
  4915. (if org-enforce-todo-checkbox-dependencies
  4916. (add-hook 'org-blocker-hook
  4917. 'org-block-todo-from-checkboxes)
  4918. (remove-hook 'org-blocker-hook
  4919. 'org-block-todo-from-checkboxes))
  4920. ;; Align options lines
  4921. (setq-local
  4922. align-mode-rules-list
  4923. '((org-in-buffer-settings
  4924. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4925. (modes . '(org-mode)))))
  4926. ;; Imenu
  4927. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4928. ;; Make isearch reveal context
  4929. (setq-local outline-isearch-open-invisible-function
  4930. (lambda (&rest _) (org-show-context 'isearch)))
  4931. ;; Setup the pcomplete hooks
  4932. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4933. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4934. (setq-local pcomplete-default-completion-function 'ignore)
  4935. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4936. (setq-local pcomplete-termination-string "")
  4937. (setq-local buffer-face-mode-face 'org-default)
  4938. ;; If empty file that did not turn on Org mode automatically, make
  4939. ;; it to.
  4940. (when (and org-insert-mode-line-in-empty-file
  4941. (called-interactively-p 'any)
  4942. (= (point-min) (point-max)))
  4943. (insert "# -*- mode: org -*-\n\n"))
  4944. (unless org-inhibit-startup
  4945. (org-unmodified
  4946. (when org-startup-with-beamer-mode (org-beamer-mode))
  4947. (when org-startup-align-all-tables
  4948. (org-table-map-tables #'org-table-align t))
  4949. (when org-startup-with-inline-images (org-display-inline-images))
  4950. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4951. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4952. (when org-startup-truncated (setq truncate-lines t))
  4953. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4954. (org-refresh-effort-properties)))
  4955. ;; Try to set `org-hide' face correctly.
  4956. (let ((foreground (org-find-invisible-foreground)))
  4957. (when foreground
  4958. (set-face-foreground 'org-hide foreground))))
  4959. ;; Update `customize-package-emacs-version-alist'
  4960. (add-to-list 'customize-package-emacs-version-alist
  4961. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4962. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4963. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4964. ("9.0" . "25.2")))
  4965. (defvar org-mode-transpose-word-syntax-table
  4966. (let ((st (make-syntax-table text-mode-syntax-table)))
  4967. (dolist (c org-emphasis-alist st)
  4968. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4969. (when (fboundp 'abbrev-table-put)
  4970. (abbrev-table-put org-mode-abbrev-table
  4971. :parents (list text-mode-abbrev-table)))
  4972. (defun org-find-invisible-foreground ()
  4973. (let ((candidates (remove
  4974. "unspecified-bg"
  4975. (nconc
  4976. (list (face-background 'default)
  4977. (face-background 'org-default))
  4978. (mapcar
  4979. (lambda (alist)
  4980. (when (boundp alist)
  4981. (cdr (assq 'background-color (symbol-value alist)))))
  4982. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4983. (list (face-foreground 'org-hide))))))
  4984. (car (remove nil candidates))))
  4985. (defun org-current-time (&optional rounding-minutes past)
  4986. "Current time, possibly rounded to ROUNDING-MINUTES.
  4987. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4988. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4989. the rounding returns a past time."
  4990. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4991. (car org-time-stamp-rounding-minutes)))
  4992. (time (decode-time)) res)
  4993. (if (< r 1)
  4994. (current-time)
  4995. (setq res
  4996. (apply 'encode-time
  4997. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4998. (nthcdr 2 time))))
  4999. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  5000. (seconds-to-time (- (float-time res) (* r 60)))
  5001. res))))
  5002. (defun org-today ()
  5003. "Return today date, considering `org-extend-today-until'."
  5004. (time-to-days
  5005. (time-subtract (current-time)
  5006. (list 0 (* 3600 org-extend-today-until) 0))))
  5007. ;;;; Font-Lock stuff, including the activators
  5008. (defvar org-mouse-map (make-sparse-keymap))
  5009. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  5010. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  5011. (when org-mouse-1-follows-link
  5012. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5013. (when org-tab-follows-link
  5014. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5015. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5016. (require 'font-lock)
  5017. (defconst org-non-link-chars "]\t\n\r<>")
  5018. (defvar org-link-types-re nil
  5019. "Matches a link that has a url-like prefix like \"http:\"")
  5020. (defvar org-link-re-with-space nil
  5021. "Matches a link with spaces, optional angular brackets around it.")
  5022. (defvar org-link-re-with-space2 nil
  5023. "Matches a link with spaces, optional angular brackets around it.")
  5024. (defvar org-link-re-with-space3 nil
  5025. "Matches a link with spaces, only for internal part in bracket links.")
  5026. (defvar org-angle-link-re nil
  5027. "Matches link with angular brackets, spaces are allowed.")
  5028. (defvar org-plain-link-re nil
  5029. "Matches plain link, without spaces.")
  5030. (defvar org-bracket-link-regexp nil
  5031. "Matches a link in double brackets.")
  5032. (defvar org-bracket-link-analytic-regexp nil
  5033. "Regular expression used to analyze links.
  5034. Here is what the match groups contain after a match:
  5035. 1: http:
  5036. 2: http
  5037. 3: path
  5038. 4: [desc]
  5039. 5: desc")
  5040. (defvar org-bracket-link-analytic-regexp++ nil
  5041. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5042. (defvar org-any-link-re nil
  5043. "Regular expression matching any link.")
  5044. (defconst org-match-sexp-depth 3
  5045. "Number of stacked braces for sub/superscript matching.")
  5046. (defun org-create-multibrace-regexp (left right n)
  5047. "Create a regular expression which will match a balanced sexp.
  5048. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5049. as single character strings.
  5050. The regexp returned will match the entire expression including the
  5051. delimiters. It will also define a single group which contains the
  5052. match except for the outermost delimiters. The maximum depth of
  5053. stacked delimiters is N. Escaping delimiters is not possible."
  5054. (let* ((nothing (concat "[^" left right "]*?"))
  5055. (or "\\|")
  5056. (re nothing)
  5057. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5058. (while (> n 1)
  5059. (setq n (1- n)
  5060. re (concat re or next)
  5061. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5062. (concat left "\\(" re "\\)" right)))
  5063. (defconst org-match-substring-regexp
  5064. (concat
  5065. "\\(\\S-\\)\\([_^]\\)\\("
  5066. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5067. "\\|"
  5068. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5069. "\\|"
  5070. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5071. "The regular expression matching a sub- or superscript.")
  5072. (defconst org-match-substring-with-braces-regexp
  5073. (concat
  5074. "\\(\\S-\\)\\([_^]\\)"
  5075. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5076. "The regular expression matching a sub- or superscript, forcing braces.")
  5077. (defun org-make-link-regexps ()
  5078. "Update the link regular expressions.
  5079. This should be called after the variable `org-link-parameters' has changed."
  5080. (let ((types-re (regexp-opt (org-link-types) t)))
  5081. (setq org-link-types-re
  5082. (concat "\\`" types-re ":")
  5083. org-link-re-with-space
  5084. (concat "<?" types-re ":"
  5085. "\\([^" org-non-link-chars " ]"
  5086. "[^" org-non-link-chars "]*"
  5087. "[^" org-non-link-chars " ]\\)>?")
  5088. org-link-re-with-space2
  5089. (concat "<?" types-re ":"
  5090. "\\([^" org-non-link-chars " ]"
  5091. "[^\t\n\r]*"
  5092. "[^" org-non-link-chars " ]\\)>?")
  5093. org-link-re-with-space3
  5094. (concat "<?" types-re ":"
  5095. "\\([^" org-non-link-chars " ]"
  5096. "[^\t\n\r]*\\)")
  5097. org-angle-link-re
  5098. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5099. types-re)
  5100. org-plain-link-re
  5101. (concat
  5102. "\\<" types-re ":"
  5103. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5104. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5105. org-bracket-link-regexp
  5106. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5107. org-bracket-link-analytic-regexp
  5108. (concat
  5109. "\\[\\["
  5110. "\\(" types-re ":\\)?"
  5111. "\\([^]]+\\)"
  5112. "\\]"
  5113. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5114. "\\]")
  5115. org-bracket-link-analytic-regexp++
  5116. (concat
  5117. "\\[\\["
  5118. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5119. "\\([^]]+\\)"
  5120. "\\]"
  5121. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5122. "\\]")
  5123. org-any-link-re
  5124. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5125. org-angle-link-re "\\)\\|\\("
  5126. org-plain-link-re "\\)"))))
  5127. (org-make-link-regexps)
  5128. (defvar org-emph-face nil)
  5129. (defun org-do-emphasis-faces (limit)
  5130. "Run through the buffer and emphasize strings."
  5131. (let (rtn a)
  5132. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5133. (let* ((border (char-after (match-beginning 3)))
  5134. (bre (regexp-quote (char-to-string border))))
  5135. (when (and (not (= border (char-after (match-beginning 4))))
  5136. (not (string-match-p (concat bre ".*" bre)
  5137. (replace-regexp-in-string
  5138. "\n" " "
  5139. (substring (match-string 2) 1 -1)))))
  5140. (setq rtn t)
  5141. (setq a (assoc (match-string 3) org-emphasis-alist))
  5142. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5143. 'face
  5144. (nth 1 a))
  5145. (and (nth 2 a)
  5146. (org-remove-flyspell-overlays-in
  5147. (match-beginning 0) (match-end 0)))
  5148. (add-text-properties (match-beginning 2) (match-end 2)
  5149. '(font-lock-multiline t org-emphasis t))
  5150. (when org-hide-emphasis-markers
  5151. (add-text-properties (match-end 4) (match-beginning 5)
  5152. '(invisible org-link))
  5153. (add-text-properties (match-beginning 3) (match-end 3)
  5154. '(invisible org-link)))))
  5155. (goto-char (1+ (match-beginning 0))))
  5156. rtn))
  5157. (defun org-emphasize (&optional char)
  5158. "Insert or change an emphasis, i.e. a font like bold or italic.
  5159. If there is an active region, change that region to a new emphasis.
  5160. If there is no region, just insert the marker characters and position
  5161. the cursor between them.
  5162. CHAR should be the marker character. If it is a space, it means to
  5163. remove the emphasis of the selected region.
  5164. If CHAR is not given (for example in an interactive call) it will be
  5165. prompted for."
  5166. (interactive)
  5167. (let ((erc org-emphasis-regexp-components)
  5168. (string "") beg end move s)
  5169. (if (org-region-active-p)
  5170. (setq beg (region-beginning)
  5171. end (region-end)
  5172. string (buffer-substring beg end))
  5173. (setq move t))
  5174. (unless char
  5175. (message "Emphasis marker or tag: [%s]"
  5176. (mapconcat #'car org-emphasis-alist ""))
  5177. (setq char (read-char-exclusive)))
  5178. (if (equal char ?\s)
  5179. (setq s ""
  5180. move nil)
  5181. (unless (assoc (char-to-string char) org-emphasis-alist)
  5182. (user-error "No such emphasis marker: \"%c\"" char))
  5183. (setq s (char-to-string char)))
  5184. (while (and (> (length string) 1)
  5185. (equal (substring string 0 1) (substring string -1))
  5186. (assoc (substring string 0 1) org-emphasis-alist))
  5187. (setq string (substring string 1 -1)))
  5188. (setq string (concat s string s))
  5189. (when beg (delete-region beg end))
  5190. (unless (or (bolp)
  5191. (string-match (concat "[" (nth 0 erc) "\n]")
  5192. (char-to-string (char-before (point)))))
  5193. (insert " "))
  5194. (unless (or (eobp)
  5195. (string-match (concat "[" (nth 1 erc) "\n]")
  5196. (char-to-string (char-after (point)))))
  5197. (insert " ") (backward-char 1))
  5198. (insert string)
  5199. (and move (backward-char 1))))
  5200. (defconst org-nonsticky-props
  5201. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5202. (defsubst org-rear-nonsticky-at (pos)
  5203. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5204. (defun org-activate-plain-links (limit)
  5205. "Add link properties for plain links."
  5206. (when (and (re-search-forward org-plain-link-re limit t)
  5207. (not (org-in-src-block-p)))
  5208. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5209. 'face))
  5210. (link (match-string-no-properties 0))
  5211. (type (match-string-no-properties 1))
  5212. (path (match-string-no-properties 2))
  5213. (link-start (match-beginning 0))
  5214. (link-end (match-end 0))
  5215. (link-face (org-link-get-parameter type :face))
  5216. (help-echo (org-link-get-parameter type :help-echo))
  5217. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5218. (activate-func (org-link-get-parameter type :activate-func)))
  5219. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5220. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5221. (add-text-properties (match-beginning 0) (match-end 0)
  5222. (list
  5223. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5224. 'highlight)
  5225. 'face (cond
  5226. ;; A function that returns a face
  5227. ((functionp link-face)
  5228. (funcall link-face path))
  5229. ;; a face
  5230. ((facep link-face)
  5231. link-face)
  5232. ;; An anonymous face
  5233. ((consp link-face)
  5234. link-face)
  5235. ;; default
  5236. (t
  5237. 'org-link))
  5238. 'help-echo (cond
  5239. ((stringp help-echo)
  5240. help-echo)
  5241. ((functionp help-echo)
  5242. help-echo)
  5243. (t
  5244. (concat "LINK: "
  5245. (save-match-data
  5246. (org-link-unescape link)))))
  5247. 'htmlize-link (cond
  5248. ((functionp htmlize-link)
  5249. (funcall htmlize-link path))
  5250. (t
  5251. `(:uri ,link)))
  5252. 'keymap (or (org-link-get-parameter type :keymap)
  5253. org-mouse-map)
  5254. 'org-link-start (match-beginning 0)))
  5255. (org-rear-nonsticky-at (match-end 0))
  5256. (when activate-func
  5257. (funcall activate-func link-start link-end path nil))
  5258. t))))
  5259. (defun org-activate-code (limit)
  5260. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5261. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5262. (remove-text-properties (match-beginning 0) (match-end 0)
  5263. '(display t invisible t intangible t))
  5264. t))
  5265. (defcustom org-src-fontify-natively t
  5266. "When non-nil, fontify code in code blocks.
  5267. See also the `org-block' face."
  5268. :type 'boolean
  5269. :version "24.4"
  5270. :package-version '(Org . "8.3")
  5271. :group 'org-appearance
  5272. :group 'org-babel)
  5273. (defcustom org-allow-promoting-top-level-subtree nil
  5274. "When non-nil, allow promoting a top level subtree.
  5275. The leading star of the top level headline will be replaced
  5276. by a #."
  5277. :type 'boolean
  5278. :version "24.1"
  5279. :group 'org-appearance)
  5280. (defun org-fontify-meta-lines-and-blocks (limit)
  5281. (condition-case nil
  5282. (org-fontify-meta-lines-and-blocks-1 limit)
  5283. (error (message "org-mode fontification error in %S at %d"
  5284. (current-buffer)
  5285. (line-number-at-pos)))))
  5286. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5287. "Fontify #+ lines and blocks."
  5288. (let ((case-fold-search t))
  5289. (when (re-search-forward
  5290. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5291. limit t)
  5292. (let ((beg (match-beginning 0))
  5293. (block-start (match-end 0))
  5294. (block-end nil)
  5295. (lang (match-string 7))
  5296. (beg1 (line-beginning-position 2))
  5297. (dc1 (downcase (match-string 2)))
  5298. (dc3 (downcase (match-string 3)))
  5299. end end1 quoting block-type)
  5300. (cond
  5301. ((and (match-end 4) (equal dc3 "+begin"))
  5302. ;; Truly a block
  5303. (setq block-type (downcase (match-string 5))
  5304. quoting (member block-type org-protecting-blocks))
  5305. (when (re-search-forward
  5306. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5307. nil t) ;; on purpose, we look further than LIMIT
  5308. (setq end (min (point-max) (match-end 0))
  5309. end1 (min (point-max) (1- (match-beginning 0))))
  5310. (setq block-end (match-beginning 0))
  5311. (when quoting
  5312. (org-remove-flyspell-overlays-in beg1 end1)
  5313. (remove-text-properties beg end
  5314. '(display t invisible t intangible t)))
  5315. (add-text-properties
  5316. beg end '(font-lock-fontified t font-lock-multiline t))
  5317. (add-text-properties beg beg1 '(face org-meta-line))
  5318. (org-remove-flyspell-overlays-in beg beg1)
  5319. (add-text-properties ; For end_src
  5320. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5321. (org-remove-flyspell-overlays-in end1 end)
  5322. (cond
  5323. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5324. (org-src-font-lock-fontify-block lang block-start block-end)
  5325. (add-text-properties beg1 block-end '(src-block t)))
  5326. (quoting
  5327. (add-text-properties beg1 (min (point-max) (1+ end1))
  5328. (list 'face
  5329. (list :inherit
  5330. (let ((face-name
  5331. (intern (format "org-block-%s" lang))))
  5332. (append (and (facep face-name) (list face-name))
  5333. '(org-block))))))) ; end of source block
  5334. ((not org-fontify-quote-and-verse-blocks))
  5335. ((string= block-type "quote")
  5336. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5337. ((string= block-type "verse")
  5338. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5339. (add-text-properties beg beg1 '(face org-block-begin-line))
  5340. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5341. '(face org-block-end-line))
  5342. t))
  5343. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5344. (org-remove-flyspell-overlays-in
  5345. (match-beginning 0)
  5346. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5347. (add-text-properties
  5348. beg (match-end 3)
  5349. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5350. '(font-lock-fontified t invisible t)
  5351. '(font-lock-fontified t face org-document-info-keyword)))
  5352. (add-text-properties
  5353. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5354. (if (string-equal dc1 "+title:")
  5355. '(font-lock-fontified t face org-document-title)
  5356. '(font-lock-fontified t face org-document-info))))
  5357. ((string-prefix-p "+caption" dc1)
  5358. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5359. (remove-text-properties (match-beginning 0) (match-end 0)
  5360. '(display t invisible t intangible t))
  5361. ;; Handle short captions.
  5362. (save-excursion
  5363. (beginning-of-line)
  5364. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5365. (add-text-properties (line-beginning-position) (match-end 1)
  5366. '(font-lock-fontified t face org-meta-line))
  5367. (add-text-properties (match-end 0) (line-end-position)
  5368. '(font-lock-fontified t face org-block))
  5369. t)
  5370. ((member dc3 '(" " ""))
  5371. (org-remove-flyspell-overlays-in beg (match-end 0))
  5372. (add-text-properties
  5373. beg (match-end 0)
  5374. '(font-lock-fontified t face font-lock-comment-face)))
  5375. (t ;; just any other in-buffer setting, but not indented
  5376. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5377. (remove-text-properties (match-beginning 0) (match-end 0)
  5378. '(display t invisible t intangible t))
  5379. (add-text-properties beg (match-end 0)
  5380. '(font-lock-fontified t face org-meta-line))
  5381. t))))))
  5382. (defun org-fontify-drawers (limit)
  5383. "Fontify drawers."
  5384. (when (re-search-forward org-drawer-regexp limit t)
  5385. (add-text-properties
  5386. (match-beginning 0) (match-end 0)
  5387. '(font-lock-fontified t face org-special-keyword))
  5388. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5389. t))
  5390. (defun org-fontify-macros (limit)
  5391. "Fontify macros."
  5392. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5393. (add-text-properties
  5394. (match-beginning 0) (match-end 0)
  5395. '(font-lock-fontified t face org-macro))
  5396. (when org-hide-macro-markers
  5397. (add-text-properties (match-end 2) (match-beginning 2)
  5398. '(invisible t))
  5399. (add-text-properties (match-beginning 1) (match-end 1)
  5400. '(invisible t)))
  5401. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5402. t))
  5403. (defun org-activate-angle-links (limit)
  5404. "Add text properties for angle links."
  5405. (when (and (re-search-forward org-angle-link-re limit t)
  5406. (not (org-in-src-block-p)))
  5407. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5408. (add-text-properties (match-beginning 0) (match-end 0)
  5409. (list 'mouse-face 'highlight
  5410. 'keymap org-mouse-map
  5411. 'font-lock-multiline t))
  5412. (org-rear-nonsticky-at (match-end 0))
  5413. t))
  5414. (defun org-activate-footnote-links (limit)
  5415. "Add text properties for footnotes."
  5416. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5417. (when fn
  5418. (let* ((beg (nth 1 fn))
  5419. (end (nth 2 fn))
  5420. (label (car fn))
  5421. (referencep (/= (line-beginning-position) beg)))
  5422. (when (and referencep (nth 3 fn))
  5423. (save-excursion
  5424. (goto-char beg)
  5425. (search-forward (or label "fn:"))
  5426. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5427. (add-text-properties beg end
  5428. (list 'mouse-face 'highlight
  5429. 'keymap org-mouse-map
  5430. 'help-echo
  5431. (if referencep "Footnote reference"
  5432. "Footnote definition")
  5433. 'font-lock-fontified t
  5434. 'font-lock-multiline t
  5435. 'face 'org-footnote))))))
  5436. (defun org-activate-bracket-links (limit)
  5437. "Add text properties for bracketed links."
  5438. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5439. (not (org-in-src-block-p)))
  5440. (let* ((hl (save-match-data
  5441. (org-link-expand-abbrev (match-string-no-properties 1))))
  5442. (type (save-match-data
  5443. (and (string-match org-plain-link-re hl)
  5444. (match-string-no-properties 1 hl))))
  5445. (path (save-match-data
  5446. (and (string-match org-plain-link-re hl)
  5447. (match-string-no-properties 2 hl))))
  5448. (link-start (match-beginning 0))
  5449. (link-end (match-end 0))
  5450. (bracketp t)
  5451. (help-echo (org-link-get-parameter type :help-echo))
  5452. (help (cond
  5453. ((stringp help-echo)
  5454. help-echo)
  5455. ((functionp help-echo)
  5456. help-echo)
  5457. (t
  5458. (concat "LINK: "
  5459. (save-match-data
  5460. (org-link-unescape hl))))))
  5461. (link-face (org-link-get-parameter type :face))
  5462. (face (cond
  5463. ;; A function that returns a face
  5464. ((functionp link-face)
  5465. (funcall link-face path))
  5466. ;; a face
  5467. ((facep link-face)
  5468. link-face)
  5469. ;; An anonymous face
  5470. ((consp link-face)
  5471. link-face)
  5472. ;; default
  5473. (t
  5474. 'org-link)))
  5475. (keymap (or (org-link-get-parameter type :keymap)
  5476. org-mouse-map))
  5477. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5478. 'highlight))
  5479. (htmlize (org-link-get-parameter type :htmlize-link))
  5480. (htmlize-link (cond
  5481. ((functionp htmlize)
  5482. (funcall htmlize))
  5483. (t
  5484. `(:uri ,(format "%s:%s" type path)))))
  5485. (activate-func (org-link-get-parameter type :activate-func))
  5486. ;; invisible part
  5487. (ip (list 'invisible (or
  5488. (org-link-get-parameter type :display)
  5489. 'org-link)
  5490. 'face face
  5491. 'keymap keymap
  5492. 'mouse-face mouse-face
  5493. 'font-lock-multiline t
  5494. 'help-echo help
  5495. 'htmlize-link htmlize-link))
  5496. ;; visible part
  5497. (vp (list 'keymap keymap
  5498. 'face face
  5499. 'mouse-face mouse-face
  5500. 'font-lock-multiline t
  5501. 'help-echo help
  5502. 'htmlize-link htmlize-link)))
  5503. ;; We need to remove the invisible property here. Table narrowing
  5504. ;; may have made some of this invisible.
  5505. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5506. (remove-text-properties (match-beginning 0) (match-end 0)
  5507. '(invisible nil))
  5508. (if (match-end 3)
  5509. (progn
  5510. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5511. (org-rear-nonsticky-at (match-beginning 3))
  5512. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5513. (org-rear-nonsticky-at (match-end 3))
  5514. (add-text-properties (match-end 3) (match-end 0) ip)
  5515. (org-rear-nonsticky-at (match-end 0)))
  5516. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5517. (org-rear-nonsticky-at (match-beginning 1))
  5518. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5519. (org-rear-nonsticky-at (match-end 1))
  5520. (add-text-properties (match-end 1) (match-end 0) ip)
  5521. (org-rear-nonsticky-at (match-end 0)))
  5522. (when activate-func
  5523. (funcall activate-func link-start link-end path bracketp))
  5524. t)))
  5525. (defun org-activate-dates (limit)
  5526. "Add text properties for dates."
  5527. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5528. (not (equal (char-before (match-beginning 0)) 91)))
  5529. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5530. (add-text-properties (match-beginning 0) (match-end 0)
  5531. (list 'mouse-face 'highlight
  5532. 'keymap org-mouse-map))
  5533. (org-rear-nonsticky-at (match-end 0))
  5534. (when org-display-custom-times
  5535. (if (match-end 3)
  5536. (org-display-custom-time (match-beginning 3) (match-end 3))
  5537. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5538. t))
  5539. (defvar-local org-target-link-regexp nil
  5540. "Regular expression matching radio targets in plain text.")
  5541. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5542. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5543. border border border))
  5544. "Regular expression matching a link target.")
  5545. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5546. "Regular expression matching a radio target.")
  5547. (defconst org-any-target-regexp
  5548. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5549. "Regular expression matching any target.")
  5550. (defun org-activate-target-links (limit)
  5551. "Add text properties for target matches."
  5552. (when org-target-link-regexp
  5553. (let ((case-fold-search t))
  5554. (when (re-search-forward org-target-link-regexp limit t)
  5555. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5556. (add-text-properties (match-beginning 1) (match-end 1)
  5557. (list 'mouse-face 'highlight
  5558. 'keymap org-mouse-map
  5559. 'help-echo "Radio target link"
  5560. 'org-linked-text t))
  5561. (org-rear-nonsticky-at (match-end 1))
  5562. t))))
  5563. (defun org-update-radio-target-regexp ()
  5564. "Find all radio targets in this file and update the regular expression.
  5565. Also refresh fontification if needed."
  5566. (interactive)
  5567. (let ((old-regexp org-target-link-regexp)
  5568. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5569. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5570. (targets
  5571. (org-with-wide-buffer
  5572. (goto-char (point-min))
  5573. (let (rtn)
  5574. (while (re-search-forward org-radio-target-regexp nil t)
  5575. ;; Make sure point is really within the object.
  5576. (backward-char)
  5577. (let ((obj (org-element-context)))
  5578. (when (eq (org-element-type obj) 'radio-target)
  5579. (cl-pushnew (org-element-property :value obj) rtn
  5580. :test #'equal))))
  5581. rtn))))
  5582. (setq org-target-link-regexp
  5583. (and targets
  5584. (concat before-re
  5585. (mapconcat
  5586. (lambda (x)
  5587. (replace-regexp-in-string
  5588. " +" "\\s-+" (regexp-quote x) t t))
  5589. targets
  5590. "\\|")
  5591. after-re)))
  5592. (unless (equal old-regexp org-target-link-regexp)
  5593. ;; Clean-up cache.
  5594. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5595. ((not org-target-link-regexp) old-regexp)
  5596. (t
  5597. (concat before-re
  5598. (mapconcat
  5599. (lambda (re)
  5600. (substring re (length before-re)
  5601. (- (length after-re))))
  5602. (list old-regexp org-target-link-regexp)
  5603. "\\|")
  5604. after-re)))))
  5605. (org-with-wide-buffer
  5606. (goto-char (point-min))
  5607. (while (re-search-forward regexp nil t)
  5608. (org-element-cache-refresh (match-beginning 1)))))
  5609. ;; Re fontify buffer.
  5610. (when (memq 'radio org-highlight-links)
  5611. (org-restart-font-lock)))))
  5612. (defun org-hide-wide-columns (limit)
  5613. (let (s e)
  5614. (setq s (text-property-any (point) (or limit (point-max))
  5615. 'org-cwidth t))
  5616. (when s
  5617. (setq e (next-single-property-change s 'org-cwidth))
  5618. (add-text-properties s e '(invisible org-cwidth))
  5619. (goto-char e)
  5620. t)))
  5621. (defvar org-latex-and-related-regexp nil
  5622. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5623. (defun org-compute-latex-and-related-regexp ()
  5624. "Compute regular expression for LaTeX, entities and sub/superscript.
  5625. Result depends on variable `org-highlight-latex-and-related'."
  5626. (setq-local
  5627. org-latex-and-related-regexp
  5628. (let* ((re-sub
  5629. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5630. ((eq org-use-sub-superscripts '{})
  5631. (list org-match-substring-with-braces-regexp))
  5632. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5633. (re-latex
  5634. (when (memq 'latex org-highlight-latex-and-related)
  5635. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5636. (delq nil
  5637. (mapcar (lambda (x)
  5638. (and (member (car x) matchers) (nth 1 x)))
  5639. org-latex-regexps)))))
  5640. (re-entities
  5641. (when (memq 'entities org-highlight-latex-and-related)
  5642. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5643. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5644. (defun org-do-latex-and-related (limit)
  5645. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5646. LIMIT bounds the search for syntax to highlight. Stop at first
  5647. highlighted object, if any. Return t if some highlighting was
  5648. done, nil otherwise."
  5649. (when (org-string-nw-p org-latex-and-related-regexp)
  5650. (catch 'found
  5651. (while (re-search-forward org-latex-and-related-regexp limit t)
  5652. (unless
  5653. (cl-some
  5654. (lambda (f)
  5655. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5656. (save-excursion
  5657. (goto-char (1+ (match-beginning 0)))
  5658. (face-at-point nil t)))
  5659. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5660. '(?_ ?^))
  5661. 1
  5662. 0)))
  5663. (font-lock-prepend-text-property
  5664. (+ offset (match-beginning 0)) (match-end 0)
  5665. 'face 'org-latex-and-related)
  5666. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5667. '(font-lock-multiline t)))
  5668. (throw 'found t)))
  5669. nil)))
  5670. (defun org-restart-font-lock ()
  5671. "Restart `font-lock-mode', to force refontification."
  5672. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5673. (font-lock-mode -1)
  5674. (font-lock-mode 1)))
  5675. (defun org-activate-tags (limit)
  5676. (when (re-search-forward
  5677. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5678. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5679. (add-text-properties (match-beginning 1) (match-end 1)
  5680. (list 'mouse-face 'highlight
  5681. 'keymap org-mouse-map))
  5682. (org-rear-nonsticky-at (match-end 1))
  5683. t))
  5684. (defun org-outline-level ()
  5685. "Compute the outline level of the heading at point.
  5686. If this is called at a normal headline, the level is the number
  5687. of stars. Use `org-reduced-level' to remove the effect of
  5688. `org-odd-levels'. Unlike to `org-current-level', this function
  5689. takes into consideration inlinetasks."
  5690. (org-with-wide-buffer
  5691. (end-of-line)
  5692. (if (re-search-backward org-outline-regexp-bol nil t)
  5693. (1- (- (match-end 0) (match-beginning 0)))
  5694. 0)))
  5695. (defvar org-font-lock-keywords nil)
  5696. (defsubst org-re-property (property &optional literal allow-null value)
  5697. "Return a regexp matching a PROPERTY line.
  5698. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5699. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5700. non-nil, match properties even without a value.
  5701. Match group 3 is set to the value when it exists. If there is no
  5702. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5703. With optional argument VALUE, match only property lines with
  5704. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5705. unless LITERAL is non-nil."
  5706. (concat
  5707. "^\\(?4:[ \t]*\\)"
  5708. (format "\\(?1::\\(?2:%s\\):\\)"
  5709. (if literal property (regexp-quote property)))
  5710. (cond (value
  5711. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5712. (if literal value (regexp-quote value))))
  5713. (allow-null
  5714. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5715. (t
  5716. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5717. (defconst org-property-re
  5718. (org-re-property "\\S-+" 'literal t)
  5719. "Regular expression matching a property line.
  5720. There are four matching groups:
  5721. 1: :PROPKEY: including the leading and trailing colon,
  5722. 2: PROPKEY without the leading and trailing colon,
  5723. 3: PROPVAL without leading or trailing spaces,
  5724. 4: the indentation of the current line,
  5725. 5: trailing whitespace.")
  5726. (defvar org-font-lock-hook nil
  5727. "Functions to be called for special font lock stuff.")
  5728. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5729. (defvar org-font-lock-set-keywords-hook nil
  5730. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5731. This is called after `org-font-lock-extra-keywords' is defined, but before
  5732. it is installed to be used by font lock. This can be useful if something
  5733. needs to be inserted at a specific position in the font-lock sequence.")
  5734. (defun org-font-lock-hook (limit)
  5735. "Run `org-font-lock-hook' within LIMIT."
  5736. (run-hook-with-args 'org-font-lock-hook limit))
  5737. (defun org-set-font-lock-defaults ()
  5738. "Set font lock defaults for the current buffer."
  5739. (let* ((em org-fontify-emphasized-text)
  5740. (lk org-highlight-links)
  5741. (org-font-lock-extra-keywords
  5742. (list
  5743. ;; Call the hook
  5744. '(org-font-lock-hook)
  5745. ;; Headlines
  5746. `(,(if org-fontify-whole-heading-line
  5747. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5748. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5749. (1 (org-get-level-face 1))
  5750. (2 (org-get-level-face 2))
  5751. (3 (org-get-level-face 3)))
  5752. ;; Table lines
  5753. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5754. (1 'org-table t))
  5755. ;; Table internals
  5756. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5757. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5758. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5759. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5760. ;; Drawers
  5761. '(org-fontify-drawers)
  5762. ;; Properties
  5763. (list org-property-re
  5764. '(1 'org-special-keyword t)
  5765. '(3 'org-property-value t))
  5766. ;; Links
  5767. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5768. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5769. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5770. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5771. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5772. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5773. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5774. ;; Targets.
  5775. (list org-any-target-regexp '(0 'org-target t))
  5776. ;; Diary sexps.
  5777. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5778. ;; Macro
  5779. '(org-fontify-macros)
  5780. '(org-hide-wide-columns (0 nil append))
  5781. ;; TODO keyword
  5782. (list (format org-heading-keyword-regexp-format
  5783. org-todo-regexp)
  5784. '(2 (org-get-todo-face 2) t))
  5785. ;; DONE
  5786. (if org-fontify-done-headline
  5787. (list (format org-heading-keyword-regexp-format
  5788. (concat
  5789. "\\(?:"
  5790. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5791. "\\)"))
  5792. '(2 'org-headline-done t))
  5793. nil)
  5794. ;; Priorities
  5795. '(org-font-lock-add-priority-faces)
  5796. ;; Tags
  5797. '(org-font-lock-add-tag-faces)
  5798. ;; Tags groups
  5799. (when (and org-group-tags org-tag-groups-alist)
  5800. (list (concat org-outline-regexp-bol ".+\\(:"
  5801. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5802. ":\\).*$")
  5803. '(1 'org-tag-group prepend)))
  5804. ;; Special keywords
  5805. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5806. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5807. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5808. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5809. ;; Emphasis
  5810. (when em '(org-do-emphasis-faces))
  5811. ;; Checkboxes
  5812. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5813. 1 'org-checkbox prepend)
  5814. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5815. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5816. (0 (org-get-checkbox-statistics-face) t)))
  5817. ;; Description list items
  5818. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5819. 1 'org-list-dt prepend)
  5820. ;; ARCHIVEd headings
  5821. (list (concat
  5822. org-outline-regexp-bol
  5823. "\\(.*:" org-archive-tag ":.*\\)")
  5824. '(1 'org-archived prepend))
  5825. ;; Specials
  5826. '(org-do-latex-and-related)
  5827. '(org-fontify-entities)
  5828. '(org-raise-scripts)
  5829. ;; Code
  5830. '(org-activate-code (1 'org-code t))
  5831. ;; COMMENT
  5832. (list (format
  5833. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5834. org-todo-regexp
  5835. org-comment-string)
  5836. '(9 'org-special-keyword t))
  5837. ;; Blocks and meta lines
  5838. '(org-fontify-meta-lines-and-blocks))))
  5839. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5840. (run-hooks 'org-font-lock-set-keywords-hook)
  5841. ;; Now set the full font-lock-keywords
  5842. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5843. (setq-local font-lock-defaults
  5844. '(org-font-lock-keywords t nil nil backward-paragraph))
  5845. (kill-local-variable 'font-lock-keywords)
  5846. nil))
  5847. (defun org-toggle-pretty-entities ()
  5848. "Toggle the composition display of entities as UTF8 characters."
  5849. (interactive)
  5850. (setq-local org-pretty-entities (not org-pretty-entities))
  5851. (org-restart-font-lock)
  5852. (if org-pretty-entities
  5853. (message "Entities are now displayed as UTF8 characters")
  5854. (save-restriction
  5855. (widen)
  5856. (decompose-region (point-min) (point-max))
  5857. (message "Entities are now displayed as plain text"))))
  5858. (defvar-local org-custom-properties-overlays nil
  5859. "List of overlays used for custom properties.")
  5860. (defun org-toggle-custom-properties-visibility ()
  5861. "Display or hide properties in `org-custom-properties'."
  5862. (interactive)
  5863. (if org-custom-properties-overlays
  5864. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5865. (setq org-custom-properties-overlays nil))
  5866. (when org-custom-properties
  5867. (org-with-wide-buffer
  5868. (goto-char (point-min))
  5869. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5870. (while (re-search-forward regexp nil t)
  5871. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5872. (when (and end (< (point) end))
  5873. ;; Hide first custom property in current drawer.
  5874. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5875. (overlay-put o 'invisible t)
  5876. (overlay-put o 'org-custom-property t)
  5877. (push o org-custom-properties-overlays))
  5878. ;; Hide additional custom properties in the same drawer.
  5879. (while (re-search-forward regexp end t)
  5880. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5881. (overlay-put o 'invisible t)
  5882. (overlay-put o 'org-custom-property t)
  5883. (push o org-custom-properties-overlays)))))
  5884. ;; Each entry is limited to a single property drawer.
  5885. (outline-next-heading)))))))
  5886. (defun org-fontify-entities (limit)
  5887. "Find an entity to fontify."
  5888. (let (ee)
  5889. (when org-pretty-entities
  5890. (catch 'match
  5891. ;; "\_ "-family is left out on purpose. Only the first one,
  5892. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5893. ;; confusing when adding a second white space character.
  5894. (while (re-search-forward
  5895. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5896. limit t)
  5897. (when (and (not (org-at-comment-p))
  5898. (setq ee (org-entity-get (match-string 1)))
  5899. (= (length (nth 6 ee)) 1))
  5900. (let* ((end (if (equal (match-string 2) "{}")
  5901. (match-end 2)
  5902. (match-end 1))))
  5903. (add-text-properties
  5904. (match-beginning 0) end
  5905. (list 'font-lock-fontified t))
  5906. (compose-region (match-beginning 0) end
  5907. (nth 6 ee) nil)
  5908. (backward-char 1)
  5909. (throw 'match t))))
  5910. nil))))
  5911. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5912. "Fontify string S like in Org mode."
  5913. (with-temp-buffer
  5914. (insert s)
  5915. (let ((org-odd-levels-only odd-levels))
  5916. (org-mode)
  5917. (org-font-lock-ensure)
  5918. (buffer-string))))
  5919. (defvar org-m nil)
  5920. (defvar org-l nil)
  5921. (defvar org-f nil)
  5922. (defun org-get-level-face (n)
  5923. "Get the right face for match N in font-lock matching of headlines."
  5924. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5925. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5926. (if org-cycle-level-faces
  5927. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5928. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5929. (cond
  5930. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5931. ((eq n 2) org-f)
  5932. (t (unless org-level-color-stars-only org-f))))
  5933. (defun org-face-from-face-or-color (context inherit face-or-color)
  5934. "Create a face list that inherits INHERIT, but sets the foreground color.
  5935. When FACE-OR-COLOR is not a string, just return it."
  5936. (if (stringp face-or-color)
  5937. (list :inherit inherit
  5938. (cdr (assoc context org-faces-easy-properties))
  5939. face-or-color)
  5940. face-or-color))
  5941. (defun org-get-todo-face (kwd)
  5942. "Get the right face for a TODO keyword KWD.
  5943. If KWD is a number, get the corresponding match group."
  5944. (when (numberp kwd) (setq kwd (match-string kwd)))
  5945. (or (org-face-from-face-or-color
  5946. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5947. (and (member kwd org-done-keywords) 'org-done)
  5948. 'org-todo))
  5949. (defun org-get-priority-face (priority)
  5950. "Get the right face for PRIORITY.
  5951. PRIORITY is a character."
  5952. (or (org-face-from-face-or-color
  5953. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5954. 'org-priority))
  5955. (defun org-get-tag-face (tag)
  5956. "Get the right face for TAG.
  5957. If TAG is a number, get the corresponding match group."
  5958. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5959. (or (org-face-from-face-or-color
  5960. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5961. 'org-tag)))
  5962. (defun org-font-lock-add-priority-faces (limit)
  5963. "Add the special priority faces."
  5964. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5965. (add-text-properties
  5966. (match-beginning 1) (match-end 1)
  5967. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5968. 'font-lock-fontified t))))
  5969. (defun org-font-lock-add-tag-faces (limit)
  5970. "Add the special tag faces."
  5971. (when (and org-tag-faces org-tags-special-faces-re)
  5972. (while (re-search-forward org-tags-special-faces-re limit t)
  5973. (add-text-properties (match-beginning 1) (match-end 1)
  5974. (list 'face (org-get-tag-face 1)
  5975. 'font-lock-fontified t))
  5976. (backward-char 1))))
  5977. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5978. "Remove fontification and activation overlays from links."
  5979. (font-lock-default-unfontify-region beg end)
  5980. (let* ((buffer-undo-list t)
  5981. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5982. (inhibit-modification-hooks t)
  5983. deactivate-mark buffer-file-name buffer-file-truename)
  5984. (decompose-region beg end)
  5985. (remove-text-properties beg end
  5986. '(mouse-face t keymap t org-linked-text t
  5987. invisible t intangible t
  5988. org-emphasis t))
  5989. (org-remove-font-lock-display-properties beg end)))
  5990. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5991. ((raise 0.3) (height 0.7))
  5992. ((raise -0.5))
  5993. ((raise 0.5)))
  5994. "Display properties for showing superscripts and subscripts.")
  5995. (defun org-remove-font-lock-display-properties (beg end)
  5996. "Remove specific display properties that have been added by font lock.
  5997. The will remove the raise properties that are used to show superscripts
  5998. and subscripts."
  5999. (let (next prop)
  6000. (while (< beg end)
  6001. (setq next (next-single-property-change beg 'display nil end)
  6002. prop (get-text-property beg 'display))
  6003. (when (member prop org-script-display)
  6004. (put-text-property beg next 'display nil))
  6005. (setq beg next))))
  6006. (defun org-raise-scripts (limit)
  6007. "Add raise properties to sub/superscripts."
  6008. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  6009. (re-search-forward
  6010. (if (eq org-use-sub-superscripts t)
  6011. org-match-substring-regexp
  6012. org-match-substring-with-braces-regexp)
  6013. limit t))
  6014. (let* ((pos (point)) table-p comment-p
  6015. (mpos (match-beginning 3))
  6016. (emph-p (get-text-property mpos 'org-emphasis))
  6017. (link-p (get-text-property mpos 'mouse-face))
  6018. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  6019. (goto-char (point-at-bol))
  6020. (setq table-p (looking-at-p org-table-dataline-regexp)
  6021. comment-p (looking-at-p "^[ \t]*#[ +]"))
  6022. (goto-char pos)
  6023. ;; Handle a_b^c
  6024. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  6025. (unless (or comment-p emph-p link-p keyw-p)
  6026. (put-text-property (match-beginning 3) (match-end 0)
  6027. 'display
  6028. (if (equal (char-after (match-beginning 2)) ?^)
  6029. (nth (if table-p 3 1) org-script-display)
  6030. (nth (if table-p 2 0) org-script-display)))
  6031. (add-text-properties (match-beginning 2) (match-end 2)
  6032. (list 'invisible t
  6033. 'org-dwidth t 'org-dwidth-n 1))
  6034. (if (and (eq (char-after (match-beginning 3)) ?{)
  6035. (eq (char-before (match-end 3)) ?}))
  6036. (progn
  6037. (add-text-properties
  6038. (match-beginning 3) (1+ (match-beginning 3))
  6039. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6040. (add-text-properties
  6041. (1- (match-end 3)) (match-end 3)
  6042. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6043. t)))
  6044. ;;;; Visibility cycling, including org-goto and indirect buffer
  6045. ;;; Cycling
  6046. (defvar-local org-cycle-global-status nil)
  6047. (put 'org-cycle-global-status 'org-state t)
  6048. (defvar-local org-cycle-subtree-status nil)
  6049. (put 'org-cycle-subtree-status 'org-state t)
  6050. (defvar org-inlinetask-min-level)
  6051. (defun org-unlogged-message (&rest args)
  6052. "Display a message, but avoid logging it in the *Messages* buffer."
  6053. (let ((message-log-max nil))
  6054. (apply 'message args)))
  6055. ;;;###autoload
  6056. (defun org-cycle (&optional arg)
  6057. "TAB-action and visibility cycling for Org mode.
  6058. This is the command invoked in Org mode by the `TAB' key. Its main
  6059. purpose is outline visibility cycling, but it also invokes other actions
  6060. in special contexts.
  6061. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6062. the entire
  6063. buffer through 3 states (global cycling)
  6064. 1. OVERVIEW: Show only top-level headlines.
  6065. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6066. 3. SHOW ALL: Show everything.
  6067. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6068. switch to the startup visibility,
  6069. determined by the variable `org-startup-folded', and by any VISIBILITY
  6070. properties in the buffer.
  6071. With a `\\[universal-argument] \\[universal-argument] \
  6072. \\[universal-argument]' prefix argument, show the entire buffer, including
  6073. any drawers.
  6074. When inside a table, re-align the table and move to the next field.
  6075. When point is at the beginning of a headline, rotate the subtree started
  6076. by this line through 3 different states (local cycling)
  6077. 1. FOLDED: Only the main headline is shown.
  6078. 2. CHILDREN: The main headline and the direct children are shown.
  6079. From this state, you can move to one of the children
  6080. and zoom in further.
  6081. 3. SUBTREE: Show the entire subtree, including body text.
  6082. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6083. When point is at the beginning of an empty headline and the variable
  6084. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6085. of the headline by demoting and promoting it to likely levels. This
  6086. speeds up creation document structure by pressing `TAB' once or several
  6087. times right after creating a new headline.
  6088. When there is a numeric prefix, go up to a heading with level ARG, do
  6089. a `show-subtree' and return to the previous cursor position. If ARG
  6090. is negative, go up that many levels.
  6091. When point is not at the beginning of a headline, execute the global
  6092. binding for `TAB', which is re-indenting the line. See the option
  6093. `org-cycle-emulate-tab' for details.
  6094. As a special case, if point is at the beginning of the buffer and there is
  6095. no headline in line 1, this function will act as if called with prefix arg
  6096. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6097. prefix arg, but only
  6098. if the variable `org-cycle-global-at-bob' is t."
  6099. (interactive "P")
  6100. (org-load-modules-maybe)
  6101. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6102. (and org-cycle-level-after-item/entry-creation
  6103. (or (org-cycle-level)
  6104. (org-cycle-item-indentation))))
  6105. (let* ((limit-level
  6106. (or org-cycle-max-level
  6107. (and (boundp 'org-inlinetask-min-level)
  6108. org-inlinetask-min-level
  6109. (1- org-inlinetask-min-level))))
  6110. (nstars (and limit-level
  6111. (if org-odd-levels-only
  6112. (and limit-level (1- (* limit-level 2)))
  6113. limit-level)))
  6114. (org-outline-regexp
  6115. (if (not (derived-mode-p 'org-mode))
  6116. outline-regexp
  6117. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6118. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6119. (not (looking-at org-outline-regexp))))
  6120. (org-cycle-hook
  6121. (if bob-special
  6122. (delq 'org-optimize-window-after-visibility-change
  6123. (copy-sequence org-cycle-hook))
  6124. org-cycle-hook))
  6125. (pos (point)))
  6126. (cond
  6127. ((equal arg '(16))
  6128. (setq last-command 'dummy)
  6129. (org-set-startup-visibility)
  6130. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6131. ((equal arg '(64))
  6132. (outline-show-all)
  6133. (org-unlogged-message "Entire buffer visible, including drawers"))
  6134. ((equal arg '(4)) (org-cycle-internal-global))
  6135. ;; Try hiding block at point.
  6136. ((org-hide-block-toggle-maybe))
  6137. ;; Try cdlatex TAB completion
  6138. ((org-try-cdlatex-tab))
  6139. ;; Table: enter it or move to the next field.
  6140. ((org-at-table-p 'any)
  6141. (if (org-at-table.el-p)
  6142. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6143. Use `\\[org-edit-special]' to edit table.el tables"))
  6144. (if arg (org-table-edit-field t)
  6145. (org-table-justify-field-maybe)
  6146. (call-interactively 'org-table-next-field))))
  6147. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6148. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6149. (bob-special (org-cycle-internal-global))
  6150. ;; Drawers: delegate to `org-flag-drawer'.
  6151. ((save-excursion
  6152. (beginning-of-line 1)
  6153. (looking-at org-drawer-regexp))
  6154. (org-flag-drawer ; toggle block visibility
  6155. (not (get-char-property (match-end 0) 'invisible))))
  6156. ;; Show-subtree, ARG levels up from here.
  6157. ((integerp arg)
  6158. (save-excursion
  6159. (org-back-to-heading)
  6160. (outline-up-heading (if (< arg 0) (- arg)
  6161. (- (funcall outline-level) arg)))
  6162. (org-show-subtree)))
  6163. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6164. ((and (featurep 'org-inlinetask)
  6165. (org-inlinetask-at-task-p)
  6166. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6167. (org-inlinetask-toggle-visibility))
  6168. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6169. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6170. (save-excursion (move-beginning-of-line 1)
  6171. (looking-at org-outline-regexp)))
  6172. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6173. (org-cycle-internal-local))
  6174. ;; From there: TAB emulation and template completion.
  6175. (buffer-read-only (org-back-to-heading))
  6176. ((run-hook-with-args-until-success
  6177. 'org-tab-after-check-for-cycling-hook))
  6178. ((org-try-structure-completion))
  6179. ((run-hook-with-args-until-success
  6180. 'org-tab-before-tab-emulation-hook))
  6181. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6182. (or (not (bolp))
  6183. (not (looking-at org-outline-regexp))))
  6184. (call-interactively (global-key-binding "\t")))
  6185. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6186. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6187. (or (and (eq org-cycle-emulate-tab 'white)
  6188. (= (match-end 0) (point-at-eol)))
  6189. (and (eq org-cycle-emulate-tab 'whitestart)
  6190. (>= (match-end 0) pos))))
  6191. t
  6192. (eq org-cycle-emulate-tab t))
  6193. (call-interactively (global-key-binding "\t")))
  6194. (t (save-excursion
  6195. (org-back-to-heading)
  6196. (org-cycle)))))))
  6197. (defun org-cycle-internal-global ()
  6198. "Do the global cycling action."
  6199. ;; Hack to avoid display of messages for .org attachments in Gnus
  6200. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6201. (cond
  6202. ((and (eq last-command this-command)
  6203. (eq org-cycle-global-status 'overview))
  6204. ;; We just created the overview - now do table of contents
  6205. ;; This can be slow in very large buffers, so indicate action
  6206. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6207. (unless ga (org-unlogged-message "CONTENTS..."))
  6208. (org-content)
  6209. (unless ga (org-unlogged-message "CONTENTS...done"))
  6210. (setq org-cycle-global-status 'contents)
  6211. (run-hook-with-args 'org-cycle-hook 'contents))
  6212. ((and (eq last-command this-command)
  6213. (eq org-cycle-global-status 'contents))
  6214. ;; We just showed the table of contents - now show everything
  6215. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6216. (outline-show-all)
  6217. (unless ga (org-unlogged-message "SHOW ALL"))
  6218. (setq org-cycle-global-status 'all)
  6219. (run-hook-with-args 'org-cycle-hook 'all))
  6220. (t
  6221. ;; Default action: go to overview
  6222. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6223. (org-overview)
  6224. (unless ga (org-unlogged-message "OVERVIEW"))
  6225. (setq org-cycle-global-status 'overview)
  6226. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6227. (defvar org-called-with-limited-levels nil
  6228. "Non-nil when `org-with-limited-levels' is currently active.")
  6229. (defun org-cycle-internal-local ()
  6230. "Do the local cycling action."
  6231. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6232. ;; First, determine end of headline (EOH), end of subtree or item
  6233. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6234. (save-excursion
  6235. (if (org-at-item-p)
  6236. (progn
  6237. (beginning-of-line)
  6238. (setq struct (org-list-struct))
  6239. (setq eoh (point-at-eol))
  6240. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6241. (setq has-children (org-list-has-child-p (point) struct)))
  6242. (org-back-to-heading)
  6243. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6244. (setq eos (save-excursion (org-end-of-subtree t t)
  6245. (when (bolp) (backward-char)) (point)))
  6246. (setq has-children
  6247. (or (save-excursion
  6248. (let ((level (funcall outline-level)))
  6249. (outline-next-heading)
  6250. (and (org-at-heading-p t)
  6251. (> (funcall outline-level) level))))
  6252. (save-excursion
  6253. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6254. ;; Determine end invisible part of buffer (EOL)
  6255. (beginning-of-line 2)
  6256. (while (and (not (eobp)) ;This is like `next-line'.
  6257. (get-char-property (1- (point)) 'invisible))
  6258. (goto-char (next-single-char-property-change (point) 'invisible))
  6259. (and (eolp) (beginning-of-line 2)))
  6260. (setq eol (point)))
  6261. ;; Find out what to do next and set `this-command'
  6262. (cond
  6263. ((= eos eoh)
  6264. ;; Nothing is hidden behind this heading
  6265. (unless (org-before-first-heading-p)
  6266. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6267. (org-unlogged-message "EMPTY ENTRY")
  6268. (setq org-cycle-subtree-status nil)
  6269. (save-excursion
  6270. (goto-char eos)
  6271. (outline-next-heading)
  6272. (when (outline-invisible-p) (org-flag-heading nil))))
  6273. ((and (or (>= eol eos)
  6274. (not (string-match "\\S-" (buffer-substring eol eos))))
  6275. (or has-children
  6276. (not (setq children-skipped
  6277. org-cycle-skip-children-state-if-no-children))))
  6278. ;; Entire subtree is hidden in one line: children view
  6279. (unless (org-before-first-heading-p)
  6280. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6281. (if (org-at-item-p)
  6282. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6283. (org-show-entry)
  6284. (org-with-limited-levels (org-show-children))
  6285. ;; FIXME: This slows down the func way too much.
  6286. ;; How keep drawers hidden in subtree anyway?
  6287. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6288. ;; (org-cycle-hide-drawers 'subtree))
  6289. ;; Fold every list in subtree to top-level items.
  6290. (when (eq org-cycle-include-plain-lists 'integrate)
  6291. (save-excursion
  6292. (org-back-to-heading)
  6293. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6294. (beginning-of-line 1)
  6295. (let* ((struct (org-list-struct))
  6296. (prevs (org-list-prevs-alist struct))
  6297. (end (org-list-get-bottom-point struct)))
  6298. (dolist (e (org-list-get-all-items (point) struct prevs))
  6299. (org-list-set-item-visibility e struct 'folded))
  6300. (goto-char (if (< end eos) end eos)))))))
  6301. (org-unlogged-message "CHILDREN")
  6302. (save-excursion
  6303. (goto-char eos)
  6304. (outline-next-heading)
  6305. (when (outline-invisible-p) (org-flag-heading nil)))
  6306. (setq org-cycle-subtree-status 'children)
  6307. (unless (org-before-first-heading-p)
  6308. (run-hook-with-args 'org-cycle-hook 'children)))
  6309. ((or children-skipped
  6310. (and (eq last-command this-command)
  6311. (eq org-cycle-subtree-status 'children)))
  6312. ;; We just showed the children, or no children are there,
  6313. ;; now show everything.
  6314. (unless (org-before-first-heading-p)
  6315. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6316. (outline-flag-region eoh eos nil)
  6317. (org-unlogged-message
  6318. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6319. (setq org-cycle-subtree-status 'subtree)
  6320. (unless (org-before-first-heading-p)
  6321. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6322. (t
  6323. ;; Default action: hide the subtree.
  6324. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6325. (outline-flag-region eoh eos t)
  6326. (org-unlogged-message "FOLDED")
  6327. (setq org-cycle-subtree-status 'folded)
  6328. (unless (org-before-first-heading-p)
  6329. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6330. ;;;###autoload
  6331. (defun org-global-cycle (&optional arg)
  6332. "Cycle the global visibility. For details see `org-cycle'.
  6333. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6334. With a numeric prefix, show all headlines up to that level."
  6335. (interactive "P")
  6336. (let ((org-cycle-include-plain-lists
  6337. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6338. (cond
  6339. ((integerp arg)
  6340. (outline-show-all)
  6341. (outline-hide-sublevels arg)
  6342. (setq org-cycle-global-status 'contents))
  6343. ((equal arg '(4))
  6344. (org-set-startup-visibility)
  6345. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6346. (t
  6347. (org-cycle '(4))))))
  6348. (defun org-set-startup-visibility ()
  6349. "Set the visibility required by startup options and properties."
  6350. (cond
  6351. ((eq org-startup-folded t)
  6352. (org-overview))
  6353. ((eq org-startup-folded 'content)
  6354. (org-content))
  6355. ((or (eq org-startup-folded 'showeverything)
  6356. (eq org-startup-folded nil))
  6357. (outline-show-all)))
  6358. (unless (eq org-startup-folded 'showeverything)
  6359. (when org-hide-block-startup (org-hide-block-all))
  6360. (org-set-visibility-according-to-property 'no-cleanup)
  6361. (org-cycle-hide-archived-subtrees 'all)
  6362. (org-cycle-hide-drawers 'all)
  6363. (org-cycle-show-empty-lines t)))
  6364. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6365. "Switch subtree visibilities according to :VISIBILITY: property."
  6366. (interactive)
  6367. (org-with-wide-buffer
  6368. (goto-char (point-min))
  6369. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6370. (if (not (org-at-property-p)) (outline-next-heading)
  6371. (let ((state (match-string 3)))
  6372. (save-excursion
  6373. (org-back-to-heading t)
  6374. (outline-hide-subtree)
  6375. (org-reveal)
  6376. (cond
  6377. ((equal state "folded")
  6378. (outline-hide-subtree))
  6379. ((equal state "children")
  6380. (org-show-hidden-entry)
  6381. (org-show-children))
  6382. ((equal state "content")
  6383. (save-excursion
  6384. (save-restriction
  6385. (org-narrow-to-subtree)
  6386. (org-content))))
  6387. ((member state '("all" "showall"))
  6388. (outline-show-subtree)))))))
  6389. (unless no-cleanup
  6390. (org-cycle-hide-archived-subtrees 'all)
  6391. (org-cycle-hide-drawers 'all)
  6392. (org-cycle-show-empty-lines 'all))))
  6393. ;; This function uses outline-regexp instead of the more fundamental
  6394. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6395. ;; buffers, where outline-regexp is needed.
  6396. (defun org-overview ()
  6397. "Switch to overview mode, showing only top-level headlines.
  6398. This shows all headlines with a level equal or greater than the level
  6399. of the first headline in the buffer. This is important, because if the
  6400. first headline is not level one, then (hide-sublevels 1) gives confusing
  6401. results."
  6402. (interactive)
  6403. (save-excursion
  6404. (let ((level
  6405. (save-excursion
  6406. (goto-char (point-min))
  6407. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6408. (goto-char (match-beginning 0))
  6409. (funcall outline-level)))))
  6410. (and level (outline-hide-sublevels level)))))
  6411. (defun org-content (&optional arg)
  6412. "Show all headlines in the buffer, like a table of contents.
  6413. With numerical argument N, show content up to level N."
  6414. (interactive "P")
  6415. (org-overview)
  6416. (save-excursion
  6417. ;; Visit all headings and show their offspring
  6418. (and (integerp arg) (org-overview))
  6419. (goto-char (point-max))
  6420. (catch 'exit
  6421. (while (and (progn (condition-case nil
  6422. (outline-previous-visible-heading 1)
  6423. (error (goto-char (point-min))))
  6424. t)
  6425. (looking-at org-outline-regexp))
  6426. (if (integerp arg)
  6427. (org-show-children (1- arg))
  6428. (outline-show-branches))
  6429. (when (bobp) (throw 'exit nil))))))
  6430. (defun org-optimize-window-after-visibility-change (state)
  6431. "Adjust the window after a change in outline visibility.
  6432. This function is the default value of the hook `org-cycle-hook'."
  6433. (when (get-buffer-window (current-buffer))
  6434. (cond
  6435. ((eq state 'content) nil)
  6436. ((eq state 'all) nil)
  6437. ((eq state 'folded) nil)
  6438. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6439. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6440. (defun org-remove-empty-overlays-at (pos)
  6441. "Remove outline overlays that do not contain non-white stuff."
  6442. (dolist (o (overlays-at pos))
  6443. (and (eq 'outline (overlay-get o 'invisible))
  6444. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6445. (overlay-end o))))
  6446. (delete-overlay o))))
  6447. (defun org-clean-visibility-after-subtree-move ()
  6448. "Fix visibility issues after moving a subtree."
  6449. ;; First, find a reasonable region to look at:
  6450. ;; Start two siblings above, end three below
  6451. (let* ((beg (save-excursion
  6452. (and (org-get-last-sibling)
  6453. (org-get-last-sibling))
  6454. (point)))
  6455. (end (save-excursion
  6456. (and (org-get-next-sibling)
  6457. (org-get-next-sibling)
  6458. (org-get-next-sibling))
  6459. (if (org-at-heading-p)
  6460. (point-at-eol)
  6461. (point))))
  6462. (level (looking-at "\\*+"))
  6463. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6464. (save-excursion
  6465. (save-restriction
  6466. (narrow-to-region beg end)
  6467. (when re
  6468. ;; Properly fold already folded siblings
  6469. (goto-char (point-min))
  6470. (while (re-search-forward re nil t)
  6471. (when (and (not (outline-invisible-p))
  6472. (save-excursion
  6473. (goto-char (point-at-eol)) (outline-invisible-p)))
  6474. (outline-hide-entry))))
  6475. (org-cycle-show-empty-lines 'overview)
  6476. (org-cycle-hide-drawers 'overview)))))
  6477. (defun org-cycle-show-empty-lines (state)
  6478. "Show empty lines above all visible headlines.
  6479. The region to be covered depends on STATE when called through
  6480. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6481. entire buffer covered. Note that an empty line is only shown if there
  6482. are at least `org-cycle-separator-lines' empty lines before the headline."
  6483. (when (/= org-cycle-separator-lines 0)
  6484. (save-excursion
  6485. (let* ((n (abs org-cycle-separator-lines))
  6486. (re (cond
  6487. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6488. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6489. (t (let ((ns (number-to-string (- n 2))))
  6490. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6491. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6492. beg end)
  6493. (cond
  6494. ((memq state '(overview contents t))
  6495. (setq beg (point-min) end (point-max)))
  6496. ((memq state '(children folded))
  6497. (setq beg (point)
  6498. end (progn (org-end-of-subtree t t)
  6499. (line-beginning-position 2)))))
  6500. (when beg
  6501. (goto-char beg)
  6502. (while (re-search-forward re end t)
  6503. (unless (get-char-property (match-end 1) 'invisible)
  6504. (let ((e (match-end 1))
  6505. (b (if (>= org-cycle-separator-lines 0)
  6506. (match-beginning 1)
  6507. (save-excursion
  6508. (goto-char (match-beginning 0))
  6509. (skip-chars-backward " \t\n")
  6510. (line-end-position)))))
  6511. (outline-flag-region b e nil))))))))
  6512. ;; Never hide empty lines at the end of the file.
  6513. (save-excursion
  6514. (goto-char (point-max))
  6515. (outline-previous-heading)
  6516. (outline-end-of-heading)
  6517. (when (and (looking-at "[ \t\n]+")
  6518. (= (match-end 0) (point-max)))
  6519. (outline-flag-region (point) (match-end 0) nil))))
  6520. (defun org-show-empty-lines-in-parent ()
  6521. "Move to the parent and re-show empty lines before visible headlines."
  6522. (save-excursion
  6523. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6524. (org-cycle-show-empty-lines context))))
  6525. (defun org-files-list ()
  6526. "Return `org-agenda-files' list, plus all open Org files.
  6527. This is useful for operations that need to scan all of a user's
  6528. open and agenda-wise Org files."
  6529. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6530. (dolist (buf (buffer-list))
  6531. (with-current-buffer buf
  6532. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6533. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6534. files))
  6535. (defsubst org-entry-beginning-position ()
  6536. "Return the beginning position of the current entry."
  6537. (save-excursion (org-back-to-heading t) (point)))
  6538. (defsubst org-entry-end-position ()
  6539. "Return the end position of the current entry."
  6540. (save-excursion (outline-next-heading) (point)))
  6541. (defun org-cycle-hide-drawers (state &optional exceptions)
  6542. "Re-hide all drawers after a visibility state change.
  6543. When non-nil, optional argument EXCEPTIONS is a list of strings
  6544. specifying which drawers should not be hidden."
  6545. (when (and (derived-mode-p 'org-mode)
  6546. (not (memq state '(overview folded contents))))
  6547. (save-excursion
  6548. (let* ((globalp (memq state '(contents all)))
  6549. (beg (if globalp (point-min) (point)))
  6550. (end (if globalp (point-max)
  6551. (if (eq state 'children)
  6552. (save-excursion (outline-next-heading) (point))
  6553. (org-end-of-subtree t)))))
  6554. (goto-char beg)
  6555. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6556. (unless (member-ignore-case (match-string 1) exceptions)
  6557. (let ((drawer (org-element-at-point)))
  6558. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6559. (org-flag-drawer t drawer)
  6560. ;; Make sure to skip drawer entirely or we might flag
  6561. ;; it another time when matching its ending line with
  6562. ;; `org-drawer-regexp'.
  6563. (goto-char (org-element-property :end drawer))))))))))
  6564. (defun org-flag-drawer (flag &optional element)
  6565. "When FLAG is non-nil, hide the drawer we are at.
  6566. Otherwise make it visible. When optional argument ELEMENT is
  6567. a parsed drawer, as returned by `org-element-at-point', hide or
  6568. show that drawer instead."
  6569. (let ((drawer (or element
  6570. (and (save-excursion
  6571. (beginning-of-line)
  6572. (looking-at-p org-drawer-regexp))
  6573. (org-element-at-point)))))
  6574. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6575. (let ((post (org-element-property :post-affiliated drawer)))
  6576. (save-excursion
  6577. (outline-flag-region
  6578. (progn (goto-char post) (line-end-position))
  6579. (progn (goto-char (org-element-property :end drawer))
  6580. (skip-chars-backward " \r\t\n")
  6581. (line-end-position))
  6582. flag))
  6583. ;; When the drawer is hidden away, make sure point lies in
  6584. ;; a visible part of the buffer.
  6585. (when (and flag (> (line-beginning-position) post))
  6586. (goto-char post))))))
  6587. (defun org-subtree-end-visible-p ()
  6588. "Is the end of the current subtree visible?"
  6589. (pos-visible-in-window-p
  6590. (save-excursion (org-end-of-subtree t) (point))))
  6591. (defun org-first-headline-recenter ()
  6592. "Move cursor to the first headline and recenter the headline."
  6593. (let ((window (get-buffer-window)))
  6594. (when window
  6595. (goto-char (point-min))
  6596. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6597. (set-window-start window (line-beginning-position))))))
  6598. ;;; Saving and restoring visibility
  6599. (defun org-outline-overlay-data (&optional use-markers)
  6600. "Return a list of the locations of all outline overlays.
  6601. These are overlays with the `invisible' property value `outline'.
  6602. The return value is a list of cons cells, with start and stop
  6603. positions for each overlay.
  6604. If USE-MARKERS is set, return the positions as markers."
  6605. (let (beg end)
  6606. (org-with-wide-buffer
  6607. (delq nil
  6608. (mapcar (lambda (o)
  6609. (when (eq (overlay-get o 'invisible) 'outline)
  6610. (setq beg (overlay-start o)
  6611. end (overlay-end o))
  6612. (and beg end (> end beg)
  6613. (if use-markers
  6614. (cons (copy-marker beg)
  6615. (copy-marker end t))
  6616. (cons beg end)))))
  6617. (overlays-in (point-min) (point-max)))))))
  6618. (defun org-set-outline-overlay-data (data)
  6619. "Create visibility overlays for all positions in DATA.
  6620. DATA should have been made by `org-outline-overlay-data'."
  6621. (org-with-wide-buffer
  6622. (outline-show-all)
  6623. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6624. ;;; Folding of blocks
  6625. (defvar-local org-hide-block-overlays nil
  6626. "Overlays hiding blocks.")
  6627. (defun org-block-map (function &optional start end)
  6628. "Call FUNCTION at the head of all source blocks in the current buffer.
  6629. Optional arguments START and END can be used to limit the range."
  6630. (let ((start (or start (point-min)))
  6631. (end (or end (point-max))))
  6632. (save-excursion
  6633. (goto-char start)
  6634. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6635. (save-excursion
  6636. (save-match-data
  6637. (goto-char (match-beginning 0))
  6638. (funcall function)))))))
  6639. (defun org-hide-block-toggle-all ()
  6640. "Toggle the visibility of all blocks in the current buffer."
  6641. (org-block-map 'org-hide-block-toggle))
  6642. (defun org-hide-block-all ()
  6643. "Fold all blocks in the current buffer."
  6644. (interactive)
  6645. (org-show-block-all)
  6646. (org-block-map 'org-hide-block-toggle-maybe))
  6647. (defun org-show-block-all ()
  6648. "Unfold all blocks in the current buffer."
  6649. (interactive)
  6650. (mapc #'delete-overlay org-hide-block-overlays)
  6651. (setq org-hide-block-overlays nil))
  6652. (defun org-hide-block-toggle-maybe ()
  6653. "Toggle visibility of block at point.
  6654. Unlike to `org-hide-block-toggle', this function does not throw
  6655. an error. Return a non-nil value when toggling is successful."
  6656. (interactive)
  6657. (ignore-errors (org-hide-block-toggle)))
  6658. (defun org-hide-block-toggle (&optional force)
  6659. "Toggle the visibility of the current block.
  6660. When optional argument FORCE is `off', make block visible. If it
  6661. is non-nil, hide it unconditionally. Throw an error when not at
  6662. a block. Return a non-nil value when toggling is successful."
  6663. (interactive)
  6664. (let ((element (org-element-at-point)))
  6665. (unless (memq (org-element-type element)
  6666. '(center-block comment-block dynamic-block example-block
  6667. export-block quote-block special-block
  6668. src-block verse-block))
  6669. (user-error "Not at a block"))
  6670. (let* ((start (save-excursion
  6671. (goto-char (org-element-property :post-affiliated element))
  6672. (line-end-position)))
  6673. (end (save-excursion
  6674. (goto-char (org-element-property :end element))
  6675. (skip-chars-backward " \r\t\n")
  6676. (line-end-position)))
  6677. (overlays (overlays-at start)))
  6678. (cond
  6679. ;; Do nothing when not before or at the block opening line or
  6680. ;; at the block closing line.
  6681. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6682. ((and (not (eq force 'off))
  6683. (not (memq t (mapcar
  6684. (lambda (o)
  6685. (eq (overlay-get o 'invisible) 'org-hide-block))
  6686. overlays))))
  6687. (let ((ov (make-overlay start end)))
  6688. (overlay-put ov 'invisible 'org-hide-block)
  6689. ;; Make the block accessible to `isearch'.
  6690. (overlay-put
  6691. ov 'isearch-open-invisible
  6692. (lambda (ov)
  6693. (when (memq ov org-hide-block-overlays)
  6694. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6695. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6696. (delete-overlay ov))))
  6697. (push ov org-hide-block-overlays)
  6698. ;; When the block is hidden away, make sure point is left in
  6699. ;; a visible part of the buffer.
  6700. (when (> (line-beginning-position) start)
  6701. (goto-char start)
  6702. (beginning-of-line))
  6703. ;; Signal successful toggling.
  6704. t))
  6705. ((or (not force) (eq force 'off))
  6706. (dolist (ov overlays t)
  6707. (when (memq ov org-hide-block-overlays)
  6708. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6709. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6710. (delete-overlay ov))))))))
  6711. ;; Remove overlays when changing major mode
  6712. (add-hook 'org-mode-hook
  6713. (lambda () (add-hook 'change-major-mode-hook
  6714. 'org-show-block-all 'append 'local)))
  6715. ;;; Org-goto
  6716. (defvar org-goto-window-configuration nil)
  6717. (defvar org-goto-marker nil)
  6718. (defvar org-goto-map)
  6719. (defun org-goto-map ()
  6720. "Set the keymap `org-goto'."
  6721. (setq org-goto-map
  6722. (let ((map (make-sparse-keymap)))
  6723. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6724. mouse-drag-region universal-argument org-occur)))
  6725. (dolist (cmd cmds)
  6726. (substitute-key-definition cmd cmd map global-map)))
  6727. (suppress-keymap map)
  6728. (org-defkey map "\C-m" 'org-goto-ret)
  6729. (org-defkey map [(return)] 'org-goto-ret)
  6730. (org-defkey map [(left)] 'org-goto-left)
  6731. (org-defkey map [(right)] 'org-goto-right)
  6732. (org-defkey map [(control ?g)] 'org-goto-quit)
  6733. (org-defkey map "\C-i" 'org-cycle)
  6734. (org-defkey map [(tab)] 'org-cycle)
  6735. (org-defkey map [(down)] 'outline-next-visible-heading)
  6736. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6737. (if org-goto-auto-isearch
  6738. (if (fboundp 'define-key-after)
  6739. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6740. nil)
  6741. (org-defkey map "q" 'org-goto-quit)
  6742. (org-defkey map "n" 'outline-next-visible-heading)
  6743. (org-defkey map "p" 'outline-previous-visible-heading)
  6744. (org-defkey map "f" 'outline-forward-same-level)
  6745. (org-defkey map "b" 'outline-backward-same-level)
  6746. (org-defkey map "u" 'outline-up-heading))
  6747. (org-defkey map "/" 'org-occur)
  6748. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6749. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6750. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6751. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6752. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6753. map)))
  6754. (defconst org-goto-help
  6755. "Browse buffer copy, to find location or copy text.%s
  6756. RET=jump to location C-g=quit and return to previous location
  6757. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6758. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6759. (defun org-goto (&optional alternative-interface)
  6760. "Look up a different location in the current file, keeping current visibility.
  6761. When you want look-up or go to a different location in a
  6762. document, the fastest way is often to fold the entire buffer and
  6763. then dive into the tree. This method has the disadvantage, that
  6764. the previous location will be folded, which may not be what you
  6765. want.
  6766. This command works around this by showing a copy of the current
  6767. buffer in an indirect buffer, in overview mode. You can dive
  6768. into the tree in that copy, use org-occur and incremental search
  6769. to find a location. When pressing RET or `Q', the command
  6770. returns to the original buffer in which the visibility is still
  6771. unchanged. After RET it will also jump to the location selected
  6772. in the indirect buffer and expose the headline hierarchy above.
  6773. With a prefix argument, use the alternative interface: e.g., if
  6774. `org-goto-interface' is `outline' use `outline-path-completion'."
  6775. (interactive "P")
  6776. (org-goto-map)
  6777. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6778. (org-refile-use-outline-path t)
  6779. (org-refile-target-verify-function nil)
  6780. (interface
  6781. (if (not alternative-interface)
  6782. org-goto-interface
  6783. (if (eq org-goto-interface 'outline)
  6784. 'outline-path-completion
  6785. 'outline)))
  6786. (org-goto-start-pos (point))
  6787. (selected-point
  6788. (if (eq interface 'outline)
  6789. (car (org-get-location (current-buffer) org-goto-help))
  6790. (let ((pa (org-refile-get-location "Goto")))
  6791. (org-refile-check-position pa)
  6792. (nth 3 pa)))))
  6793. (if selected-point
  6794. (progn
  6795. (org-mark-ring-push org-goto-start-pos)
  6796. (goto-char selected-point)
  6797. (when (or (outline-invisible-p) (org-invisible-p2))
  6798. (org-show-context 'org-goto)))
  6799. (message "Quit"))))
  6800. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6801. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6802. (defvar org-goto-local-auto-isearch-map) ; defined below
  6803. (defun org-get-location (_buf help)
  6804. "Let the user select a location in current buffer.
  6805. This function uses a recursive edit. It returns the selected position
  6806. or nil."
  6807. (org-no-popups
  6808. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6809. (isearch-hide-immediately nil)
  6810. (isearch-search-fun-function
  6811. (lambda () 'org-goto-local-search-headings))
  6812. (org-goto-selected-point org-goto-exit-command))
  6813. (save-excursion
  6814. (save-window-excursion
  6815. (delete-other-windows)
  6816. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6817. (pop-to-buffer-same-window
  6818. (condition-case nil
  6819. (make-indirect-buffer (current-buffer) "*org-goto*")
  6820. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6821. (with-output-to-temp-buffer "*Org Help*"
  6822. (princ (format help (if org-goto-auto-isearch
  6823. " Just type for auto-isearch."
  6824. " n/p/f/b/u to navigate, q to quit."))))
  6825. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6826. (setq buffer-read-only nil)
  6827. (let ((org-startup-truncated t)
  6828. (org-startup-folded nil)
  6829. (org-startup-align-all-tables nil))
  6830. (org-mode)
  6831. (org-overview))
  6832. (setq buffer-read-only t)
  6833. (if (and (boundp 'org-goto-start-pos)
  6834. (integer-or-marker-p org-goto-start-pos))
  6835. (progn (goto-char org-goto-start-pos)
  6836. (when (outline-invisible-p)
  6837. (org-show-set-visibility 'lineage)))
  6838. (goto-char (point-min)))
  6839. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6840. (message "Select location and press RET")
  6841. (use-local-map org-goto-map)
  6842. (recursive-edit)))
  6843. (kill-buffer "*org-goto*")
  6844. (cons org-goto-selected-point org-goto-exit-command))))
  6845. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6846. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6847. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6848. (if (fboundp 'isearch-other-control-char)
  6849. (progn
  6850. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6851. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6852. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6853. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6854. (define-key org-goto-local-auto-isearch-map [return] nil))
  6855. (defun org-goto-local-search-headings (string bound noerror)
  6856. "Search and make sure that any matches are in headlines."
  6857. (catch 'return
  6858. (while (if isearch-forward
  6859. (search-forward string bound noerror)
  6860. (search-backward string bound noerror))
  6861. (when (save-match-data
  6862. (and (save-excursion
  6863. (beginning-of-line)
  6864. (looking-at org-complex-heading-regexp))
  6865. (or (not (match-beginning 5))
  6866. (< (point) (match-beginning 5)))))
  6867. (throw 'return (point))))))
  6868. (defun org-goto-local-auto-isearch ()
  6869. "Start isearch."
  6870. (interactive)
  6871. (goto-char (point-min))
  6872. (let ((keys (this-command-keys)))
  6873. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6874. (isearch-mode t)
  6875. (isearch-process-search-char (string-to-char keys)))))
  6876. (defun org-goto-ret (&optional _arg)
  6877. "Finish `org-goto' by going to the new location."
  6878. (interactive "P")
  6879. (setq org-goto-selected-point (point))
  6880. (setq org-goto-exit-command 'return)
  6881. (throw 'exit nil))
  6882. (defun org-goto-left ()
  6883. "Finish `org-goto' by going to the new location."
  6884. (interactive)
  6885. (if (org-at-heading-p)
  6886. (progn
  6887. (beginning-of-line 1)
  6888. (setq org-goto-selected-point (point)
  6889. org-goto-exit-command 'left)
  6890. (throw 'exit nil))
  6891. (user-error "Not on a heading")))
  6892. (defun org-goto-right ()
  6893. "Finish `org-goto' by going to the new location."
  6894. (interactive)
  6895. (if (org-at-heading-p)
  6896. (progn
  6897. (setq org-goto-selected-point (point)
  6898. org-goto-exit-command 'right)
  6899. (throw 'exit nil))
  6900. (user-error "Not on a heading")))
  6901. (defun org-goto-quit ()
  6902. "Finish `org-goto' without cursor motion."
  6903. (interactive)
  6904. (setq org-goto-selected-point nil)
  6905. (setq org-goto-exit-command 'quit)
  6906. (throw 'exit nil))
  6907. ;;; Indirect buffer display of subtrees
  6908. (defvar org-indirect-dedicated-frame nil
  6909. "This is the frame being used for indirect tree display.")
  6910. (defvar org-last-indirect-buffer nil)
  6911. (defun org-tree-to-indirect-buffer (&optional arg)
  6912. "Create indirect buffer and narrow it to current subtree.
  6913. With a numerical prefix ARG, go up to this level and then take that tree.
  6914. If ARG is negative, go up that many levels.
  6915. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6916. indirect buffer previously made with this command, to avoid proliferation of
  6917. indirect buffers. However, when you call the command with a \
  6918. `\\[universal-argument]' prefix, or
  6919. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6920. so that you can work with several indirect buffers at the same time. If
  6921. `org-indirect-buffer-display' is `dedicated-frame', the \
  6922. `\\[universal-argument]' prefix also
  6923. requests that a new frame be made for the new buffer, so that the dedicated
  6924. frame is not changed."
  6925. (interactive "P")
  6926. (let ((cbuf (current-buffer))
  6927. (cwin (selected-window))
  6928. (pos (point))
  6929. beg end level heading ibuf)
  6930. (save-excursion
  6931. (org-back-to-heading t)
  6932. (when (numberp arg)
  6933. (setq level (org-outline-level))
  6934. (when (< arg 0) (setq arg (+ level arg)))
  6935. (while (> (setq level (org-outline-level)) arg)
  6936. (org-up-heading-safe)))
  6937. (setq beg (point)
  6938. heading (org-get-heading 'no-tags))
  6939. (org-end-of-subtree t t)
  6940. (when (org-at-heading-p) (backward-char 1))
  6941. (setq end (point)))
  6942. (when (and (buffer-live-p org-last-indirect-buffer)
  6943. (not (eq org-indirect-buffer-display 'new-frame))
  6944. (not arg))
  6945. (kill-buffer org-last-indirect-buffer))
  6946. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6947. org-last-indirect-buffer ibuf)
  6948. (cond
  6949. ((or (eq org-indirect-buffer-display 'new-frame)
  6950. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6951. (select-frame (make-frame))
  6952. (delete-other-windows)
  6953. (pop-to-buffer-same-window ibuf)
  6954. (org-set-frame-title heading))
  6955. ((eq org-indirect-buffer-display 'dedicated-frame)
  6956. (raise-frame
  6957. (select-frame (or (and org-indirect-dedicated-frame
  6958. (frame-live-p org-indirect-dedicated-frame)
  6959. org-indirect-dedicated-frame)
  6960. (setq org-indirect-dedicated-frame (make-frame)))))
  6961. (delete-other-windows)
  6962. (pop-to-buffer-same-window ibuf)
  6963. (org-set-frame-title (concat "Indirect: " heading)))
  6964. ((eq org-indirect-buffer-display 'current-window)
  6965. (pop-to-buffer-same-window ibuf))
  6966. ((eq org-indirect-buffer-display 'other-window)
  6967. (pop-to-buffer ibuf))
  6968. (t (error "Invalid value")))
  6969. (narrow-to-region beg end)
  6970. (outline-show-all)
  6971. (goto-char pos)
  6972. (run-hook-with-args 'org-cycle-hook 'all)
  6973. (and (window-live-p cwin) (select-window cwin))))
  6974. (defun org-get-indirect-buffer (&optional buffer heading)
  6975. (setq buffer (or buffer (current-buffer)))
  6976. (let ((n 1) (base (buffer-name buffer)) bname)
  6977. (while (buffer-live-p
  6978. (get-buffer
  6979. (setq bname
  6980. (concat base "-"
  6981. (if heading (concat heading "-" (number-to-string n))
  6982. (number-to-string n))))))
  6983. (setq n (1+ n)))
  6984. (condition-case nil
  6985. (make-indirect-buffer buffer bname 'clone)
  6986. (error (make-indirect-buffer buffer bname)))))
  6987. (defun org-set-frame-title (title)
  6988. "Set the title of the current frame to the string TITLE."
  6989. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6990. ;;;; Structure editing
  6991. ;;; Inserting headlines
  6992. (defun org--line-empty-p (n)
  6993. "Is the Nth next line empty?
  6994. Counts the current line as N = 1 and the previous line as N = 0;
  6995. see `beginning-of-line'."
  6996. (save-excursion
  6997. (and (not (bobp))
  6998. (or (beginning-of-line n) t)
  6999. (save-match-data
  7000. (looking-at "[ \t]*$")))))
  7001. (defun org-previous-line-empty-p ()
  7002. "Is the previous line a blank line?
  7003. When NEXT is non-nil, check the next line instead."
  7004. (org--line-empty-p 0))
  7005. (defun org-next-line-empty-p ()
  7006. "Is the previous line a blank line?
  7007. When NEXT is non-nil, check the next line instead."
  7008. (org--line-empty-p 2))
  7009. (defun org-insert-heading (&optional arg invisible-ok top)
  7010. "Insert a new heading or an item with the same depth at point.
  7011. If point is at the beginning of a heading or a list item, insert
  7012. a new heading or a new item above the current one. When at the
  7013. beginning of a regular line of text, turn it into a heading.
  7014. If point is in the middle of a line, split it and create a new
  7015. headline/item with the text in the current line after point (see
  7016. `org-M-RET-may-split-line' on how to modify this behavior). As
  7017. a special case, on a headline, splitting can only happen on the
  7018. title itself. E.g., this excludes breaking stars or tags.
  7019. With a `\\[universal-argument]' prefix, set \
  7020. `org-insert-heading-respect-content' to
  7021. a non-nil value for the duration of the command. This forces the
  7022. insertion of a heading after the current subtree, independently
  7023. on the location of point.
  7024. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  7025. insert the heading at the end of the tree
  7026. above the current heading. For example, if point is within a
  7027. 2nd-level heading, then it will insert a 2nd-level heading at
  7028. the end of the 1st-level parent subtree.
  7029. When INVISIBLE-OK is set, stop at invisible headlines when going
  7030. back. This is important for non-interactive uses of the
  7031. command.
  7032. When optional argument TOP is non-nil, insert a level 1 heading,
  7033. unconditionally."
  7034. (interactive "P")
  7035. (let ((itemp (and (not top) (org-in-item-p)))
  7036. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7037. (respect-content (or org-insert-heading-respect-content
  7038. (equal arg '(4))))
  7039. (initial-content ""))
  7040. (cond
  7041. ((or (= (buffer-size) 0)
  7042. (and (not (save-excursion
  7043. (and (ignore-errors (org-back-to-heading invisible-ok))
  7044. (org-at-heading-p))))
  7045. (or arg (not itemp))))
  7046. ;; At beginning of buffer or so high up that only a heading
  7047. ;; makes sense.
  7048. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7049. ((not respect-content)
  7050. (unless may-split (end-of-line))
  7051. (insert "\n* "))
  7052. ((re-search-forward org-outline-regexp-bol nil t)
  7053. (beginning-of-line)
  7054. (insert "* \n")
  7055. (backward-char))
  7056. (t (goto-char (point-max))
  7057. (insert "\n* ")))
  7058. (run-hooks 'org-insert-heading-hook))
  7059. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7060. (t
  7061. ;; Maybe move at the end of the subtree
  7062. (when (equal arg '(16))
  7063. (org-up-heading-safe)
  7064. (org-end-of-subtree t))
  7065. ;; Insert a heading
  7066. (save-restriction
  7067. (widen)
  7068. (let* ((level nil)
  7069. (on-heading (org-at-heading-p))
  7070. (empty-line-p (if on-heading
  7071. (org-previous-line-empty-p)
  7072. ;; We will decide later
  7073. nil))
  7074. ;; Get a level string to fall back on.
  7075. (fix-level
  7076. (if (org-before-first-heading-p) "*"
  7077. (save-excursion
  7078. (org-back-to-heading t)
  7079. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7080. (looking-at org-outline-regexp)
  7081. (make-string (1- (length (match-string 0))) ?*))))
  7082. (stars
  7083. (save-excursion
  7084. (condition-case nil
  7085. (if top "* "
  7086. (org-back-to-heading invisible-ok)
  7087. (when (and (not on-heading)
  7088. (featurep 'org-inlinetask)
  7089. (integerp org-inlinetask-min-level)
  7090. (>= (length (match-string 0))
  7091. org-inlinetask-min-level))
  7092. ;; Find a heading level before the inline
  7093. ;; task.
  7094. (while (and (setq level (org-up-heading-safe))
  7095. (>= level org-inlinetask-min-level)))
  7096. (if (org-at-heading-p)
  7097. (org-back-to-heading invisible-ok)
  7098. (error "This should not happen")))
  7099. (unless (and (save-excursion
  7100. (save-match-data
  7101. (org-backward-heading-same-level
  7102. 1 invisible-ok))
  7103. (= (point) (match-beginning 0)))
  7104. (not (org-next-line-empty-p)))
  7105. (setq empty-line-p (or empty-line-p
  7106. (org-previous-line-empty-p))))
  7107. (match-string 0))
  7108. (error (or fix-level "* ")))))
  7109. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7110. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7111. ;; If we insert after content, move there and clean up
  7112. ;; whitespace.
  7113. (when respect-content
  7114. (if (not (org-before-first-heading-p))
  7115. (org-end-of-subtree nil t)
  7116. (re-search-forward org-outline-regexp-bol)
  7117. (beginning-of-line 0))
  7118. (skip-chars-backward " \r\t\n")
  7119. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7120. (looking-at "[ \t]+") (replace-match ""))
  7121. (unless (eobp) (forward-char 1))
  7122. (when (looking-at "^\\*")
  7123. (unless (bobp) (backward-char 1))
  7124. (insert "\n")))
  7125. ;; If we are splitting, grab the text that should be moved
  7126. ;; to the new headline.
  7127. (when may-split
  7128. (if (org-at-heading-p)
  7129. ;; This is a heading: split intelligently (keeping
  7130. ;; tags).
  7131. (let ((pos (point)))
  7132. (beginning-of-line)
  7133. (let ((case-fold-search nil))
  7134. (unless (looking-at org-complex-heading-regexp)
  7135. (error "This should not happen")))
  7136. (when (and (match-beginning 4)
  7137. (> pos (match-beginning 4))
  7138. (< pos (match-end 4)))
  7139. (setq initial-content (buffer-substring pos (match-end 4)))
  7140. (goto-char pos)
  7141. (delete-region (point) (match-end 4))
  7142. (if (looking-at "[ \t]*$")
  7143. (replace-match "")
  7144. (insert (make-string (length initial-content) ?\s)))
  7145. (setq initial-content (org-trim initial-content)))
  7146. (goto-char pos))
  7147. ;; A normal line.
  7148. (setq initial-content
  7149. (org-trim
  7150. (delete-and-extract-region (point) (line-end-position))))))
  7151. ;; If we are at the beginning of the line, insert before it.
  7152. ;; Otherwise, after it.
  7153. (cond
  7154. ((and (bolp) (looking-at "[ \t]*$")))
  7155. ((bolp) (save-excursion (insert "\n")))
  7156. (t (end-of-line)
  7157. (insert "\n")))
  7158. ;; Insert the new heading
  7159. (insert stars)
  7160. (just-one-space)
  7161. (insert initial-content)
  7162. (unless (and blank (org-previous-line-empty-p))
  7163. (org-N-empty-lines-before-current (if blank 1 0)))
  7164. ;; Adjust visibility, which may be messed up if we removed
  7165. ;; blank lines while previous entry was hidden.
  7166. (let ((bol (line-beginning-position)))
  7167. (dolist (o (overlays-at (1- bol)))
  7168. (when (and (eq (overlay-get o 'invisible) 'outline)
  7169. (eq (overlay-end o) bol))
  7170. (move-overlay o (overlay-start o) (1- bol)))))
  7171. (run-hooks 'org-insert-heading-hook)))))))
  7172. (defun org-N-empty-lines-before-current (N)
  7173. "Make the number of empty lines before current exactly N.
  7174. So this will delete or add empty lines."
  7175. (save-excursion
  7176. (beginning-of-line)
  7177. (let ((p (point)))
  7178. (skip-chars-backward " \r\t\n")
  7179. (unless (bolp) (forward-line))
  7180. (delete-region (point) p))
  7181. (when (> N 0) (insert (make-string N ?\n)))))
  7182. (defun org-get-heading (&optional no-tags no-todo)
  7183. "Return the heading of the current entry, without the stars.
  7184. When NO-TAGS is non-nil, don't include tags.
  7185. When NO-TODO is non-nil, don't include TODO keywords."
  7186. (save-excursion
  7187. (org-back-to-heading t)
  7188. (let ((case-fold-search nil))
  7189. (cond
  7190. ((and no-tags no-todo)
  7191. (looking-at org-complex-heading-regexp)
  7192. ;; Return value has to be a string, but match group 4 is
  7193. ;; optional.
  7194. (or (match-string 4) ""))
  7195. (no-tags
  7196. (looking-at (concat org-outline-regexp
  7197. "\\(.*?\\)"
  7198. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7199. (match-string 1))
  7200. (no-todo
  7201. (looking-at org-todo-line-regexp)
  7202. (match-string 3))
  7203. (t (looking-at org-heading-regexp)
  7204. (match-string 2))))))
  7205. (defvar orgstruct-mode) ; defined below
  7206. (defun org-heading-components ()
  7207. "Return the components of the current heading.
  7208. This is a list with the following elements:
  7209. - the level as an integer
  7210. - the reduced level, different if `org-odd-levels-only' is set.
  7211. - the TODO keyword, or nil
  7212. - the priority character, like ?A, or nil if no priority is given
  7213. - the headline text itself, or the tags string if no headline text
  7214. - the tags string, or nil."
  7215. (save-excursion
  7216. (org-back-to-heading t)
  7217. (when (let (case-fold-search)
  7218. (looking-at
  7219. (if orgstruct-mode
  7220. org-heading-regexp
  7221. org-complex-heading-regexp)))
  7222. (if orgstruct-mode
  7223. (list (length (match-string 1))
  7224. (org-reduced-level (length (match-string 1)))
  7225. nil
  7226. nil
  7227. (match-string 2)
  7228. nil)
  7229. (list (length (match-string 1))
  7230. (org-reduced-level (length (match-string 1)))
  7231. (match-string-no-properties 2)
  7232. (and (match-end 3) (aref (match-string 3) 2))
  7233. (match-string-no-properties 4)
  7234. (match-string-no-properties 5))))))
  7235. (defun org-get-entry ()
  7236. "Get the entry text, after heading, entire subtree."
  7237. (save-excursion
  7238. (org-back-to-heading t)
  7239. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7240. (defun org-edit-headline (&optional heading)
  7241. "Edit the current headline.
  7242. Set it to HEADING when provided."
  7243. (interactive)
  7244. (org-with-wide-buffer
  7245. (org-back-to-heading t)
  7246. (let ((case-fold-search nil))
  7247. (when (looking-at org-complex-heading-regexp)
  7248. (let* ((old (match-string-no-properties 4))
  7249. (new (save-match-data
  7250. (org-trim (or heading (read-string "Edit: " old))))))
  7251. (unless (equal old new)
  7252. (if old (replace-match new t t nil 4)
  7253. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7254. (insert " " new))
  7255. (org-set-tags nil t)
  7256. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7257. (defun org-insert-heading-after-current ()
  7258. "Insert a new heading with same level as current, after current subtree."
  7259. (interactive)
  7260. (org-back-to-heading)
  7261. (org-insert-heading)
  7262. (org-move-subtree-down)
  7263. (end-of-line 1))
  7264. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7265. "Insert heading with `org-insert-heading-respect-content' set to t."
  7266. (interactive)
  7267. (org-insert-heading '(4) invisible-ok))
  7268. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7269. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7270. (interactive)
  7271. (org-insert-todo-heading force-state '(4)))
  7272. (defun org-insert-todo-heading (arg &optional force-heading)
  7273. "Insert a new heading with the same level and TODO state as current heading.
  7274. If the heading has no TODO state, or if the state is DONE, use
  7275. the first state (TODO by default). Also with one prefix arg,
  7276. force first state. With two prefix args, force inserting at the
  7277. end of the parent subtree.
  7278. When called at a plain list item, insert a new item with an
  7279. unchecked check box."
  7280. (interactive "P")
  7281. (when (or force-heading (not (org-insert-item 'checkbox)))
  7282. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7283. force-heading))
  7284. (save-excursion
  7285. (org-back-to-heading)
  7286. (outline-previous-heading)
  7287. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7288. (let* ((new-mark-x
  7289. (if (or (equal arg '(4))
  7290. (not (match-beginning 2))
  7291. (member (match-string 2) org-done-keywords))
  7292. (car org-todo-keywords-1)
  7293. (match-string 2)))
  7294. (new-mark
  7295. (or
  7296. (run-hook-with-args-until-success
  7297. 'org-todo-get-default-hook new-mark-x nil)
  7298. new-mark-x)))
  7299. (beginning-of-line 1)
  7300. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7301. (if org-treat-insert-todo-heading-as-state-change
  7302. (org-todo new-mark)
  7303. (insert new-mark " "))))
  7304. (when org-provide-todo-statistics
  7305. (org-update-parent-todo-statistics))))
  7306. (defun org-insert-subheading (arg)
  7307. "Insert a new subheading and demote it.
  7308. Works for outline headings and for plain lists alike."
  7309. (interactive "P")
  7310. (org-insert-heading arg)
  7311. (cond
  7312. ((org-at-heading-p) (org-do-demote))
  7313. ((org-at-item-p) (org-indent-item))))
  7314. (defun org-insert-todo-subheading (arg)
  7315. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7316. Works for outline headings and for plain lists alike."
  7317. (interactive "P")
  7318. (org-insert-todo-heading arg)
  7319. (cond
  7320. ((org-at-heading-p) (org-do-demote))
  7321. ((org-at-item-p) (org-indent-item))))
  7322. ;;; Promotion and Demotion
  7323. (defvar org-after-demote-entry-hook nil
  7324. "Hook run after an entry has been demoted.
  7325. The cursor will be at the beginning of the entry.
  7326. When a subtree is being demoted, the hook will be called for each node.")
  7327. (defvar org-after-promote-entry-hook nil
  7328. "Hook run after an entry has been promoted.
  7329. The cursor will be at the beginning of the entry.
  7330. When a subtree is being promoted, the hook will be called for each node.")
  7331. (defun org-promote-subtree ()
  7332. "Promote the entire subtree.
  7333. See also `org-promote'."
  7334. (interactive)
  7335. (save-excursion
  7336. (org-with-limited-levels (org-map-tree 'org-promote)))
  7337. (org-fix-position-after-promote))
  7338. (defun org-demote-subtree ()
  7339. "Demote the entire subtree.
  7340. See `org-demote' and `org-promote'."
  7341. (interactive)
  7342. (save-excursion
  7343. (org-with-limited-levels (org-map-tree 'org-demote)))
  7344. (org-fix-position-after-promote))
  7345. (defun org-do-promote ()
  7346. "Promote the current heading higher up the tree.
  7347. If the region is active in `transient-mark-mode', promote all
  7348. headings in the region."
  7349. (interactive)
  7350. (save-excursion
  7351. (if (org-region-active-p)
  7352. (org-map-region 'org-promote (region-beginning) (region-end))
  7353. (org-promote)))
  7354. (org-fix-position-after-promote))
  7355. (defun org-do-demote ()
  7356. "Demote the current heading lower down the tree.
  7357. If the region is active in `transient-mark-mode', demote all
  7358. headings in the region."
  7359. (interactive)
  7360. (save-excursion
  7361. (if (org-region-active-p)
  7362. (org-map-region 'org-demote (region-beginning) (region-end))
  7363. (org-demote)))
  7364. (org-fix-position-after-promote))
  7365. (defun org-fix-position-after-promote ()
  7366. "Fix cursor position and indentation after demoting/promoting."
  7367. (let ((pos (point)))
  7368. (when (save-excursion
  7369. (beginning-of-line)
  7370. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7371. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7372. (cond ((eobp) (insert " "))
  7373. ((eolp) (insert " "))
  7374. ((equal (char-after) ?\s) (forward-char 1))))))
  7375. (defun org-current-level ()
  7376. "Return the level of the current entry, or nil if before the first headline.
  7377. The level is the number of stars at the beginning of the
  7378. headline. Use `org-reduced-level' to remove the effect of
  7379. `org-odd-levels'. Unlike to `org-outline-level', this function
  7380. ignores inlinetasks."
  7381. (let ((level (org-with-limited-levels (org-outline-level))))
  7382. (and (> level 0) level)))
  7383. (defun org-get-previous-line-level ()
  7384. "Return the outline depth of the last headline before the current line.
  7385. Returns 0 for the first headline in the buffer, and nil if before the
  7386. first headline."
  7387. (and (org-current-level)
  7388. (or (and (/= (line-beginning-position) (point-min))
  7389. (save-excursion (beginning-of-line 0) (org-current-level)))
  7390. 0)))
  7391. (defun org-reduced-level (l)
  7392. "Compute the effective level of a heading.
  7393. This takes into account the setting of `org-odd-levels-only'."
  7394. (cond
  7395. ((zerop l) 0)
  7396. (org-odd-levels-only (1+ (floor (/ l 2))))
  7397. (t l)))
  7398. (defun org-level-increment ()
  7399. "Return the number of stars that will be added or removed at a
  7400. time to headlines when structure editing, based on the value of
  7401. `org-odd-levels-only'."
  7402. (if org-odd-levels-only 2 1))
  7403. (defun org-get-valid-level (level &optional change)
  7404. "Rectify a level change under the influence of `org-odd-levels-only'
  7405. LEVEL is a current level, CHANGE is by how much the level should be
  7406. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7407. even level numbers will become the next higher odd number."
  7408. (if org-odd-levels-only
  7409. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7410. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7411. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7412. (max 1 (+ level (or change 0)))))
  7413. (defun org-promote ()
  7414. "Promote the current heading higher up the tree."
  7415. (org-with-wide-buffer
  7416. (org-back-to-heading t)
  7417. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7418. after-change-functions))
  7419. (level (save-match-data (funcall outline-level)))
  7420. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7421. (diff (abs (- level (length up-head) -1))))
  7422. (cond
  7423. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7424. (replace-match "# " nil t))
  7425. ((= level 1)
  7426. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7427. (t (replace-match up-head nil t)))
  7428. (unless (= level 1)
  7429. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7430. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7431. (run-hooks 'org-after-promote-entry-hook))))
  7432. (defun org-demote ()
  7433. "Demote the current heading lower down the tree."
  7434. (org-with-wide-buffer
  7435. (org-back-to-heading t)
  7436. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7437. after-change-functions))
  7438. (level (save-match-data (funcall outline-level)))
  7439. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7440. (diff (abs (- level (length down-head) -1))))
  7441. (replace-match down-head nil t)
  7442. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7443. (when org-adapt-indentation (org-fixup-indentation diff))
  7444. (run-hooks 'org-after-demote-entry-hook))))
  7445. (defun org-cycle-level ()
  7446. "Cycle the level of an empty headline through possible states.
  7447. This goes first to child, then to parent, level, then up the hierarchy.
  7448. After top level, it switches back to sibling level."
  7449. (interactive)
  7450. (let ((org-adapt-indentation nil))
  7451. (when (org-point-at-end-of-empty-headline)
  7452. (setq this-command 'org-cycle-level) ; Only needed for caching
  7453. (let ((cur-level (org-current-level))
  7454. (prev-level (org-get-previous-line-level)))
  7455. (cond
  7456. ;; If first headline in file, promote to top-level.
  7457. ((= prev-level 0)
  7458. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7459. do (org-do-promote)))
  7460. ;; If same level as prev, demote one.
  7461. ((= prev-level cur-level)
  7462. (org-do-demote))
  7463. ;; If parent is top-level, promote to top level if not already.
  7464. ((= prev-level 1)
  7465. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7466. do (org-do-promote)))
  7467. ;; If top-level, return to prev-level.
  7468. ((= cur-level 1)
  7469. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7470. do (org-do-demote)))
  7471. ;; If less than prev-level, promote one.
  7472. ((< cur-level prev-level)
  7473. (org-do-promote))
  7474. ;; If deeper than prev-level, promote until higher than
  7475. ;; prev-level.
  7476. ((> cur-level prev-level)
  7477. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7478. do (org-do-promote))))
  7479. t))))
  7480. (defun org-map-tree (fun)
  7481. "Call FUN for every heading underneath the current one."
  7482. (org-back-to-heading t)
  7483. (let ((level (funcall outline-level)))
  7484. (save-excursion
  7485. (funcall fun)
  7486. (while (and (progn
  7487. (outline-next-heading)
  7488. (> (funcall outline-level) level))
  7489. (not (eobp)))
  7490. (funcall fun)))))
  7491. (defun org-map-region (fun beg end)
  7492. "Call FUN for every heading between BEG and END."
  7493. (let ((org-ignore-region t))
  7494. (save-excursion
  7495. (setq end (copy-marker end))
  7496. (goto-char beg)
  7497. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7498. (< (point) end))
  7499. (funcall fun))
  7500. (while (and (progn
  7501. (outline-next-heading)
  7502. (< (point) end))
  7503. (not (eobp)))
  7504. (funcall fun)))))
  7505. (defun org-fixup-indentation (diff)
  7506. "Change the indentation in the current entry by DIFF.
  7507. DIFF is an integer. Indentation is done according to the
  7508. following rules:
  7509. - Planning information and property drawers are always indented
  7510. according to the new level of the headline;
  7511. - Footnote definitions and their contents are ignored;
  7512. - Inlinetasks' boundaries are not shifted;
  7513. - Empty lines are ignored;
  7514. - Other lines' indentation are shifted by DIFF columns, unless
  7515. it would introduce a structural change in the document, in
  7516. which case no shifting is done at all.
  7517. Assume point is at a heading or an inlinetask beginning."
  7518. (org-with-wide-buffer
  7519. (narrow-to-region (line-beginning-position)
  7520. (save-excursion
  7521. (if (org-with-limited-levels (org-at-heading-p))
  7522. (org-with-limited-levels (outline-next-heading))
  7523. (org-inlinetask-goto-end))
  7524. (point)))
  7525. (forward-line)
  7526. ;; Indent properly planning info and property drawer.
  7527. (when (looking-at-p org-planning-line-re)
  7528. (org-indent-line)
  7529. (forward-line))
  7530. (when (looking-at org-property-drawer-re)
  7531. (goto-char (match-end 0))
  7532. (forward-line)
  7533. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7534. (catch 'no-shift
  7535. (when (zerop diff) (throw 'no-shift nil))
  7536. ;; If DIFF is negative, first check if a shift is possible at all
  7537. ;; (e.g., it doesn't break structure). This can only happen if
  7538. ;; some contents are not properly indented.
  7539. (let ((case-fold-search t))
  7540. (when (< diff 0)
  7541. (let ((diff (- diff))
  7542. (forbidden-re (concat org-outline-regexp
  7543. "\\|"
  7544. (substring org-footnote-definition-re 1))))
  7545. (save-excursion
  7546. (while (not (eobp))
  7547. (cond
  7548. ((looking-at-p "[ \t]*$") (forward-line))
  7549. ((and (looking-at-p org-footnote-definition-re)
  7550. (let ((e (org-element-at-point)))
  7551. (and (eq (org-element-type e) 'footnote-definition)
  7552. (goto-char (org-element-property :end e))))))
  7553. ((looking-at-p org-outline-regexp) (forward-line))
  7554. ;; Give up if shifting would move before column 0 or
  7555. ;; if it would introduce a headline or a footnote
  7556. ;; definition.
  7557. (t
  7558. (skip-chars-forward " \t")
  7559. (let ((ind (current-column)))
  7560. (when (or (< ind diff)
  7561. (and (= ind diff) (looking-at-p forbidden-re)))
  7562. (throw 'no-shift nil)))
  7563. ;; Ignore contents of example blocks and source
  7564. ;; blocks if their indentation is meant to be
  7565. ;; preserved. Jump to block's closing line.
  7566. (beginning-of-line)
  7567. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7568. (let ((e (org-element-at-point)))
  7569. (and (memq (org-element-type e)
  7570. '(example-block src-block))
  7571. (or org-src-preserve-indentation
  7572. (org-element-property :preserve-indent e))
  7573. (goto-char (org-element-property :end e))
  7574. (progn (skip-chars-backward " \r\t\n")
  7575. (beginning-of-line)
  7576. t))))
  7577. (forward-line))))))))
  7578. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7579. ;; by DIFF. Also skip contents of source or example blocks
  7580. ;; when indentation is meant to be preserved.
  7581. (while (not (eobp))
  7582. (cond
  7583. ((and (looking-at-p org-footnote-definition-re)
  7584. (let ((e (org-element-at-point)))
  7585. (and (eq (org-element-type e) 'footnote-definition)
  7586. (goto-char (org-element-property :end e))))))
  7587. ((looking-at-p org-outline-regexp) (forward-line))
  7588. ((looking-at-p "[ \t]*$") (forward-line))
  7589. (t
  7590. (indent-line-to (+ (org-get-indentation) diff))
  7591. (beginning-of-line)
  7592. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7593. (let ((e (org-element-at-point)))
  7594. (and (memq (org-element-type e)
  7595. '(example-block src-block))
  7596. (or org-src-preserve-indentation
  7597. (org-element-property :preserve-indent e))
  7598. (goto-char (org-element-property :end e))
  7599. (progn (skip-chars-backward " \r\t\n")
  7600. (beginning-of-line)
  7601. t))))
  7602. (forward-line)))))))))
  7603. (defun org-convert-to-odd-levels ()
  7604. "Convert an Org file with all levels allowed to one with odd levels.
  7605. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7606. level 5 etc."
  7607. (interactive)
  7608. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7609. (let ((outline-level 'org-outline-level)
  7610. (org-odd-levels-only nil) n)
  7611. (save-excursion
  7612. (goto-char (point-min))
  7613. (while (re-search-forward "^\\*\\*+ " nil t)
  7614. (setq n (- (length (match-string 0)) 2))
  7615. (while (>= (setq n (1- n)) 0)
  7616. (org-demote))
  7617. (end-of-line 1))))))
  7618. (defun org-convert-to-oddeven-levels ()
  7619. "Convert an Org file with only odd levels to one with odd/even levels.
  7620. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7621. file contains a section with an even level, conversion would
  7622. destroy the structure of the file. An error is signaled in this
  7623. case."
  7624. (interactive)
  7625. (goto-char (point-min))
  7626. ;; First check if there are no even levels
  7627. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7628. (org-show-set-visibility 'canonical)
  7629. (error "Not all levels are odd in this file. Conversion not possible"))
  7630. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7631. (let ((outline-regexp org-outline-regexp)
  7632. (outline-level 'org-outline-level)
  7633. (org-odd-levels-only nil) n)
  7634. (save-excursion
  7635. (goto-char (point-min))
  7636. (while (re-search-forward "^\\*\\*+ " nil t)
  7637. (setq n (/ (1- (length (match-string 0))) 2))
  7638. (while (>= (setq n (1- n)) 0)
  7639. (org-promote))
  7640. (end-of-line 1))))))
  7641. (defun org-tr-level (n)
  7642. "Make N odd if required."
  7643. (if org-odd-levels-only (1+ (/ n 2)) n))
  7644. ;;; Vertical tree motion, cutting and pasting of subtrees
  7645. (defun org-move-subtree-up (&optional arg)
  7646. "Move the current subtree up past ARG headlines of the same level."
  7647. (interactive "p")
  7648. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7649. (defun org-move-subtree-down (&optional arg)
  7650. "Move the current subtree down past ARG headlines of the same level."
  7651. (interactive "p")
  7652. (setq arg (prefix-numeric-value arg))
  7653. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7654. 'org-get-last-sibling))
  7655. (ins-point (make-marker))
  7656. (cnt (abs arg))
  7657. (col (current-column))
  7658. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7659. ;; Select the tree
  7660. (org-back-to-heading)
  7661. (setq beg0 (point))
  7662. (save-excursion
  7663. (setq ne-beg (org-back-over-empty-lines))
  7664. (setq beg (point)))
  7665. (save-match-data
  7666. (save-excursion (outline-end-of-heading)
  7667. (setq folded (outline-invisible-p)))
  7668. (progn (org-end-of-subtree nil t)
  7669. (unless (eobp) (backward-char))))
  7670. (outline-next-heading)
  7671. (setq ne-end (org-back-over-empty-lines))
  7672. (setq end (point))
  7673. (goto-char beg0)
  7674. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7675. ;; include less whitespace
  7676. (save-excursion
  7677. (goto-char beg)
  7678. (forward-line (- ne-beg ne-end))
  7679. (setq beg (point))))
  7680. ;; Find insertion point, with error handling
  7681. (while (> cnt 0)
  7682. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7683. (progn (goto-char beg0)
  7684. (user-error "Cannot move past superior level or buffer limit")))
  7685. (setq cnt (1- cnt)))
  7686. (when (> arg 0)
  7687. ;; Moving forward - still need to move over subtree
  7688. (org-end-of-subtree t t)
  7689. (save-excursion
  7690. (org-back-over-empty-lines)
  7691. (or (bolp) (newline))))
  7692. (setq ne-ins (org-back-over-empty-lines))
  7693. (move-marker ins-point (point))
  7694. (setq txt (buffer-substring beg end))
  7695. (org-save-markers-in-region beg end)
  7696. (delete-region beg end)
  7697. (org-remove-empty-overlays-at beg)
  7698. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7699. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7700. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7701. (let ((bbb (point)))
  7702. (insert-before-markers txt)
  7703. (org-reinstall-markers-in-region bbb)
  7704. (move-marker ins-point bbb))
  7705. (or (bolp) (insert "\n"))
  7706. (setq ins-end (point))
  7707. (goto-char ins-point)
  7708. (org-skip-whitespace)
  7709. (when (and (< arg 0)
  7710. (org-first-sibling-p)
  7711. (> ne-ins ne-beg))
  7712. ;; Move whitespace back to beginning
  7713. (save-excursion
  7714. (goto-char ins-end)
  7715. (let ((kill-whole-line t))
  7716. (kill-line (- ne-ins ne-beg)) (point)))
  7717. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7718. (move-marker ins-point nil)
  7719. (if folded
  7720. (outline-hide-subtree)
  7721. (org-show-entry)
  7722. (org-show-children)
  7723. (org-cycle-hide-drawers 'children))
  7724. (org-clean-visibility-after-subtree-move)
  7725. ;; move back to the initial column we were at
  7726. (move-to-column col)))
  7727. (defvar org-subtree-clip ""
  7728. "Clipboard for cut and paste of subtrees.
  7729. This is actually only a copy of the kill, because we use the normal kill
  7730. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7731. (defvar org-subtree-clip-folded nil
  7732. "Was the last copied subtree folded?
  7733. This is used to fold the tree back after pasting.")
  7734. (defun org-cut-subtree (&optional n)
  7735. "Cut the current subtree into the clipboard.
  7736. With prefix arg N, cut this many sequential subtrees.
  7737. This is a short-hand for marking the subtree and then cutting it."
  7738. (interactive "p")
  7739. (org-copy-subtree n 'cut))
  7740. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7741. "Copy the current subtree it in the clipboard.
  7742. With prefix arg N, copy this many sequential subtrees.
  7743. This is a short-hand for marking the subtree and then copying it.
  7744. If CUT is non-nil, actually cut the subtree.
  7745. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7746. of some markers in the region, even if CUT is non-nil. This is
  7747. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7748. (interactive "p")
  7749. (let (beg end folded (beg0 (point)))
  7750. (if (called-interactively-p 'any)
  7751. (org-back-to-heading nil) ; take what looks like a subtree
  7752. (org-back-to-heading t)) ; take what is really there
  7753. (setq beg (point))
  7754. (skip-chars-forward " \t\r\n")
  7755. (save-match-data
  7756. (if nosubtrees
  7757. (outline-next-heading)
  7758. (save-excursion (outline-end-of-heading)
  7759. (setq folded (outline-invisible-p)))
  7760. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7761. (org-end-of-subtree t t)))
  7762. ;; Include the end of an inlinetask
  7763. (when (and (featurep 'org-inlinetask)
  7764. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7765. "END[ \t]*$")))
  7766. (end-of-line))
  7767. (setq end (point))
  7768. (goto-char beg0)
  7769. (when (> end beg)
  7770. (setq org-subtree-clip-folded folded)
  7771. (when (or cut force-store-markers)
  7772. (org-save-markers-in-region beg end))
  7773. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7774. (setq org-subtree-clip (current-kill 0))
  7775. (message "%s: Subtree(s) with %d characters"
  7776. (if cut "Cut" "Copied")
  7777. (length org-subtree-clip)))))
  7778. (defun org-paste-subtree (&optional level tree for-yank remove)
  7779. "Paste the clipboard as a subtree, with modification of headline level.
  7780. The entire subtree is promoted or demoted in order to match a new headline
  7781. level.
  7782. If the cursor is at the beginning of a headline, the same level as
  7783. that headline is used to paste the tree.
  7784. If not, the new level is derived from the *visible* headings
  7785. before and after the insertion point, and taken to be the inferior headline
  7786. level of the two. So if the previous visible heading is level 3 and the
  7787. next is level 4 (or vice versa), level 4 will be used for insertion.
  7788. This makes sure that the subtree remains an independent subtree and does
  7789. not swallow low level entries.
  7790. You can also force a different level, either by using a numeric prefix
  7791. argument, or by inserting the heading marker by hand. For example, if the
  7792. cursor is after \"*****\", then the tree will be shifted to level 5.
  7793. If optional TREE is given, use this text instead of the kill ring.
  7794. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7795. move back over whitespace before inserting, and move point to the end of
  7796. the inserted text when done.
  7797. When REMOVE is non-nil, remove the subtree from the clipboard."
  7798. (interactive "P")
  7799. (setq tree (or tree (and kill-ring (current-kill 0))))
  7800. (unless (org-kill-is-subtree-p tree)
  7801. (user-error "%s"
  7802. (substitute-command-keys
  7803. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7804. (org-with-limited-levels
  7805. (let* ((visp (not (outline-invisible-p)))
  7806. (txt tree)
  7807. (^re_ "\\(\\*+\\)[ \t]*")
  7808. (old-level (if (string-match org-outline-regexp-bol txt)
  7809. (- (match-end 0) (match-beginning 0) 1)
  7810. -1))
  7811. (force-level (cond (level (prefix-numeric-value level))
  7812. ((and (looking-at "[ \t]*$")
  7813. (string-match
  7814. "^\\*+$" (buffer-substring
  7815. (point-at-bol) (point))))
  7816. (- (match-end 0) (match-beginning 0)))
  7817. ((and (bolp)
  7818. (looking-at org-outline-regexp))
  7819. (- (match-end 0) (point) 1))))
  7820. (previous-level (save-excursion
  7821. (condition-case nil
  7822. (progn
  7823. (outline-previous-visible-heading 1)
  7824. (if (looking-at ^re_)
  7825. (- (match-end 0) (match-beginning 0) 1)
  7826. 1))
  7827. (error 1))))
  7828. (next-level (save-excursion
  7829. (condition-case nil
  7830. (progn
  7831. (or (looking-at org-outline-regexp)
  7832. (outline-next-visible-heading 1))
  7833. (if (looking-at ^re_)
  7834. (- (match-end 0) (match-beginning 0) 1)
  7835. 1))
  7836. (error 1))))
  7837. (new-level (or force-level (max previous-level next-level)))
  7838. (shift (if (or (= old-level -1)
  7839. (= new-level -1)
  7840. (= old-level new-level))
  7841. 0
  7842. (- new-level old-level)))
  7843. (delta (if (> shift 0) -1 1))
  7844. (func (if (> shift 0) 'org-demote 'org-promote))
  7845. (org-odd-levels-only nil)
  7846. beg end newend)
  7847. ;; Remove the forced level indicator
  7848. (when force-level
  7849. (delete-region (point-at-bol) (point)))
  7850. ;; Paste
  7851. (beginning-of-line (if (bolp) 1 2))
  7852. (setq beg (point))
  7853. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7854. (insert-before-markers txt)
  7855. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7856. (setq newend (point))
  7857. (org-reinstall-markers-in-region beg)
  7858. (setq end (point))
  7859. (goto-char beg)
  7860. (skip-chars-forward " \t\n\r")
  7861. (setq beg (point))
  7862. (when (and (outline-invisible-p) visp)
  7863. (save-excursion (outline-show-heading)))
  7864. ;; Shift if necessary
  7865. (unless (= shift 0)
  7866. (save-restriction
  7867. (narrow-to-region beg end)
  7868. (while (not (= shift 0))
  7869. (org-map-region func (point-min) (point-max))
  7870. (setq shift (+ delta shift)))
  7871. (goto-char (point-min))
  7872. (setq newend (point-max))))
  7873. (when (or (called-interactively-p 'interactive) for-yank)
  7874. (message "Clipboard pasted as level %d subtree" new-level))
  7875. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7876. kill-ring
  7877. (eq org-subtree-clip (current-kill 0))
  7878. org-subtree-clip-folded)
  7879. ;; The tree was folded before it was killed/copied
  7880. (outline-hide-subtree))
  7881. (and for-yank (goto-char newend))
  7882. (and remove (setq kill-ring (cdr kill-ring))))))
  7883. (defun org-kill-is-subtree-p (&optional txt)
  7884. "Check if the current kill is an outline subtree, or a set of trees.
  7885. Returns nil if kill does not start with a headline, or if the first
  7886. headline level is not the largest headline level in the tree.
  7887. So this will actually accept several entries of equal levels as well,
  7888. which is OK for `org-paste-subtree'.
  7889. If optional TXT is given, check this string instead of the current kill."
  7890. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7891. (re (org-get-limited-outline-regexp))
  7892. (^re (concat "^" re))
  7893. (start-level (and kill
  7894. (string-match
  7895. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7896. kill)
  7897. (- (match-end 2) (match-beginning 2) 1)))
  7898. (start (1+ (or (match-beginning 2) -1))))
  7899. (if (not start-level)
  7900. (progn
  7901. nil) ;; does not even start with a heading
  7902. (catch 'exit
  7903. (while (setq start (string-match ^re kill (1+ start)))
  7904. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7905. (throw 'exit nil)))
  7906. t))))
  7907. (defvar org-markers-to-move nil
  7908. "Markers that should be moved with a cut-and-paste operation.
  7909. Those markers are stored together with their positions relative to
  7910. the start of the region.")
  7911. (defun org-save-markers-in-region (beg end)
  7912. "Check markers in region.
  7913. If these markers are between BEG and END, record their position relative
  7914. to BEG, so that after moving the block of text, we can put the markers back
  7915. into place.
  7916. This function gets called just before an entry or tree gets cut from the
  7917. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7918. called immediately, to move the markers with the entries."
  7919. (setq org-markers-to-move nil)
  7920. (when (featurep 'org-clock)
  7921. (org-clock-save-markers-for-cut-and-paste beg end))
  7922. (when (featurep 'org-agenda)
  7923. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7924. (defun org-check-and-save-marker (marker beg end)
  7925. "Check if MARKER is between BEG and END.
  7926. If yes, remember the marker and the distance to BEG."
  7927. (when (and (marker-buffer marker)
  7928. (equal (marker-buffer marker) (current-buffer))
  7929. (>= marker beg) (< marker end))
  7930. (push (cons marker (- marker beg)) org-markers-to-move)))
  7931. (defun org-reinstall-markers-in-region (beg)
  7932. "Move all remembered markers to their position relative to BEG."
  7933. (dolist (x org-markers-to-move)
  7934. (move-marker (car x) (+ beg (cdr x))))
  7935. (setq org-markers-to-move nil))
  7936. (defun org-narrow-to-subtree ()
  7937. "Narrow buffer to the current subtree."
  7938. (interactive)
  7939. (save-excursion
  7940. (save-match-data
  7941. (org-with-limited-levels
  7942. (narrow-to-region
  7943. (progn (org-back-to-heading t) (point))
  7944. (progn (org-end-of-subtree t t)
  7945. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7946. (point)))))))
  7947. (defun org-narrow-to-block ()
  7948. "Narrow buffer to the current block."
  7949. (interactive)
  7950. (let* ((case-fold-search t)
  7951. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7952. "^[ \t]*#\\+end_.*")))
  7953. (if blockp
  7954. (narrow-to-region (car blockp) (cdr blockp))
  7955. (user-error "Not in a block"))))
  7956. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7957. "Clone the task (subtree) at point N times.
  7958. The clones will be inserted as siblings.
  7959. In interactive use, the user will be prompted for the number of
  7960. clones to be produced. If the entry has a timestamp, the user
  7961. will also be prompted for a time shift, which may be a repeater
  7962. as used in time stamps, for example `+3d'. To disable this,
  7963. you can call the function with a universal prefix argument.
  7964. When a valid repeater is given and the entry contains any time
  7965. stamps, the clones will become a sequence in time, with time
  7966. stamps in the subtree shifted for each clone produced. If SHIFT
  7967. is nil or the empty string, time stamps will be left alone. The
  7968. ID property of the original subtree is removed.
  7969. In each clone, all the CLOCK entries will be removed. This
  7970. prevents Org from considering that the clocked times overlap.
  7971. If the original subtree did contain time stamps with a repeater,
  7972. the following will happen:
  7973. - the repeater will be removed in each clone
  7974. - an additional clone will be produced, with the current, unshifted
  7975. date(s) in the entry.
  7976. - the original entry will be placed *after* all the clones, with
  7977. repeater intact.
  7978. - the start days in the repeater in the original entry will be shifted
  7979. to past the last clone.
  7980. In this way you can spell out a number of instances of a repeating task,
  7981. and still retain the repeater to cover future instances of the task.
  7982. As described above, N+1 clones are produced when the original
  7983. subtree has a repeater. Setting N to 0, then, can be used to
  7984. remove the repeater from a subtree and create a shifted clone
  7985. with the original repeater."
  7986. (interactive "nNumber of clones to produce: ")
  7987. (let ((shift
  7988. (or shift
  7989. (if (and (not (equal current-prefix-arg '(4)))
  7990. (save-excursion
  7991. (re-search-forward org-ts-regexp-both
  7992. (save-excursion
  7993. (org-end-of-subtree t)
  7994. (point)) t)))
  7995. (read-from-minibuffer
  7996. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7997. ""))) ;; No time shift
  7998. (n-no-remove -1)
  7999. (drawer-re org-drawer-regexp)
  8000. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  8001. beg end template task idprop
  8002. shift-n shift-what doshift nmin nmax)
  8003. (unless (wholenump n)
  8004. (user-error "Invalid number of replications %s" n))
  8005. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  8006. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  8007. shift)))
  8008. (user-error "Invalid shift specification %s" shift))
  8009. (when doshift
  8010. (setq shift-n (string-to-number (match-string 1 shift))
  8011. shift-what (cdr (assoc (match-string 2 shift)
  8012. '(("d" . day) ("w" . week)
  8013. ("m" . month) ("y" . year))))))
  8014. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  8015. (setq nmin 1 nmax n)
  8016. (org-back-to-heading t)
  8017. (setq beg (point))
  8018. (setq idprop (org-entry-get nil "ID"))
  8019. (org-end-of-subtree t t)
  8020. (or (bolp) (insert "\n"))
  8021. (setq end (point))
  8022. (setq template (buffer-substring beg end))
  8023. (when (and doshift
  8024. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  8025. (delete-region beg end)
  8026. (setq end beg)
  8027. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  8028. (goto-char end)
  8029. (cl-loop for n from nmin to nmax do
  8030. ;; prepare clone
  8031. (with-temp-buffer
  8032. (insert template)
  8033. (org-mode)
  8034. (goto-char (point-min))
  8035. (org-show-subtree)
  8036. (and idprop (if org-clone-delete-id
  8037. (org-entry-delete nil "ID")
  8038. (org-id-get-create t)))
  8039. (unless (= n 0)
  8040. (while (re-search-forward org-clock-re nil t)
  8041. (kill-whole-line))
  8042. (goto-char (point-min))
  8043. (while (re-search-forward drawer-re nil t)
  8044. (org-remove-empty-drawer-at (point))))
  8045. (goto-char (point-min))
  8046. (when doshift
  8047. (while (re-search-forward org-ts-regexp-both nil t)
  8048. (org-timestamp-change (* n shift-n) shift-what))
  8049. (unless (= n n-no-remove)
  8050. (goto-char (point-min))
  8051. (while (re-search-forward org-ts-regexp nil t)
  8052. (save-excursion
  8053. (goto-char (match-beginning 0))
  8054. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8055. (delete-region (match-beginning 1) (match-end 1)))))))
  8056. (setq task (buffer-string)))
  8057. (insert task))
  8058. (goto-char beg)))
  8059. ;;; Outline Sorting
  8060. (defun org-sort (with-case)
  8061. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8062. Optional argument WITH-CASE means sort case-sensitively."
  8063. (interactive "P")
  8064. (cond
  8065. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8066. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8067. (t
  8068. (org-call-with-arg 'org-sort-entries with-case))))
  8069. (defun org-sort-remove-invisible (s)
  8070. "Remove invisible links from string S."
  8071. (remove-text-properties 0 (length s) org-rm-props s)
  8072. (while (string-match org-bracket-link-regexp s)
  8073. (setq s (replace-match (if (match-end 2)
  8074. (match-string 3 s)
  8075. (match-string 1 s))
  8076. t t s)))
  8077. (let ((st (format " %s " s)))
  8078. (while (string-match org-emph-re st)
  8079. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8080. (setq s (substring st 1 -1)))
  8081. s)
  8082. (defvar org-priority-regexp) ; defined later in the file
  8083. (defvar org-after-sorting-entries-or-items-hook nil
  8084. "Hook that is run after a bunch of entries or items have been sorted.
  8085. When children are sorted, the cursor is in the parent line when this
  8086. hook gets called. When a region or a plain list is sorted, the cursor
  8087. will be in the first entry of the sorted region/list.")
  8088. (defun org-sort-entries
  8089. (&optional with-case sorting-type getkey-func compare-func property)
  8090. "Sort entries on a certain level of an outline tree.
  8091. If there is an active region, the entries in the region are sorted.
  8092. Else, if the cursor is before the first entry, sort the top-level items.
  8093. Else, the children of the entry at point are sorted.
  8094. Sorting can be alphabetically, numerically, by date/time as given by
  8095. a time stamp, by a property, by priority order, or by a custom function.
  8096. The command prompts for the sorting type unless it has been given to the
  8097. function through the SORTING-TYPE argument, which needs to be a character,
  8098. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8099. the precise meaning of each character:
  8100. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8101. c By creation time, which is assumed to be the first inactive time stamp
  8102. at the beginning of a line.
  8103. d By deadline date/time.
  8104. k By clocking time.
  8105. n Numerically, by converting the beginning of the entry/item to a number.
  8106. o By order of TODO keywords.
  8107. p By priority according to the cookie.
  8108. r By the value of a property.
  8109. s By scheduled date/time.
  8110. t By date/time, either the first active time stamp in the entry, or, if
  8111. none exist, by the first inactive one.
  8112. Capital letters will reverse the sort order.
  8113. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8114. called with point at the beginning of the record. It must return either
  8115. a string or a number that should serve as the sorting key for that record.
  8116. Comparing entries ignores case by default. However, with an optional argument
  8117. WITH-CASE, the sorting considers case as well.
  8118. Sorting is done against the visible part of the headlines, it ignores hidden
  8119. links.
  8120. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8121. (interactive "P")
  8122. (let ((case-func (if with-case 'identity 'downcase))
  8123. (cmstr
  8124. ;; The clock marker is lost when using `sort-subr', let's
  8125. ;; store the clocking string.
  8126. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8127. (save-excursion
  8128. (goto-char org-clock-marker)
  8129. (buffer-substring-no-properties (line-beginning-position)
  8130. (point)))))
  8131. start beg end stars re re2
  8132. txt what tmp)
  8133. ;; Find beginning and end of region to sort
  8134. (cond
  8135. ((org-region-active-p)
  8136. ;; we will sort the region
  8137. (setq end (region-end)
  8138. what "region")
  8139. (goto-char (region-beginning))
  8140. (unless (org-at-heading-p) (outline-next-heading))
  8141. (setq start (point)))
  8142. ((or (org-at-heading-p)
  8143. (ignore-errors (progn (org-back-to-heading) t)))
  8144. ;; we will sort the children of the current headline
  8145. (org-back-to-heading)
  8146. (setq start (point)
  8147. end (progn (org-end-of-subtree t t)
  8148. (or (bolp) (insert "\n"))
  8149. (when (>= (org-back-over-empty-lines) 1)
  8150. (forward-line 1))
  8151. (point))
  8152. what "children")
  8153. (goto-char start)
  8154. (outline-show-subtree)
  8155. (outline-next-heading))
  8156. (t
  8157. ;; we will sort the top-level entries in this file
  8158. (goto-char (point-min))
  8159. (or (org-at-heading-p) (outline-next-heading))
  8160. (setq start (point))
  8161. (goto-char (point-max))
  8162. (beginning-of-line 1)
  8163. (when (looking-at ".*?\\S-")
  8164. ;; File ends in a non-white line
  8165. (end-of-line 1)
  8166. (insert "\n"))
  8167. (setq end (point-max))
  8168. (setq what "top-level")
  8169. (goto-char start)
  8170. (outline-show-all)))
  8171. (setq beg (point))
  8172. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8173. (looking-at "\\(\\*+\\)")
  8174. (setq stars (match-string 1)
  8175. re (concat "^" (regexp-quote stars) " +")
  8176. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8177. txt (buffer-substring beg end))
  8178. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8179. (when (and (not (equal stars "*")) (string-match re2 txt))
  8180. (user-error "Region to sort contains a level above the first entry"))
  8181. (unless sorting-type
  8182. (message
  8183. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8184. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8185. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8186. what)
  8187. (setq sorting-type (read-char-exclusive))
  8188. (unless getkey-func
  8189. (and (= (downcase sorting-type) ?f)
  8190. (setq getkey-func
  8191. (completing-read "Sort using function: "
  8192. obarray 'fboundp t nil nil))
  8193. (setq getkey-func (intern getkey-func))))
  8194. (and (= (downcase sorting-type) ?r)
  8195. (not property)
  8196. (setq property
  8197. (completing-read "Property: "
  8198. (mapcar #'list (org-buffer-property-keys t))
  8199. nil t))))
  8200. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8201. (message "Sorting entries...")
  8202. (save-restriction
  8203. (narrow-to-region start end)
  8204. (let ((dcst (downcase sorting-type))
  8205. (case-fold-search nil)
  8206. (now (current-time)))
  8207. (sort-subr
  8208. (/= dcst sorting-type)
  8209. ;; This function moves to the beginning character of the "record" to
  8210. ;; be sorted.
  8211. (lambda nil
  8212. (if (re-search-forward re nil t)
  8213. (goto-char (match-beginning 0))
  8214. (goto-char (point-max))))
  8215. ;; This function moves to the last character of the "record" being
  8216. ;; sorted.
  8217. (lambda nil
  8218. (save-match-data
  8219. (condition-case nil
  8220. (outline-forward-same-level 1)
  8221. (error
  8222. (goto-char (point-max))))))
  8223. ;; This function returns the value that gets sorted against.
  8224. (lambda nil
  8225. (cond
  8226. ((= dcst ?n)
  8227. (if (looking-at org-complex-heading-regexp)
  8228. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8229. nil))
  8230. ((= dcst ?a)
  8231. (if (looking-at org-complex-heading-regexp)
  8232. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8233. nil))
  8234. ((= dcst ?k)
  8235. (or (get-text-property (point) :org-clock-minutes) 0))
  8236. ((= dcst ?t)
  8237. (let ((end (save-excursion (outline-next-heading) (point))))
  8238. (if (or (re-search-forward org-ts-regexp end t)
  8239. (re-search-forward org-ts-regexp-both end t))
  8240. (org-time-string-to-seconds (match-string 0))
  8241. (float-time now))))
  8242. ((= dcst ?c)
  8243. (let ((end (save-excursion (outline-next-heading) (point))))
  8244. (if (re-search-forward
  8245. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8246. end t)
  8247. (org-time-string-to-seconds (match-string 0))
  8248. (float-time now))))
  8249. ((= dcst ?s)
  8250. (let ((end (save-excursion (outline-next-heading) (point))))
  8251. (if (re-search-forward org-scheduled-time-regexp end t)
  8252. (org-time-string-to-seconds (match-string 1))
  8253. (float-time now))))
  8254. ((= dcst ?d)
  8255. (let ((end (save-excursion (outline-next-heading) (point))))
  8256. (if (re-search-forward org-deadline-time-regexp end t)
  8257. (org-time-string-to-seconds (match-string 1))
  8258. (float-time now))))
  8259. ((= dcst ?p)
  8260. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8261. (string-to-char (match-string 2))
  8262. org-default-priority))
  8263. ((= dcst ?r)
  8264. (or (org-entry-get nil property) ""))
  8265. ((= dcst ?o)
  8266. (when (looking-at org-complex-heading-regexp)
  8267. (let* ((m (match-string 2))
  8268. (s (if (member m org-done-keywords) '- '+)))
  8269. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8270. ((= dcst ?f)
  8271. (if getkey-func
  8272. (progn
  8273. (setq tmp (funcall getkey-func))
  8274. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8275. tmp)
  8276. (error "Invalid key function `%s'" getkey-func)))
  8277. (t (error "Invalid sorting type `%c'" sorting-type))))
  8278. nil
  8279. (cond
  8280. ((= dcst ?a) 'string<)
  8281. ((= dcst ?f) compare-func)
  8282. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8283. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8284. ;; Reset the clock marker if needed
  8285. (when cmstr
  8286. (save-excursion
  8287. (goto-char start)
  8288. (search-forward cmstr nil t)
  8289. (move-marker org-clock-marker (point))))
  8290. (message "Sorting entries...done")))
  8291. ;;; The orgstruct minor mode
  8292. ;; Define a minor mode which can be used in other modes in order to
  8293. ;; integrate the Org mode structure editing commands.
  8294. ;; This is really a hack, because the Org mode structure commands use
  8295. ;; keys which normally belong to the major mode. Here is how it
  8296. ;; works: The minor mode defines all the keys necessary to operate the
  8297. ;; structure commands, but wraps the commands into a function which
  8298. ;; tests if the cursor is currently at a headline or a plain list
  8299. ;; item. If that is the case, the structure command is used,
  8300. ;; temporarily setting many Org mode variables like regular
  8301. ;; expressions for filling etc. However, when any of those keys is
  8302. ;; used at a different location, function uses `key-binding' to look
  8303. ;; up if the key has an associated command in another currently active
  8304. ;; keymap (minor modes, major mode, global), and executes that
  8305. ;; command. There might be problems if any of the keys is otherwise
  8306. ;; used as a prefix key.
  8307. (defcustom orgstruct-heading-prefix-regexp ""
  8308. "Regexp that matches the custom prefix of Org headlines in
  8309. orgstruct(++)-mode."
  8310. :group 'org
  8311. :version "24.4"
  8312. :package-version '(Org . "8.3")
  8313. :type 'regexp)
  8314. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8315. (defcustom orgstruct-setup-hook nil
  8316. "Hook run after orgstruct-mode-map is filled."
  8317. :group 'org
  8318. :version "24.4"
  8319. :package-version '(Org . "8.0")
  8320. :type 'hook)
  8321. (defvar orgstruct-initialized nil)
  8322. (defvar org-local-vars nil
  8323. "List of local variables, for use by `orgstruct-mode'.")
  8324. ;;;###autoload
  8325. (define-minor-mode orgstruct-mode
  8326. "Toggle the minor mode `orgstruct-mode'.
  8327. This mode is for using Org mode structure commands in other
  8328. modes. The following keys behave as if Org mode were active, if
  8329. the cursor is on a headline, or on a plain list item (both as
  8330. defined by Org mode)."
  8331. nil " OrgStruct" (make-sparse-keymap)
  8332. (funcall (if orgstruct-mode
  8333. 'add-to-invisibility-spec
  8334. 'remove-from-invisibility-spec)
  8335. '(outline . t))
  8336. (when orgstruct-mode
  8337. (org-load-modules-maybe)
  8338. (unless orgstruct-initialized
  8339. (orgstruct-setup)
  8340. (setq orgstruct-initialized t))))
  8341. ;;;###autoload
  8342. (defun turn-on-orgstruct ()
  8343. "Unconditionally turn on `orgstruct-mode'."
  8344. (orgstruct-mode 1))
  8345. (defvar-local orgstruct-is-++ nil
  8346. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8347. (defvar-local org-fb-vars nil)
  8348. (defun orgstruct++-mode (&optional arg)
  8349. "Toggle `orgstruct-mode', the enhanced version of it.
  8350. In addition to setting orgstruct-mode, this also exports all
  8351. indentation and autofilling variables from Org mode into the
  8352. buffer. It will also recognize item context in multiline items."
  8353. (interactive "P")
  8354. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8355. (if (< arg 1)
  8356. (progn (orgstruct-mode -1)
  8357. (dolist (v org-fb-vars)
  8358. (set (make-local-variable (car v))
  8359. (if (eq (car-safe (cadr v)) 'quote)
  8360. (cl-cadadr v)
  8361. (nth 1 v)))))
  8362. (orgstruct-mode 1)
  8363. (setq org-fb-vars nil)
  8364. (unless org-local-vars
  8365. (setq org-local-vars (org-get-local-variables)))
  8366. (let (var val)
  8367. (dolist (x org-local-vars)
  8368. (when (string-match
  8369. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8370. \\|fill-prefix\\|indent-\\)"
  8371. (symbol-name (car x)))
  8372. (setq var (car x) val (nth 1 x))
  8373. (push (list var `(quote ,(eval var))) org-fb-vars)
  8374. (set (make-local-variable var)
  8375. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8376. (setq-local orgstruct-is-++ t))))
  8377. ;;;###autoload
  8378. (defun turn-on-orgstruct++ ()
  8379. "Unconditionally turn on `orgstruct++-mode'."
  8380. (orgstruct++-mode 1))
  8381. (defun orgstruct-error ()
  8382. "Error when there is no default binding for a structure key."
  8383. (interactive)
  8384. (funcall (if (fboundp 'user-error)
  8385. 'user-error
  8386. 'error)
  8387. "This key has no function outside structure elements"))
  8388. (defun orgstruct-setup ()
  8389. "Setup orgstruct keymap."
  8390. (dolist (cell '((org-demote . t)
  8391. (org-metaleft . t)
  8392. (org-metaright . t)
  8393. (org-promote . t)
  8394. (org-shiftmetaleft . t)
  8395. (org-shiftmetaright . t)
  8396. org-backward-element
  8397. org-backward-heading-same-level
  8398. org-ctrl-c-ret
  8399. org-ctrl-c-minus
  8400. org-ctrl-c-star
  8401. org-cycle
  8402. org-force-cycle-archived
  8403. org-forward-heading-same-level
  8404. org-insert-heading
  8405. org-insert-heading-respect-content
  8406. org-kill-note-or-show-branches
  8407. org-mark-subtree
  8408. org-meta-return
  8409. org-metadown
  8410. org-metaup
  8411. org-narrow-to-subtree
  8412. org-promote-subtree
  8413. org-reveal
  8414. org-shiftdown
  8415. org-shiftleft
  8416. org-shiftmetadown
  8417. org-shiftmetaup
  8418. org-shiftright
  8419. org-shifttab
  8420. org-shifttab
  8421. org-shiftup
  8422. org-show-children
  8423. org-show-subtree
  8424. org-sort
  8425. org-up-element
  8426. outline-demote
  8427. outline-next-visible-heading
  8428. outline-previous-visible-heading
  8429. outline-promote
  8430. outline-up-heading))
  8431. (let ((f (or (car-safe cell) cell))
  8432. (disable-when-heading-prefix (cdr-safe cell)))
  8433. (when (fboundp f)
  8434. (let ((new-bindings))
  8435. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8436. (where-is-internal f outline-mode-map)))
  8437. (push binding new-bindings)
  8438. ;; TODO use local-function-key-map
  8439. (dolist (rep '(("<tab>" . "TAB")
  8440. ("<return>" . "RET")
  8441. ("<escape>" . "ESC")
  8442. ("<delete>" . "DEL")))
  8443. (setq binding (read-kbd-macro
  8444. (let ((case-fold-search))
  8445. (replace-regexp-in-string
  8446. (regexp-quote (cdr rep))
  8447. (car rep)
  8448. (key-description binding)))))
  8449. (cl-pushnew binding new-bindings :test 'equal)))
  8450. (dolist (binding new-bindings)
  8451. (let ((key (lookup-key orgstruct-mode-map binding)))
  8452. (when (or (not key) (numberp key))
  8453. (ignore-errors
  8454. (org-defkey orgstruct-mode-map
  8455. binding
  8456. (orgstruct-make-binding
  8457. f binding disable-when-heading-prefix))))))))))
  8458. (run-hooks 'orgstruct-setup-hook))
  8459. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8460. "Create a function for binding in the structure minor mode.
  8461. FUN is the command to call inside a table. KEY is the key that
  8462. should be checked in for a command to execute outside of tables.
  8463. Non-nil `disable-when-heading-prefix' means to disable the command
  8464. if `orgstruct-heading-prefix-regexp' is not empty."
  8465. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8466. (let ((nname name)
  8467. (i 0))
  8468. (while (fboundp (intern nname))
  8469. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8470. (setq name (intern nname)))
  8471. (eval
  8472. (let ((bindings '((org-heading-regexp
  8473. (concat "^"
  8474. orgstruct-heading-prefix-regexp
  8475. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8476. (org-outline-regexp
  8477. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8478. (org-outline-regexp-bol
  8479. (concat "^" org-outline-regexp))
  8480. (outline-regexp org-outline-regexp)
  8481. (outline-heading-end-regexp "\n")
  8482. (outline-level 'org-outline-level)
  8483. (outline-heading-alist))))
  8484. `(defun ,name (arg)
  8485. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8486. "Outside of structure, run the binding of `"
  8487. (key-description key) "'."
  8488. (when disable-when-heading-prefix
  8489. (concat
  8490. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8491. "back to the default binding due to limitations of Org's implementation of\n"
  8492. "`" (symbol-name fun) "'.")))
  8493. (interactive "p")
  8494. (let* ((disable
  8495. ,(and disable-when-heading-prefix
  8496. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8497. (fallback
  8498. (or disable
  8499. (not
  8500. (let* ,bindings
  8501. (org-context-p 'headline 'item
  8502. ,(when (memq fun
  8503. '(org-insert-heading
  8504. org-insert-heading-respect-content
  8505. org-meta-return))
  8506. '(when orgstruct-is-++
  8507. 'item-body))))))))
  8508. (if fallback
  8509. (let* ((orgstruct-mode)
  8510. (binding
  8511. (let ((key ,key))
  8512. (catch 'exit
  8513. (dolist
  8514. (rep
  8515. '(nil
  8516. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8517. ("<\\([^>]*\\)return>" . "\\1RET")
  8518. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8519. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8520. nil)
  8521. (when rep
  8522. (setq key (read-kbd-macro
  8523. (let ((case-fold-search))
  8524. (replace-regexp-in-string
  8525. (car rep)
  8526. (cdr rep)
  8527. (key-description key))))))
  8528. (when (key-binding key)
  8529. (throw 'exit (key-binding key))))))))
  8530. (if (keymapp binding)
  8531. (org-set-transient-map binding)
  8532. (let ((func (or binding
  8533. (unless disable
  8534. 'orgstruct-error))))
  8535. (when func
  8536. (call-interactively func)))))
  8537. (org-run-like-in-org-mode
  8538. (lambda ()
  8539. (interactive)
  8540. (let* ,bindings
  8541. (call-interactively ',fun)))))))))
  8542. name))
  8543. (defun org-contextualize-keys (alist contexts)
  8544. "Return valid elements in ALIST depending on CONTEXTS.
  8545. `org-agenda-custom-commands' or `org-capture-templates' are the
  8546. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8547. or `org-capture-templates-contexts' are the associated contexts
  8548. definitions."
  8549. (let ((contexts
  8550. ;; normalize contexts
  8551. (mapcar
  8552. (lambda(c) (cond ((listp (cadr c))
  8553. (list (car c) (car c) (nth 1 c)))
  8554. ((string= "" (cadr c))
  8555. (list (car c) (car c) (nth 2 c)))
  8556. (t c)))
  8557. contexts))
  8558. (a alist) r s)
  8559. ;; loop over all commands or templates
  8560. (dolist (c a)
  8561. (let (vrules repl)
  8562. (cond
  8563. ((not (assoc (car c) contexts))
  8564. (push c r))
  8565. ((and (assoc (car c) contexts)
  8566. (setq vrules (org-contextualize-validate-key
  8567. (car c) contexts)))
  8568. (mapc (lambda (vr)
  8569. (unless (equal (car vr) (cadr vr))
  8570. (setq repl vr)))
  8571. vrules)
  8572. (if (not repl) (push c r)
  8573. (push (cadr repl) s)
  8574. (push
  8575. (cons (car c)
  8576. (cdr (or (assoc (cadr repl) alist)
  8577. (error "Undefined key `%s' as contextual replacement for `%s'"
  8578. (cadr repl) (car c)))))
  8579. r))))))
  8580. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8581. (delq
  8582. nil
  8583. (delete-dups
  8584. (mapcar (lambda (x)
  8585. (let ((tpl (car x)))
  8586. (unless (delq
  8587. nil
  8588. (mapcar (lambda (y)
  8589. (equal y tpl))
  8590. s))
  8591. x)))
  8592. (reverse r))))))
  8593. (defun org-contextualize-validate-key (key contexts)
  8594. "Check CONTEXTS for agenda or capture KEY."
  8595. (let (res)
  8596. (dolist (r contexts)
  8597. (dolist (rr (car (last r)))
  8598. (when
  8599. (and (equal key (car r))
  8600. (if (functionp rr) (funcall rr)
  8601. (or (and (eq (car rr) 'in-file)
  8602. (buffer-file-name)
  8603. (string-match (cdr rr) (buffer-file-name)))
  8604. (and (eq (car rr) 'in-mode)
  8605. (string-match (cdr rr) (symbol-name major-mode)))
  8606. (and (eq (car rr) 'in-buffer)
  8607. (string-match (cdr rr) (buffer-name)))
  8608. (when (and (eq (car rr) 'not-in-file)
  8609. (buffer-file-name))
  8610. (not (string-match (cdr rr) (buffer-file-name))))
  8611. (when (eq (car rr) 'not-in-mode)
  8612. (not (string-match (cdr rr) (symbol-name major-mode))))
  8613. (when (eq (car rr) 'not-in-buffer)
  8614. (not (string-match (cdr rr) (buffer-name)))))))
  8615. (push r res))))
  8616. (delete-dups (delq nil res))))
  8617. (defun org-context-p (&rest contexts)
  8618. "Check if local context is any of CONTEXTS.
  8619. Possible values in the list of contexts are `table', `headline', and `item'."
  8620. (let ((pos (point)))
  8621. (goto-char (point-at-bol))
  8622. (prog1 (or (and (memq 'table contexts)
  8623. (looking-at "[ \t]*|"))
  8624. (and (memq 'headline contexts)
  8625. (looking-at org-outline-regexp))
  8626. (and (memq 'item contexts)
  8627. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8628. (and (memq 'item-body contexts)
  8629. (org-in-item-p)))
  8630. (goto-char pos))))
  8631. (defconst org-unique-local-variables
  8632. '(org-element--cache
  8633. org-element--cache-objects
  8634. org-element--cache-sync-keys
  8635. org-element--cache-sync-requests
  8636. org-element--cache-sync-timer)
  8637. "List of local variables that cannot be transferred to another buffer.")
  8638. (defun org-get-local-variables ()
  8639. "Return a list of all local variables in an Org mode buffer."
  8640. (delq nil
  8641. (mapcar
  8642. (lambda (x)
  8643. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8644. (name (car binding)))
  8645. (and (not (get name 'org-state))
  8646. (not (memq name org-unique-local-variables))
  8647. (string-match-p
  8648. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8649. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8650. (symbol-name name))
  8651. binding)))
  8652. (with-temp-buffer
  8653. (org-mode)
  8654. (buffer-local-variables)))))
  8655. (defun org-clone-local-variables (from-buffer &optional regexp)
  8656. "Clone local variables from FROM-BUFFER.
  8657. Optional argument REGEXP selects variables to clone."
  8658. (dolist (pair (buffer-local-variables from-buffer))
  8659. (let ((name (car pair)))
  8660. (when (and (symbolp name)
  8661. (not (memq name org-unique-local-variables))
  8662. (or (null regexp) (string-match regexp (symbol-name name))))
  8663. (set (make-local-variable name) (cdr pair))))))
  8664. ;;;###autoload
  8665. (defun org-run-like-in-org-mode (cmd)
  8666. "Run a command, pretending that the current buffer is in Org mode.
  8667. This will temporarily bind local variables that are typically bound in
  8668. Org mode to the values they have in Org mode, and then interactively
  8669. call CMD."
  8670. (org-load-modules-maybe)
  8671. (unless org-local-vars
  8672. (setq org-local-vars (org-get-local-variables)))
  8673. (let (binds)
  8674. (dolist (var org-local-vars)
  8675. (when (or (not (boundp (car var)))
  8676. (eq (symbol-value (car var))
  8677. (default-value (car var))))
  8678. (push (list (car var) `(quote ,(cadr var))) binds)))
  8679. (eval `(let ,binds
  8680. (call-interactively (quote ,cmd))))))
  8681. (defun org-get-category (&optional pos force-refresh)
  8682. "Get the category applying to position POS."
  8683. (save-match-data
  8684. (when force-refresh (org-refresh-category-properties))
  8685. (let ((pos (or pos (point))))
  8686. (or (get-text-property pos 'org-category)
  8687. (progn (org-refresh-category-properties)
  8688. (get-text-property pos 'org-category))))))
  8689. ;;; Refresh properties
  8690. (defun org-refresh-properties (dprop tprop)
  8691. "Refresh buffer text properties.
  8692. DPROP is the drawer property and TPROP is either the
  8693. corresponding text property to set, or an alist with each element
  8694. being a text property (as a symbol) and a function to apply to
  8695. the value of the drawer property."
  8696. (let ((case-fold-search t)
  8697. (inhibit-read-only t))
  8698. (org-with-silent-modifications
  8699. (org-with-wide-buffer
  8700. (goto-char (point-min))
  8701. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8702. (org-refresh-property tprop (match-string-no-properties 1)))))))
  8703. (defun org-refresh-property (tprop p)
  8704. "Refresh the buffer text property TPROP from the drawer property P.
  8705. The refresh happens only for the current tree (not subtree)."
  8706. (unless (org-before-first-heading-p)
  8707. (save-excursion
  8708. (org-back-to-heading t)
  8709. (if (symbolp tprop)
  8710. ;; TPROP is a text property symbol
  8711. (put-text-property
  8712. (point) (or (outline-next-heading) (point-max)) tprop p)
  8713. ;; TPROP is an alist with (properties . function) elements
  8714. (dolist (al tprop)
  8715. (save-excursion
  8716. (put-text-property
  8717. (line-beginning-position) (or (outline-next-heading) (point-max))
  8718. (car al)
  8719. (funcall (cdr al) p))))))))
  8720. (defun org-refresh-category-properties ()
  8721. "Refresh category text properties in the buffer."
  8722. (let ((case-fold-search t)
  8723. (inhibit-read-only t)
  8724. (default-category
  8725. (cond ((null org-category)
  8726. (if buffer-file-name
  8727. (file-name-sans-extension
  8728. (file-name-nondirectory buffer-file-name))
  8729. "???"))
  8730. ((symbolp org-category) (symbol-name org-category))
  8731. (t org-category))))
  8732. (org-with-silent-modifications
  8733. (org-with-wide-buffer
  8734. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8735. ;; This is the default category for the buffer. If none is
  8736. ;; found, fall-back to `org-category' or buffer file name.
  8737. (put-text-property
  8738. (point-min) (point-max)
  8739. 'org-category
  8740. (catch 'buffer-category
  8741. (goto-char (point-max))
  8742. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8743. (let ((element (org-element-at-point)))
  8744. (when (eq (org-element-type element) 'keyword)
  8745. (throw 'buffer-category
  8746. (org-element-property :value element)))))
  8747. default-category))
  8748. ;; Set sub-tree specific categories.
  8749. (goto-char (point-min))
  8750. (let ((regexp (org-re-property "CATEGORY")))
  8751. (while (re-search-forward regexp nil t)
  8752. (let ((value (match-string-no-properties 3)))
  8753. (when (org-at-property-p)
  8754. (put-text-property
  8755. (save-excursion (org-back-to-heading t) (point))
  8756. (save-excursion (org-end-of-subtree t t) (point))
  8757. 'org-category
  8758. value)))))))))
  8759. (defun org-refresh-stats-properties ()
  8760. "Refresh stats text properties in the buffer."
  8761. (let (stats)
  8762. (org-with-silent-modifications
  8763. (org-with-wide-buffer
  8764. (goto-char (point-min))
  8765. (while (re-search-forward
  8766. (concat org-outline-regexp-bol ".*"
  8767. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8768. nil t)
  8769. (setq stats (cond ((equal (match-string 3) "0") 0)
  8770. ((match-string 2)
  8771. (/ (* (string-to-number (match-string 2)) 100)
  8772. (string-to-number (match-string 3))))
  8773. (t (string-to-number (match-string 1)))))
  8774. (org-back-to-heading t)
  8775. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8776. 'org-stats stats))))))
  8777. (defun org-refresh-effort-properties ()
  8778. "Refresh effort properties"
  8779. (org-refresh-properties
  8780. org-effort-property
  8781. '((effort . identity)
  8782. (effort-minutes . org-duration-string-to-minutes))))
  8783. ;;;; Link Stuff
  8784. ;;; Link abbreviations
  8785. (defun org-link-expand-abbrev (link)
  8786. "Apply replacements as defined in `org-link-abbrev-alist'."
  8787. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8788. (let* ((key (match-string 1 link))
  8789. (as (or (assoc key org-link-abbrev-alist-local)
  8790. (assoc key org-link-abbrev-alist)))
  8791. (tag (and (match-end 2) (match-string 3 link)))
  8792. rpl)
  8793. (if (not as)
  8794. link
  8795. (setq rpl (cdr as))
  8796. (cond
  8797. ((symbolp rpl) (funcall rpl tag))
  8798. ((string-match "%(\\([^)]+\\))" rpl)
  8799. (replace-match
  8800. (save-match-data
  8801. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8802. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8803. ((string-match "%h" rpl)
  8804. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8805. (t (concat rpl tag)))))
  8806. link))
  8807. ;;; Storing and inserting links
  8808. (defvar org-insert-link-history nil
  8809. "Minibuffer history for links inserted with `org-insert-link'.")
  8810. (defvar org-stored-links nil
  8811. "Contains the links stored with `org-store-link'.")
  8812. (defvar org-store-link-plist nil
  8813. "Plist with info about the most recently link created with `org-store-link'.")
  8814. (defun org-store-link-functions ()
  8815. "Return a list of functions that are called to create and store a link.
  8816. The functions defined in the :store property of
  8817. `org-link-parameters'.
  8818. Each function will be called in turn until one returns a non-nil
  8819. value. Each function should check if it is responsible for
  8820. creating this link (for example by looking at the major mode).
  8821. If not, it must exit and return nil. If yes, it should return
  8822. a non-nil value after calling `org-store-link-props' with a list
  8823. of properties and values. Special properties are:
  8824. :type The link prefix, like \"http\". This must be given.
  8825. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8826. This is obligatory as well.
  8827. :description Optional default description for the second pair
  8828. of brackets in an Org mode link. The user can still change
  8829. this when inserting this link into an Org mode buffer.
  8830. In addition to these, any additional properties can be specified
  8831. and then used in capture templates."
  8832. (cl-loop for link in org-link-parameters
  8833. with store-func
  8834. do (setq store-func (org-link-get-parameter (car link) :store))
  8835. if store-func
  8836. collect store-func))
  8837. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8838. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8839. ;;;###autoload
  8840. (defun org-store-link (arg)
  8841. "Store an org-link to the current location.
  8842. \\<org-mode-map>
  8843. This link is added to `org-stored-links' and can later be inserted
  8844. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8845. For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
  8846. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8847. For file links, ARG negates `org-context-in-file-links'.
  8848. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8849. skipping storing functions that are not
  8850. part of Org core.
  8851. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8852. prefix ARG forces storing a link for each line in the
  8853. active region."
  8854. (interactive "P")
  8855. (org-load-modules-maybe)
  8856. (if (and (equal arg '(64)) (org-region-active-p))
  8857. (save-excursion
  8858. (let ((end (region-end)))
  8859. (goto-char (region-beginning))
  8860. (set-mark (point))
  8861. (while (< (point-at-eol) end)
  8862. (move-end-of-line 1) (activate-mark)
  8863. (let (current-prefix-arg)
  8864. (call-interactively 'org-store-link))
  8865. (move-beginning-of-line 2)
  8866. (set-mark (point)))))
  8867. (setq org-store-link-plist nil)
  8868. (let (link cpltxt desc description search
  8869. txt custom-id agenda-link sfuns sfunsn)
  8870. (cond
  8871. ;; Store a link using an external link type
  8872. ((and (not (equal arg '(16)))
  8873. (setq sfuns
  8874. (delq
  8875. nil (mapcar (lambda (f)
  8876. (let (fs) (if (funcall f) (push f fs))))
  8877. (org-store-link-functions)))
  8878. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8879. (or (and (cdr sfuns)
  8880. (funcall (intern
  8881. (completing-read
  8882. "Which function for creating the link? "
  8883. sfunsn nil t (car sfunsn)))))
  8884. (funcall (caar sfuns)))
  8885. (setq link (plist-get org-store-link-plist :link)
  8886. desc (or (plist-get org-store-link-plist
  8887. :description)
  8888. link))))
  8889. ;; Store a link from a source code buffer.
  8890. ((org-src-edit-buffer-p)
  8891. (let ((coderef-format (org-src-coderef-format)))
  8892. (cond ((save-excursion
  8893. (beginning-of-line)
  8894. (looking-at (org-src-coderef-regexp coderef-format)))
  8895. (setq link (format "(%s)" (match-string-no-properties 3))))
  8896. ((called-interactively-p 'any)
  8897. (let ((label (read-string "Code line label: ")))
  8898. (end-of-line)
  8899. (setq link (format coderef-format label))
  8900. (let ((gc (- 79 (length link))))
  8901. (if (< (current-column) gc)
  8902. (org-move-to-column gc t)
  8903. (insert " ")))
  8904. (insert link)
  8905. (setq link (concat "(" label ")"))
  8906. (setq desc nil)))
  8907. (t (setq link nil)))))
  8908. ;; We are in the agenda, link to referenced location
  8909. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8910. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8911. (get-text-property (point) 'org-marker))))
  8912. (when m
  8913. (org-with-point-at m
  8914. (setq agenda-link
  8915. (if (called-interactively-p 'any)
  8916. (call-interactively 'org-store-link)
  8917. (org-store-link nil)))))))
  8918. ((eq major-mode 'calendar-mode)
  8919. (let ((cd (calendar-cursor-to-date)))
  8920. (setq link
  8921. (format-time-string
  8922. (car org-time-stamp-formats)
  8923. (apply 'encode-time
  8924. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8925. nil nil nil))))
  8926. (org-store-link-props :type "calendar" :date cd)))
  8927. ((eq major-mode 'help-mode)
  8928. (setq link (concat "help:" (save-excursion
  8929. (goto-char (point-min))
  8930. (looking-at "^[^ ]+")
  8931. (match-string 0))))
  8932. (org-store-link-props :type "help"))
  8933. ((eq major-mode 'w3-mode)
  8934. (setq cpltxt (if (and (buffer-name)
  8935. (not (string-match "Untitled" (buffer-name))))
  8936. (buffer-name)
  8937. (url-view-url t))
  8938. link (url-view-url t))
  8939. (org-store-link-props :type "w3" :url (url-view-url t)))
  8940. ((eq major-mode 'image-mode)
  8941. (setq cpltxt (concat "file:"
  8942. (abbreviate-file-name buffer-file-name))
  8943. link cpltxt)
  8944. (org-store-link-props :type "image" :file buffer-file-name))
  8945. ;; In dired, store a link to the file of the current line
  8946. ((derived-mode-p 'dired-mode)
  8947. (let ((file (dired-get-filename nil t)))
  8948. (setq file (if file
  8949. (abbreviate-file-name
  8950. (expand-file-name (dired-get-filename nil t)))
  8951. ;; otherwise, no file so use current directory.
  8952. default-directory))
  8953. (setq cpltxt (concat "file:" file)
  8954. link cpltxt)))
  8955. ((setq search (run-hook-with-args-until-success
  8956. 'org-create-file-search-functions))
  8957. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8958. "::" search))
  8959. (setq cpltxt (or description link)))
  8960. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8961. (org-with-limited-levels
  8962. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8963. (cond
  8964. ;; Store a link using the target at point
  8965. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8966. (setq cpltxt
  8967. (concat "file:"
  8968. (abbreviate-file-name
  8969. (buffer-file-name (buffer-base-buffer)))
  8970. "::" (match-string 1))
  8971. link cpltxt))
  8972. ((and (featurep 'org-id)
  8973. (or (eq org-id-link-to-org-use-id t)
  8974. (and (called-interactively-p 'any)
  8975. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8976. (and (eq org-id-link-to-org-use-id
  8977. 'create-if-interactive-and-no-custom-id)
  8978. (not custom-id))))
  8979. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8980. ;; Store a link using the ID at point
  8981. (setq link (condition-case nil
  8982. (prog1 (org-id-store-link)
  8983. (setq desc (or (plist-get org-store-link-plist
  8984. :description)
  8985. "")))
  8986. (error
  8987. ;; Probably before first headline, link only to file
  8988. (concat "file:"
  8989. (abbreviate-file-name
  8990. (buffer-file-name (buffer-base-buffer))))))))
  8991. (t
  8992. ;; Just link to current headline
  8993. (setq cpltxt (concat "file:"
  8994. (abbreviate-file-name
  8995. (buffer-file-name (buffer-base-buffer)))))
  8996. ;; Add a context search string
  8997. (when (org-xor org-context-in-file-links arg)
  8998. (let* ((element (org-element-at-point))
  8999. (name (org-element-property :name element)))
  9000. (setq txt (cond
  9001. ((org-at-heading-p) nil)
  9002. (name)
  9003. ((org-region-active-p)
  9004. (buffer-substring (region-beginning) (region-end)))))
  9005. (when (or (null txt) (string-match "\\S-" txt))
  9006. (setq cpltxt
  9007. (concat cpltxt "::"
  9008. (condition-case nil
  9009. (org-make-org-heading-search-string txt)
  9010. (error "")))
  9011. desc (or name
  9012. (nth 4 (ignore-errors (org-heading-components)))
  9013. "NONE")))))
  9014. (when (string-match "::\\'" cpltxt)
  9015. (setq cpltxt (substring cpltxt 0 -2)))
  9016. (setq link cpltxt)))))
  9017. ((buffer-file-name (buffer-base-buffer))
  9018. ;; Just link to this file here.
  9019. (setq cpltxt (concat "file:"
  9020. (abbreviate-file-name
  9021. (buffer-file-name (buffer-base-buffer)))))
  9022. ;; Add a context string.
  9023. (when (org-xor org-context-in-file-links arg)
  9024. (setq txt (if (org-region-active-p)
  9025. (buffer-substring (region-beginning) (region-end))
  9026. (buffer-substring (point-at-bol) (point-at-eol))))
  9027. ;; Only use search option if there is some text.
  9028. (when (string-match "\\S-" txt)
  9029. (setq cpltxt
  9030. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  9031. desc "NONE")))
  9032. (setq link cpltxt))
  9033. ((called-interactively-p 'interactive)
  9034. (user-error "No method for storing a link from this buffer"))
  9035. (t (setq link nil)))
  9036. ;; We're done setting link and desc, clean up
  9037. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9038. (setq link (or link cpltxt)
  9039. desc (or desc cpltxt))
  9040. (cond ((not desc))
  9041. ((equal desc "NONE") (setq desc nil))
  9042. (t (setq desc
  9043. (replace-regexp-in-string
  9044. org-bracket-link-analytic-regexp
  9045. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9046. desc))))
  9047. ;; Return the link
  9048. (if (not (and (or (called-interactively-p 'any)
  9049. executing-kbd-macro)
  9050. link))
  9051. (or agenda-link (and link (org-make-link-string link desc)))
  9052. (push (list link desc) org-stored-links)
  9053. (message "Stored: %s" (or desc link))
  9054. (when custom-id
  9055. (setq link (concat "file:" (abbreviate-file-name
  9056. (buffer-file-name)) "::#" custom-id))
  9057. (push (list link desc) org-stored-links))
  9058. (car org-stored-links)))))
  9059. (defun org-store-link-props (&rest plist)
  9060. "Store link properties, extract names, addresses and dates."
  9061. (let ((x (plist-get plist :from)))
  9062. (when x
  9063. (let ((adr (mail-extract-address-components x)))
  9064. (setq plist (plist-put plist :fromname (car adr)))
  9065. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9066. (let ((x (plist-get plist :to)))
  9067. (when x
  9068. (let ((adr (mail-extract-address-components x)))
  9069. (setq plist (plist-put plist :toname (car adr)))
  9070. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9071. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9072. (when x
  9073. (setq plist (plist-put plist :date-timestamp
  9074. (format-time-string
  9075. (org-time-stamp-format t) x)))
  9076. (setq plist (plist-put plist :date-timestamp-inactive
  9077. (format-time-string
  9078. (org-time-stamp-format t t) x)))))
  9079. (let ((from (plist-get plist :from))
  9080. (to (plist-get plist :to)))
  9081. (when (and from to org-from-is-user-regexp)
  9082. (setq plist
  9083. (plist-put plist :fromto
  9084. (if (string-match org-from-is-user-regexp from)
  9085. (concat "to %t")
  9086. (concat "from %f"))))))
  9087. (setq org-store-link-plist plist))
  9088. (defun org-add-link-props (&rest plist)
  9089. "Add these properties to the link property list."
  9090. (let (key value)
  9091. (while plist
  9092. (setq key (pop plist) value (pop plist))
  9093. (setq org-store-link-plist
  9094. (plist-put org-store-link-plist key value)))))
  9095. (defun org-email-link-description (&optional fmt)
  9096. "Return the description part of an email link.
  9097. This takes information from `org-store-link-plist' and formats it
  9098. according to FMT (default from `org-email-link-description-format')."
  9099. (setq fmt (or fmt org-email-link-description-format))
  9100. (let* ((p org-store-link-plist)
  9101. (to (plist-get p :toaddress))
  9102. (from (plist-get p :fromaddress))
  9103. (table
  9104. (list
  9105. (cons "%c" (plist-get p :fromto))
  9106. (cons "%F" (plist-get p :from))
  9107. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9108. (cons "%T" (plist-get p :to))
  9109. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9110. (cons "%s" (plist-get p :subject))
  9111. (cons "%d" (plist-get p :date))
  9112. (cons "%m" (plist-get p :message-id)))))
  9113. (when (string-match "%c" fmt)
  9114. ;; Check if the user wrote this message
  9115. (if (and org-from-is-user-regexp from to
  9116. (save-match-data (string-match org-from-is-user-regexp from)))
  9117. (setq fmt (replace-match "to %t" t t fmt))
  9118. (setq fmt (replace-match "from %f" t t fmt))))
  9119. (org-replace-escapes fmt table)))
  9120. (defun org-make-org-heading-search-string (&optional string)
  9121. "Make search string for the current headline or STRING."
  9122. (let ((s (or string
  9123. (and (derived-mode-p 'org-mode)
  9124. (save-excursion
  9125. (org-back-to-heading t)
  9126. (org-element-property :raw-value (org-element-at-point))))))
  9127. (lines org-context-in-file-links))
  9128. (or string (setq s (concat "*" s))) ; Add * for headlines
  9129. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9130. (when (and string (integerp lines) (> lines 0))
  9131. (let ((slines (org-split-string s "\n")))
  9132. (when (< lines (length slines))
  9133. (setq s (mapconcat
  9134. 'identity
  9135. (reverse (nthcdr (- (length slines) lines)
  9136. (reverse slines))) "\n")))))
  9137. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9138. (defun org-make-link-string (link &optional description)
  9139. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9140. (unless (org-string-nw-p link) (error "Empty link"))
  9141. (let ((uri (cond ((string-match org-link-types-re link)
  9142. (concat (match-string 1 link)
  9143. (org-link-escape (substring link (match-end 1)))))
  9144. ;; For readability, url-encode internal links only
  9145. ;; when absolutely needed (i.e, when they contain
  9146. ;; square brackets). File links however, are
  9147. ;; encoded since, e.g., spaces are significant.
  9148. ((or (file-name-absolute-p link)
  9149. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9150. (org-link-escape link))
  9151. (t link)))
  9152. (description
  9153. (and (org-string-nw-p description)
  9154. ;; Remove brackets from description, as they are fatal.
  9155. (replace-regexp-in-string
  9156. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9157. (org-trim description)))))
  9158. (format "[[%s]%s]"
  9159. uri
  9160. (if description (format "[%s]" description) ""))))
  9161. (defconst org-link-escape-chars
  9162. ;;%20 %5B %5D %25
  9163. '(?\s ?\[ ?\] ?%)
  9164. "List of characters that should be escaped in a link when stored to Org.
  9165. This is the list that is used for internal purposes.")
  9166. (defun org-link-escape (text &optional table merge)
  9167. "Return percent escaped representation of TEXT.
  9168. TEXT is a string with the text to escape.
  9169. Optional argument TABLE is a list with characters that should be
  9170. escaped. When nil, `org-link-escape-chars' is used.
  9171. If optional argument MERGE is set, merge TABLE into
  9172. `org-link-escape-chars'."
  9173. (let ((characters-to-encode
  9174. (cond ((null table) org-link-escape-chars)
  9175. (merge (append org-link-escape-chars table))
  9176. (t table))))
  9177. (mapconcat
  9178. (lambda (c)
  9179. (if (or (memq c characters-to-encode)
  9180. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9181. (mapconcat (lambda (e) (format "%%%.2X" e))
  9182. (or (encode-coding-char c 'utf-8)
  9183. (error "Unable to percent escape character: %c" c))
  9184. "")
  9185. (char-to-string c)))
  9186. text "")))
  9187. (defun org-link-unescape (str)
  9188. "Unhex hexified Unicode parts in string STR.
  9189. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9190. reciprocal of `org-link-escape', which see."
  9191. (if (org-string-nw-p str)
  9192. (replace-regexp-in-string
  9193. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9194. str))
  9195. (defun org-link-unescape-compound (hex)
  9196. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9197. Note: this function also decodes single byte encodings like
  9198. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9199. (save-match-data
  9200. (let* ((bytes (cdr (split-string hex "%")))
  9201. (ret "")
  9202. (eat 0)
  9203. (sum 0))
  9204. (while bytes
  9205. (let* ((val (string-to-number (pop bytes) 16))
  9206. (shift-xor
  9207. (if (= 0 eat)
  9208. (cond
  9209. ((>= val 252) (cons 6 252))
  9210. ((>= val 248) (cons 5 248))
  9211. ((>= val 240) (cons 4 240))
  9212. ((>= val 224) (cons 3 224))
  9213. ((>= val 192) (cons 2 192))
  9214. (t (cons 0 0)))
  9215. (cons 6 128))))
  9216. (when (>= val 192) (setq eat (car shift-xor)))
  9217. (setq val (logxor val (cdr shift-xor)))
  9218. (setq sum (+ (lsh sum (car shift-xor)) val))
  9219. (when (> eat 0) (setq eat (- eat 1)))
  9220. (cond
  9221. ((= 0 eat) ;multi byte
  9222. (setq ret (concat ret (char-to-string sum)))
  9223. (setq sum 0))
  9224. ((not bytes) ; single byte(s)
  9225. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9226. ret)))
  9227. (defun org-link-unescape-single-byte-sequence (hex)
  9228. "Unhexify hex-encoded single byte character sequences."
  9229. (mapconcat (lambda (byte)
  9230. (char-to-string (string-to-number byte 16)))
  9231. (cdr (split-string hex "%")) ""))
  9232. (defun org-xor (a b)
  9233. "Exclusive or."
  9234. (if a (not b) b))
  9235. (defun org-fixup-message-id-for-http (s)
  9236. "Replace special characters in a message id, so it can be used in an http query."
  9237. (when (string-match "%" s)
  9238. (setq s (mapconcat (lambda (c)
  9239. (if (eq c ?%)
  9240. "%25"
  9241. (char-to-string c)))
  9242. s "")))
  9243. (while (string-match "<" s)
  9244. (setq s (replace-match "%3C" t t s)))
  9245. (while (string-match ">" s)
  9246. (setq s (replace-match "%3E" t t s)))
  9247. (while (string-match "@" s)
  9248. (setq s (replace-match "%40" t t s)))
  9249. s)
  9250. (defun org-link-prettify (link)
  9251. "Return a human-readable representation of LINK.
  9252. The car of LINK must be a raw link.
  9253. The cdr of LINK must be either a link description or nil."
  9254. (let ((desc (or (cadr link) "<no description>")))
  9255. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9256. "<" (car link) ">")))
  9257. ;;;###autoload
  9258. (defun org-insert-link-global ()
  9259. "Insert a link like Org mode does.
  9260. This command can be called in any mode to insert a link in Org syntax."
  9261. (interactive)
  9262. (org-load-modules-maybe)
  9263. (org-run-like-in-org-mode 'org-insert-link))
  9264. (defun org-insert-all-links (arg &optional pre post)
  9265. "Insert all links in `org-stored-links'.
  9266. When a universal prefix, do not delete the links from `org-stored-links'.
  9267. When `ARG' is a number, insert the last N link(s).
  9268. `PRE' and `POST' are optional arguments to define a string to
  9269. prepend or to append."
  9270. (interactive "P")
  9271. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9272. (links (copy-sequence org-stored-links))
  9273. (pr (or pre "- "))
  9274. (po (or post "\n"))
  9275. (cnt 1) l)
  9276. (if (null org-stored-links)
  9277. (message "No link to insert")
  9278. (while (and (or (listp arg) (>= arg cnt))
  9279. (setq l (if (listp arg)
  9280. (pop links)
  9281. (pop org-stored-links))))
  9282. (setq cnt (1+ cnt))
  9283. (insert pr)
  9284. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9285. (insert po)))))
  9286. (defun org-insert-last-stored-link (arg)
  9287. "Insert the last link stored in `org-stored-links'."
  9288. (interactive "p")
  9289. (org-insert-all-links arg "" "\n"))
  9290. (defun org-link-fontify-links-to-this-file ()
  9291. "Fontify links to the current file in `org-stored-links'."
  9292. (let ((f (buffer-file-name)) a b)
  9293. (setq a (mapcar (lambda(l)
  9294. (let ((ll (car l)))
  9295. (when (and (string-match "^file:\\(.+\\)::" ll)
  9296. (equal f (expand-file-name (match-string 1 ll))))
  9297. ll)))
  9298. org-stored-links))
  9299. (when (featurep 'org-id)
  9300. (setq b (mapcar (lambda(l)
  9301. (let ((ll (car l)))
  9302. (when (and (string-match "^id:\\(.+\\)$" ll)
  9303. (equal f (expand-file-name
  9304. (or (org-id-find-id-file
  9305. (match-string 1 ll)) ""))))
  9306. ll)))
  9307. org-stored-links)))
  9308. (mapcar (lambda(l)
  9309. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9310. (delq nil (append a b)))))
  9311. (defvar org--links-history nil)
  9312. (defun org-insert-link (&optional complete-file link-location default-description)
  9313. "Insert a link. At the prompt, enter the link.
  9314. Completion can be used to insert any of the link protocol prefixes in use.
  9315. The history can be used to select a link previously stored with
  9316. `org-store-link'. When the empty string is entered (i.e. if you just
  9317. press `RET' at the prompt), the link defaults to the most recently
  9318. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9319. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9320. You will also be prompted for a description, and if one is given, it will
  9321. be displayed in the buffer instead of the link.
  9322. If there is already a link at point, this command will allow you to edit
  9323. link and description parts.
  9324. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9325. file name can be
  9326. selected using completion. The path to the file will be relative to the
  9327. current directory if the file is in the current directory or a subdirectory.
  9328. Otherwise, the link will be the absolute path as completed in the minibuffer
  9329. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9330. option `org-link-file-path-type'.
  9331. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9332. absolute path even if the file is in
  9333. the current directory or below.
  9334. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9335. prefix negates `org-keep-stored-link-after-insertion'.
  9336. If `org-make-link-description-function' is non-nil, this function will be
  9337. called with the link target, and the result will be the default
  9338. link description.
  9339. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9340. the link location instead of reading one interactively.
  9341. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9342. as the default description."
  9343. (interactive "P")
  9344. (let* ((wcf (current-window-configuration))
  9345. (origbuf (current-buffer))
  9346. (region (when (org-region-active-p)
  9347. (buffer-substring (region-beginning) (region-end))))
  9348. (remove (and region (list (region-beginning) (region-end))))
  9349. (desc region)
  9350. (link link-location)
  9351. (abbrevs org-link-abbrev-alist-local)
  9352. entry all-prefixes auto-desc)
  9353. (cond
  9354. (link-location) ; specified by arg, just use it.
  9355. ((org-in-regexp org-bracket-link-regexp 1)
  9356. ;; We do have a link at point, and we are going to edit it.
  9357. (setq remove (list (match-beginning 0) (match-end 0)))
  9358. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9359. (setq link (read-string "Link: "
  9360. (org-link-unescape
  9361. (match-string-no-properties 1)))))
  9362. ((or (org-in-regexp org-angle-link-re)
  9363. (org-in-regexp org-plain-link-re))
  9364. ;; Convert to bracket link
  9365. (setq remove (list (match-beginning 0) (match-end 0))
  9366. link (read-string "Link: "
  9367. (org-unbracket-string "<" ">" (match-string 0)))))
  9368. ((member complete-file '((4) (16)))
  9369. ;; Completing read for file names.
  9370. (setq link (org-file-complete-link complete-file)))
  9371. (t
  9372. ;; Read link, with completion for stored links.
  9373. (org-link-fontify-links-to-this-file)
  9374. (org-switch-to-buffer-other-window "*Org Links*")
  9375. (with-current-buffer "*Org Links*"
  9376. (erase-buffer)
  9377. (insert "Insert a link.
  9378. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9379. (when org-stored-links
  9380. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9381. (insert (mapconcat 'org-link-prettify
  9382. (reverse org-stored-links) "\n")))
  9383. (goto-char (point-min)))
  9384. (let ((cw (selected-window)))
  9385. (select-window (get-buffer-window "*Org Links*" 'visible))
  9386. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9387. (unless (pos-visible-in-window-p (point-max))
  9388. (org-fit-window-to-buffer))
  9389. (and (window-live-p cw) (select-window cw)))
  9390. (setq all-prefixes (append (mapcar 'car abbrevs)
  9391. (mapcar 'car org-link-abbrev-alist)
  9392. (org-link-types)))
  9393. (unwind-protect
  9394. ;; Fake a link history, containing the stored links.
  9395. (let ((org--links-history
  9396. (append (mapcar #'car org-stored-links)
  9397. org-insert-link-history)))
  9398. (setq link
  9399. (org-completing-read
  9400. "Link: "
  9401. (append
  9402. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9403. (mapcar #'car org-stored-links))
  9404. nil nil nil
  9405. 'org--links-history
  9406. (caar org-stored-links)))
  9407. (unless (org-string-nw-p link) (user-error "No link selected"))
  9408. (dolist (l org-stored-links)
  9409. (when (equal link (cadr l))
  9410. (setq link (car l))
  9411. (setq auto-desc t)))
  9412. (when (or (member link all-prefixes)
  9413. (and (equal ":" (substring link -1))
  9414. (member (substring link 0 -1) all-prefixes)
  9415. (setq link (substring link 0 -1))))
  9416. (setq link (with-current-buffer origbuf
  9417. (org-link-try-special-completion link)))))
  9418. (set-window-configuration wcf)
  9419. (kill-buffer "*Org Links*"))
  9420. (setq entry (assoc link org-stored-links))
  9421. (or entry (push link org-insert-link-history))
  9422. (setq desc (or desc (nth 1 entry)))))
  9423. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9424. (not org-keep-stored-link-after-insertion))
  9425. (setq org-stored-links (delq (assoc link org-stored-links)
  9426. org-stored-links)))
  9427. (when (and (string-match org-plain-link-re link)
  9428. (not (string-match org-ts-regexp link)))
  9429. ;; URL-like link, normalize the use of angular brackets.
  9430. (setq link (org-unbracket-string "<" ">" link)))
  9431. ;; Check if we are linking to the current file with a search
  9432. ;; option If yes, simplify the link by using only the search
  9433. ;; option.
  9434. (when (and buffer-file-name
  9435. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9436. (let* ((path (match-string 1 link))
  9437. (case-fold-search nil)
  9438. (search (match-string 2 link)))
  9439. (save-match-data
  9440. (when (equal (file-truename buffer-file-name) (file-truename path))
  9441. ;; We are linking to this same file, with a search option
  9442. (setq link search)))))
  9443. ;; Check if we can/should use a relative path. If yes, simplify the link
  9444. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9445. (let* ((type (match-string 1 link))
  9446. (path (match-string 2 link))
  9447. (origpath path)
  9448. (case-fold-search nil))
  9449. (cond
  9450. ((or (eq org-link-file-path-type 'absolute)
  9451. (equal complete-file '(16)))
  9452. (setq path (abbreviate-file-name (expand-file-name path))))
  9453. ((eq org-link-file-path-type 'noabbrev)
  9454. (setq path (expand-file-name path)))
  9455. ((eq org-link-file-path-type 'relative)
  9456. (setq path (file-relative-name path)))
  9457. (t
  9458. (save-match-data
  9459. (if (string-match (concat "^" (regexp-quote
  9460. (expand-file-name
  9461. (file-name-as-directory
  9462. default-directory))))
  9463. (expand-file-name path))
  9464. ;; We are linking a file with relative path name.
  9465. (setq path (substring (expand-file-name path)
  9466. (match-end 0)))
  9467. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9468. (setq link (concat type path))
  9469. (when (equal desc origpath)
  9470. (setq desc path))))
  9471. (if org-make-link-description-function
  9472. (setq desc
  9473. (or (condition-case nil
  9474. (funcall org-make-link-description-function link desc)
  9475. (error (progn (message "Can't get link description from `%s'"
  9476. (symbol-name org-make-link-description-function))
  9477. (sit-for 2) nil)))
  9478. (read-string "Description: " default-description)))
  9479. (if default-description (setq desc default-description)
  9480. (setq desc (or (and auto-desc desc)
  9481. (read-string "Description: " desc)))))
  9482. (unless (string-match "\\S-" desc) (setq desc nil))
  9483. (when remove (apply 'delete-region remove))
  9484. (insert (org-make-link-string link desc))
  9485. ;; Redisplay so as the new link has proper invisible characters.
  9486. (sit-for 0)))
  9487. (defun org-link-try-special-completion (type)
  9488. "If there is completion support for link type TYPE, offer it."
  9489. (let ((fun (org-link-get-parameter type :complete)))
  9490. (if (functionp fun)
  9491. (funcall fun)
  9492. (read-string "Link (no completion support): " (concat type ":")))))
  9493. (defun org-file-complete-link (&optional arg)
  9494. "Create a file link using completion."
  9495. (let ((file (read-file-name "File: "))
  9496. (pwd (file-name-as-directory (expand-file-name ".")))
  9497. (pwd1 (file-name-as-directory (abbreviate-file-name
  9498. (expand-file-name ".")))))
  9499. (cond ((equal arg '(16))
  9500. (concat "file:"
  9501. (abbreviate-file-name (expand-file-name file))))
  9502. ((string-match
  9503. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9504. (concat "file:" (match-string 1 file)))
  9505. ((string-match
  9506. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9507. (expand-file-name file))
  9508. (concat "file:"
  9509. (match-string 1 (expand-file-name file))))
  9510. (t (concat "file:" file)))))
  9511. (defun org-completing-read (&rest args)
  9512. "Completing-read with SPACE being a normal character."
  9513. (let ((enable-recursive-minibuffers t)
  9514. (minibuffer-local-completion-map
  9515. (copy-keymap minibuffer-local-completion-map)))
  9516. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9517. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9518. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9519. 'org-time-stamp-inactive)
  9520. (apply #'completing-read args)))
  9521. ;;; Opening/following a link
  9522. (defvar org-link-search-failed nil)
  9523. (defvar org-open-link-functions nil
  9524. "Hook for functions finding a plain text link.
  9525. These functions must take a single argument, the link content.
  9526. They will be called for links that look like [[link text][description]]
  9527. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9528. like a filename (e.g. \"./blue.png\").
  9529. These functions will be called *before* Org attempts to resolve the
  9530. link by doing text searches in the current buffer - so if you want a
  9531. link \"[[target]]\" to still find \"<<target>>\", your function should
  9532. handle this as a special case.
  9533. When the function does handle the link, it must return a non-nil value.
  9534. If it decides that it is not responsible for this link, it must return
  9535. nil to indicate that that Org can continue with other options like
  9536. exact and fuzzy text search.")
  9537. (defun org-next-link (&optional search-backward)
  9538. "Move forward to the next link.
  9539. If the link is in hidden text, expose it."
  9540. (interactive "P")
  9541. (when (and org-link-search-failed (eq this-command last-command))
  9542. (goto-char (point-min))
  9543. (message "Link search wrapped back to beginning of buffer"))
  9544. (setq org-link-search-failed nil)
  9545. (let* ((pos (point))
  9546. (ct (org-context))
  9547. (a (assq :link ct))
  9548. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9549. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9550. ((looking-at org-any-link-re)
  9551. ;; Don't stay stuck at link without an org-link face
  9552. (forward-char (if search-backward -1 1))))
  9553. (if (funcall srch-fun org-any-link-re nil t)
  9554. (progn
  9555. (goto-char (match-beginning 0))
  9556. (when (outline-invisible-p) (org-show-context)))
  9557. (goto-char pos)
  9558. (setq org-link-search-failed t)
  9559. (message "No further link found"))))
  9560. (defun org-previous-link ()
  9561. "Move backward to the previous link.
  9562. If the link is in hidden text, expose it."
  9563. (interactive)
  9564. (funcall 'org-next-link t))
  9565. (defun org-translate-link (s)
  9566. "Translate a link string if a translation function has been defined."
  9567. (with-temp-buffer
  9568. (insert (org-trim s))
  9569. (org-trim (org-element-interpret-data (org-element-context)))))
  9570. (defun org-translate-link-from-planner (type path)
  9571. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9572. This is still an experimental function, your mileage may vary."
  9573. (cond
  9574. ((member type '("http" "https" "news" "ftp"))
  9575. ;; standard Internet links are the same.
  9576. nil)
  9577. ((and (equal type "irc") (string-match "^//" path))
  9578. ;; Planner has two / at the beginning of an irc link, we have 1.
  9579. ;; We should have zero, actually....
  9580. (setq path (substring path 1)))
  9581. ((and (equal type "lisp") (string-match "^/" path))
  9582. ;; Planner has a slash, we do not.
  9583. (setq type "elisp" path (substring path 1)))
  9584. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9585. ;; A typical message link. Planner has the id after the final slash,
  9586. ;; we separate it with a hash mark
  9587. (setq path (concat (match-string 1 path) "#"
  9588. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9589. (cons type path))
  9590. (defun org-find-file-at-mouse (ev)
  9591. "Open file link or URL at mouse."
  9592. (interactive "e")
  9593. (mouse-set-point ev)
  9594. (org-open-at-point 'in-emacs))
  9595. (defun org-open-at-mouse (ev)
  9596. "Open file link or URL at mouse.
  9597. See the docstring of `org-open-file' for details."
  9598. (interactive "e")
  9599. (mouse-set-point ev)
  9600. (when (eq major-mode 'org-agenda-mode)
  9601. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9602. (org-open-at-point))
  9603. (defvar org-window-config-before-follow-link nil
  9604. "The window configuration before following a link.
  9605. This is saved in case the need arises to restore it.")
  9606. ;;;###autoload
  9607. (defun org-open-at-point-global ()
  9608. "Follow a link or time-stamp like Org mode does.
  9609. This command can be called in any mode to follow an external link
  9610. or a time-stamp that has Org mode syntax. Its behavior is
  9611. undefined when called on internal links (e.g., fuzzy links).
  9612. Raise an error when there is nothing to follow. "
  9613. (interactive)
  9614. (cond ((org-in-regexp org-any-link-re)
  9615. (org-open-link-from-string (match-string-no-properties 0)))
  9616. ((or (org-in-regexp org-ts-regexp-both nil t)
  9617. (org-in-regexp org-tsr-regexp-both nil t))
  9618. (org-follow-timestamp-link))
  9619. (t (user-error "No link found"))))
  9620. ;;;###autoload
  9621. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9622. "Open a link in the string S, as if it was in Org mode."
  9623. (interactive "sLink: \nP")
  9624. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9625. (with-temp-buffer
  9626. (let ((org-inhibit-startup (not reference-buffer)))
  9627. (org-mode)
  9628. (insert s)
  9629. (goto-char (point-min))
  9630. (when reference-buffer
  9631. (setq org-link-abbrev-alist-local
  9632. (with-current-buffer reference-buffer
  9633. org-link-abbrev-alist-local)))
  9634. (org-open-at-point arg reference-buffer)))))
  9635. (defvar org-open-at-point-functions nil
  9636. "Hook that is run when following a link at point.
  9637. Functions in this hook must return t if they identify and follow
  9638. a link at point. If they don't find anything interesting at point,
  9639. they must return nil.")
  9640. (defvar org-link-search-inhibit-query nil)
  9641. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9642. (defun org--open-doi-link (path)
  9643. "Open a \"doi\" type link.
  9644. PATH is a the path to search for, as a string."
  9645. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9646. (defun org--open-elisp-link (path)
  9647. "Open a \"elisp\" type link.
  9648. PATH is the sexp to evaluate, as a string."
  9649. (let ((cmd path))
  9650. (if (or (and (org-string-nw-p
  9651. org-confirm-elisp-link-not-regexp)
  9652. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9653. (not org-confirm-elisp-link-function)
  9654. (funcall org-confirm-elisp-link-function
  9655. (format "Execute \"%s\" as elisp? "
  9656. (org-add-props cmd nil 'face 'org-warning))))
  9657. (message "%s => %s" cmd
  9658. (if (eq (string-to-char cmd) ?\()
  9659. (eval (read cmd))
  9660. (call-interactively (read cmd))))
  9661. (user-error "Abort"))))
  9662. (defun org--open-help-link (path)
  9663. "Open a \"help\" type link.
  9664. PATH is a symbol name, as a string."
  9665. (pcase (intern path)
  9666. ((and (pred fboundp) variable) (describe-function variable))
  9667. ((and (pred boundp) function) (describe-variable function))
  9668. (name (user-error "Unknown function or variable: %s" name))))
  9669. (defun org--open-shell-link (path)
  9670. "Open a \"shell\" type link.
  9671. PATH is the command to execute, as a string."
  9672. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9673. (cmd path))
  9674. (if (or (and (org-string-nw-p
  9675. org-confirm-shell-link-not-regexp)
  9676. (string-match
  9677. org-confirm-shell-link-not-regexp cmd))
  9678. (not org-confirm-shell-link-function)
  9679. (funcall org-confirm-shell-link-function
  9680. (format "Execute \"%s\" in shell? "
  9681. (org-add-props cmd nil
  9682. 'face 'org-warning))))
  9683. (progn
  9684. (message "Executing %s" cmd)
  9685. (shell-command cmd buf)
  9686. (when (featurep 'midnight)
  9687. (setq clean-buffer-list-kill-buffer-names
  9688. (cons (buffer-name buf)
  9689. clean-buffer-list-kill-buffer-names))))
  9690. (user-error "Abort"))))
  9691. (defun org-open-at-point (&optional arg reference-buffer)
  9692. "Open link, timestamp, footnote or tags at point.
  9693. When point is on a link, follow it. Normally, files will be
  9694. opened by an appropriate application. If the optional prefix
  9695. argument ARG is non-nil, Emacs will visit the file. With
  9696. a double prefix argument, try to open outside of Emacs, in the
  9697. application the system uses for this file type.
  9698. When point is on a timestamp, open the agenda at the day
  9699. specified.
  9700. When point is a footnote definition, move to the first reference
  9701. found. If it is on a reference, move to the associated
  9702. definition.
  9703. When point is on a headline, display a list of every link in the
  9704. entry, so it is possible to pick one, or all, of them. If point
  9705. is on a tag, call `org-tags-view' instead.
  9706. When optional argument REFERENCE-BUFFER is non-nil, it should
  9707. specify a buffer from where the link search should happen. This
  9708. is used internally by `org-open-link-from-string'.
  9709. On top of syntactically correct links, this function will open
  9710. the link at point in comments or comment blocks and the first
  9711. link in a property drawer line."
  9712. (interactive "P")
  9713. ;; On a code block, open block's results.
  9714. (unless (call-interactively 'org-babel-open-src-block-result)
  9715. (org-load-modules-maybe)
  9716. (setq org-window-config-before-follow-link (current-window-configuration))
  9717. (org-remove-occur-highlights nil nil t)
  9718. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9719. (let* ((context
  9720. ;; Only consider supported types, even if they are not
  9721. ;; the closest one.
  9722. (org-element-lineage
  9723. (org-element-context)
  9724. '(clock comment comment-block footnote-definition
  9725. footnote-reference headline inlinetask keyword link
  9726. node-property timestamp)
  9727. t))
  9728. (type (org-element-type context))
  9729. (value (org-element-property :value context)))
  9730. (cond
  9731. ((not context) (user-error "No link found"))
  9732. ;; Exception: open timestamps and links in properties
  9733. ;; drawers, keywords and comments.
  9734. ((memq type '(comment comment-block keyword node-property))
  9735. (call-interactively #'org-open-at-point-global))
  9736. ;; On a headline or an inlinetask, but not on a timestamp,
  9737. ;; a link, a footnote reference or on tags.
  9738. ((and (memq type '(headline inlinetask))
  9739. ;; Not on tags.
  9740. (let ((case-fold-search nil))
  9741. (save-excursion
  9742. (beginning-of-line)
  9743. (looking-at org-complex-heading-regexp))
  9744. (or (not (match-beginning 5))
  9745. (< (point) (match-beginning 5)))))
  9746. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9747. (links (car data))
  9748. (links-end (cdr data)))
  9749. (if links
  9750. (dolist (link (if (stringp links) (list links) links))
  9751. (search-forward link nil links-end)
  9752. (goto-char (match-beginning 0))
  9753. (org-open-at-point))
  9754. (require 'org-attach)
  9755. (org-attach-reveal 'if-exists))))
  9756. ;; On a clock line, make sure point is on the timestamp
  9757. ;; before opening it.
  9758. ((and (eq type 'clock)
  9759. value
  9760. (>= (point) (org-element-property :begin value))
  9761. (<= (point) (org-element-property :end value)))
  9762. (org-follow-timestamp-link))
  9763. ;; Do nothing on white spaces after an object.
  9764. ((>= (point)
  9765. (save-excursion
  9766. (goto-char (org-element-property :end context))
  9767. (skip-chars-backward " \t")
  9768. (point)))
  9769. (user-error "No link found"))
  9770. ((eq type 'timestamp) (org-follow-timestamp-link))
  9771. ;; On tags within a headline or an inlinetask.
  9772. ((and (memq type '(headline inlinetask))
  9773. (let ((case-fold-search nil))
  9774. (save-excursion (beginning-of-line)
  9775. (looking-at org-complex-heading-regexp))
  9776. (and (match-beginning 5)
  9777. (>= (point) (match-beginning 5)))))
  9778. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9779. ((eq type 'link)
  9780. ;; When link is located within the description of another
  9781. ;; link (e.g., an inline image), always open the parent
  9782. ;; link.
  9783. (let* ((link (let ((up (org-element-property :parent context)))
  9784. (if (eq (org-element-type up) 'link) up context)))
  9785. (type (org-element-property :type link))
  9786. (path (org-link-unescape (org-element-property :path link))))
  9787. ;; Switch back to REFERENCE-BUFFER needed when called in
  9788. ;; a temporary buffer through `org-open-link-from-string'.
  9789. (with-current-buffer (or reference-buffer (current-buffer))
  9790. (cond
  9791. ((equal type "file")
  9792. (if (string-match "[*?{]" (file-name-nondirectory path))
  9793. (dired path)
  9794. ;; Look into `org-link-parameters' in order to find
  9795. ;; a DEDICATED-FUNCTION to open file. The function
  9796. ;; will be applied on raw link instead of parsed
  9797. ;; link due to the limitation in `org-add-link-type'
  9798. ;; ("open" function called with a single argument).
  9799. ;; If no such function is found, fallback to
  9800. ;; `org-open-file'.
  9801. (let* ((option (org-element-property :search-option link))
  9802. (app (org-element-property :application link))
  9803. (dedicated-function
  9804. (org-link-get-parameter
  9805. (if app (concat type "+" app) type)
  9806. :follow)))
  9807. (if dedicated-function
  9808. (funcall dedicated-function
  9809. (concat path
  9810. (and option (concat "::" option))))
  9811. (apply #'org-open-file
  9812. path
  9813. (cond (arg)
  9814. ((equal app "emacs") 'emacs)
  9815. ((equal app "sys") 'system))
  9816. (cond ((not option) nil)
  9817. ((string-match-p "\\`[0-9]+\\'" option)
  9818. (list (string-to-number option)))
  9819. (t (list nil
  9820. (org-link-unescape option)))))))))
  9821. ((functionp (org-link-get-parameter type :follow))
  9822. (funcall (org-link-get-parameter type :follow) path))
  9823. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9824. (unless (run-hook-with-args-until-success
  9825. 'org-open-link-functions path)
  9826. (if (not arg) (org-mark-ring-push)
  9827. (switch-to-buffer-other-window
  9828. (org-get-buffer-for-internal-link (current-buffer))))
  9829. (let ((destination
  9830. (org-with-wide-buffer
  9831. (if (equal type "radio")
  9832. (org-search-radio-target
  9833. (org-element-property :path link))
  9834. (org-link-search
  9835. (if (member type '("custom-id" "coderef"))
  9836. (org-element-property :raw-link link)
  9837. path)
  9838. ;; Prevent fuzzy links from matching
  9839. ;; themselves.
  9840. (and (equal type "fuzzy")
  9841. (+ 2 (org-element-property :begin link)))))
  9842. (point))))
  9843. (unless (and (<= (point-min) destination)
  9844. (>= (point-max) destination))
  9845. (widen))
  9846. (goto-char destination))))
  9847. (t (browse-url-at-point))))))
  9848. ;; On a footnote reference or at a footnote definition's label.
  9849. ((or (eq type 'footnote-reference)
  9850. (and (eq type 'footnote-definition)
  9851. (save-excursion
  9852. ;; Do not validate action when point is on the
  9853. ;; spaces right after the footnote label, in
  9854. ;; order to be on par with behaviour on links.
  9855. (skip-chars-forward " \t")
  9856. (let ((begin
  9857. (org-element-property :contents-begin context)))
  9858. (if begin (< (point) begin)
  9859. (= (org-element-property :post-affiliated context)
  9860. (line-beginning-position)))))))
  9861. (org-footnote-action))
  9862. (t (user-error "No link found")))))
  9863. (run-hook-with-args 'org-follow-link-hook)))
  9864. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9865. "Offer links in the current entry and return the selected link.
  9866. If there is only one link, return it.
  9867. If NTH is an integer, return the NTH link found.
  9868. If ZERO is a string, check also this string for a link, and if
  9869. there is one, return it."
  9870. (with-current-buffer buffer
  9871. (org-with-wide-buffer
  9872. (goto-char marker)
  9873. (let ((cnt ?0)
  9874. have-zero end links link c)
  9875. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9876. (push (match-string 0 zero) links)
  9877. (setq cnt (1- cnt) have-zero t))
  9878. (save-excursion
  9879. (org-back-to-heading t)
  9880. (setq end (save-excursion (outline-next-heading) (point)))
  9881. (while (re-search-forward org-any-link-re end t)
  9882. (push (match-string 0) links))
  9883. (setq links (org-uniquify (reverse links))))
  9884. (cond
  9885. ((null links)
  9886. (message "No links"))
  9887. ((equal (length links) 1)
  9888. (setq link (car links)))
  9889. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9890. (setq link (nth (if have-zero nth (1- nth)) links)))
  9891. (t ; we have to select a link
  9892. (save-excursion
  9893. (save-window-excursion
  9894. (delete-other-windows)
  9895. (with-output-to-temp-buffer "*Select Link*"
  9896. (dolist (l links)
  9897. (cond
  9898. ((not (string-match org-bracket-link-regexp l))
  9899. (princ (format "[%c] %s\n" (cl-incf cnt)
  9900. (org-unbracket-string "<" ">" l))))
  9901. ((match-end 3)
  9902. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9903. (match-string 3 l) (match-string 1 l))))
  9904. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9905. (match-string 1 l)))))))
  9906. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9907. (message "Select link to open, RET to open all:")
  9908. (setq c (read-char-exclusive))
  9909. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9910. (when (equal c ?q) (user-error "Abort"))
  9911. (if (equal c ?\C-m)
  9912. (setq link links)
  9913. (setq nth (- c ?0))
  9914. (when have-zero (setq nth (1+ nth)))
  9915. (unless (and (integerp nth) (>= (length links) nth))
  9916. (user-error "Invalid link selection"))
  9917. (setq link (nth (1- nth) links)))))
  9918. (cons link end)))))
  9919. ;; TODO: These functions are deprecated since `org-open-at-point'
  9920. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9921. (defun org-open-file-with-system (path)
  9922. "Open file at PATH using the system way of opening it."
  9923. (org-open-file path 'system))
  9924. (defun org-open-file-with-emacs (path)
  9925. "Open file at PATH in Emacs."
  9926. (org-open-file path 'emacs))
  9927. ;;; File search
  9928. (defvar org-create-file-search-functions nil
  9929. "List of functions to construct the right search string for a file link.
  9930. These functions are called in turn with point at the location to
  9931. which the link should point.
  9932. A function in the hook should first test if it would like to
  9933. handle this file type, for example by checking the `major-mode'
  9934. or the file extension. If it decides not to handle this file, it
  9935. should just return nil to give other functions a chance. If it
  9936. does handle the file, it must return the search string to be used
  9937. when following the link. The search string will be part of the
  9938. file link, given after a double colon, and `org-open-at-point'
  9939. will automatically search for it. If special measures must be
  9940. taken to make the search successful, another function should be
  9941. added to the companion hook `org-execute-file-search-functions',
  9942. which see.
  9943. A function in this hook may also use `setq' to set the variable
  9944. `description' to provide a suggestion for the descriptive text to
  9945. be used for this link when it gets inserted into an Org buffer
  9946. with \\[org-insert-link].")
  9947. (defvar org-execute-file-search-functions nil
  9948. "List of functions to execute a file search triggered by a link.
  9949. Functions added to this hook must accept a single argument, the
  9950. search string that was part of the file link, the part after the
  9951. double colon. The function must first check if it would like to
  9952. handle this search, for example by checking the `major-mode' or
  9953. the file extension. If it decides not to handle this search, it
  9954. should just return nil to give other functions a chance. If it
  9955. does handle the search, it must return a non-nil value to keep
  9956. other functions from trying.
  9957. Each function can access the current prefix argument through the
  9958. variable `current-prefix-arg'. Note that a single prefix is used
  9959. to force opening a link in Emacs, so it may be good to only use a
  9960. numeric or double prefix to guide the search function.
  9961. In case this is needed, a function in this hook can also restore
  9962. the window configuration before `org-open-at-point' was called using:
  9963. (set-window-configuration org-window-config-before-follow-link)")
  9964. (defun org-search-radio-target (target)
  9965. "Search a radio target matching TARGET in current buffer.
  9966. White spaces are not significant."
  9967. (let ((re (format "<<<%s>>>"
  9968. (mapconcat #'regexp-quote
  9969. (org-split-string target "[ \t\n]+")
  9970. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9971. (origin (point)))
  9972. (goto-char (point-min))
  9973. (catch :radio-match
  9974. (while (re-search-forward re nil t)
  9975. (backward-char)
  9976. (let ((object (org-element-context)))
  9977. (when (eq (org-element-type object) 'radio-target)
  9978. (goto-char (org-element-property :begin object))
  9979. (org-show-context 'link-search)
  9980. (throw :radio-match nil))))
  9981. (goto-char origin)
  9982. (user-error "No match for radio target: %s" target))))
  9983. (defun org-link-search (s &optional avoid-pos stealth)
  9984. "Search for a search string S.
  9985. If S starts with \"#\", it triggers a custom ID search.
  9986. If S is enclosed within parenthesis, it initiates a coderef
  9987. search.
  9988. If S is surrounded by forward slashes, it is interpreted as
  9989. a regular expression. In Org mode files, this will create an
  9990. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9991. to list matches. If the current buffer is in `dired-mode', grep
  9992. will be used to search in all files.
  9993. When AVOID-POS is given, ignore matches near that position.
  9994. When optional argument STEALTH is non-nil, do not modify
  9995. visibility around point, thus ignoring `org-show-context-detail'
  9996. variable.
  9997. Search is case-insensitive and ignores white spaces. Return type
  9998. of matched result, which is either `dedicated' or `fuzzy'."
  9999. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  10000. (let* ((case-fold-search t)
  10001. (origin (point))
  10002. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  10003. (words (org-split-string s "[ \t\n]+"))
  10004. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  10005. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  10006. type)
  10007. (cond
  10008. ;; Check if there are any special search functions.
  10009. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  10010. ((eq (string-to-char s) ?#)
  10011. ;; Look for a custom ID S if S starts with "#".
  10012. (let* ((id (substring normalized 1))
  10013. (match (org-find-property "CUSTOM_ID" id)))
  10014. (if match (progn (goto-char match) (setf type 'dedicated))
  10015. (error "No match for custom ID: %s" id))))
  10016. ((string-match "\\`(\\(.*\\))\\'" normalized)
  10017. ;; Look for coderef targets if S is enclosed within parenthesis.
  10018. (let ((coderef (match-string-no-properties 1 normalized))
  10019. (re (substring s-single-re 1 -1)))
  10020. (goto-char (point-min))
  10021. (catch :coderef-match
  10022. (while (re-search-forward re nil t)
  10023. (let ((element (org-element-at-point)))
  10024. (when (and (memq (org-element-type element)
  10025. '(example-block src-block))
  10026. ;; Build proper regexp according to current
  10027. ;; block's label format.
  10028. (let ((label-fmt
  10029. (regexp-quote
  10030. (or (org-element-property :label-fmt element)
  10031. org-coderef-label-format))))
  10032. (save-excursion
  10033. (beginning-of-line)
  10034. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  10035. (format label-fmt coderef))))))
  10036. (setq type 'dedicated)
  10037. (goto-char (match-beginning 1))
  10038. (throw :coderef-match nil))))
  10039. (goto-char origin)
  10040. (error "No match for coderef: %s" coderef))))
  10041. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10042. ;; Look for a regular expression.
  10043. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10044. (match-string 1 s)))
  10045. ;; Fuzzy links.
  10046. (t
  10047. (let ((starred (eq (string-to-char normalized) ?*)))
  10048. (cond
  10049. ;; Look for targets, only if not in a headline search.
  10050. ((and (not starred)
  10051. (let ((target (format "<<%s>>" s-multi-re)))
  10052. (catch :target-match
  10053. (goto-char (point-min))
  10054. (while (re-search-forward target nil t)
  10055. (backward-char)
  10056. (let ((context (org-element-context)))
  10057. (when (eq (org-element-type context) 'target)
  10058. (setq type 'dedicated)
  10059. (goto-char (org-element-property :begin context))
  10060. (throw :target-match t))))
  10061. nil))))
  10062. ;; Look for elements named after S, only if not in a headline
  10063. ;; search.
  10064. ((and (not starred)
  10065. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10066. (catch :name-match
  10067. (goto-char (point-min))
  10068. (while (re-search-forward name nil t)
  10069. (let ((element (org-element-at-point)))
  10070. (when (equal (org-split-string
  10071. (org-element-property :name element)
  10072. "[ \t]+")
  10073. words)
  10074. (setq type 'dedicated)
  10075. (beginning-of-line)
  10076. (throw :name-match t))))
  10077. nil))))
  10078. ;; Regular text search. Prefer headlines in Org mode
  10079. ;; buffers.
  10080. ((and (derived-mode-p 'org-mode)
  10081. (let* ((wspace "[ \t]")
  10082. (wspaceopt (concat wspace "*"))
  10083. (cookie (concat "\\(?:"
  10084. wspaceopt
  10085. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  10086. wspaceopt
  10087. "\\)"))
  10088. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10089. (title
  10090. (format "\\(?:%s[ \t]+\\)?%s?%s%s?"
  10091. org-comment-string
  10092. sep
  10093. (let ((re (mapconcat #'regexp-quote words sep)))
  10094. (if starred (substring re 1) re))
  10095. sep))
  10096. (exact-title (format "\\`%s\\'" title))
  10097. (re (concat org-outline-regexp-bol "+.*" title)))
  10098. (goto-char (point-min))
  10099. (catch :found
  10100. (while (re-search-forward re nil t)
  10101. (when (string-match-p exact-title (org-get-heading t t))
  10102. (throw :found t)))
  10103. nil)))
  10104. (beginning-of-line)
  10105. (setq type 'dedicated))
  10106. ;; Offer to create non-existent headline depending on
  10107. ;; `org-link-search-must-match-exact-headline'.
  10108. ((and (derived-mode-p 'org-mode)
  10109. (not org-link-search-inhibit-query)
  10110. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10111. (yes-or-no-p "No match - create this as a new heading? "))
  10112. (goto-char (point-max))
  10113. (unless (bolp) (newline))
  10114. (org-insert-heading nil t t)
  10115. (insert s "\n")
  10116. (beginning-of-line 0))
  10117. ;; Only headlines are looked after. No need to process
  10118. ;; further: throw an error.
  10119. ((and (derived-mode-p 'org-mode)
  10120. (or starred org-link-search-must-match-exact-headline))
  10121. (goto-char origin)
  10122. (error "No match for fuzzy expression: %s" normalized))
  10123. ;; Regular text search.
  10124. ((catch :fuzzy-match
  10125. (goto-char (point-min))
  10126. (while (re-search-forward s-multi-re nil t)
  10127. ;; Skip match if it contains AVOID-POS or it is included
  10128. ;; in a link with a description but outside the
  10129. ;; description.
  10130. (unless (or (and avoid-pos
  10131. (<= (match-beginning 0) avoid-pos)
  10132. (> (match-end 0) avoid-pos))
  10133. (and (save-match-data
  10134. (org-in-regexp org-bracket-link-regexp))
  10135. (match-beginning 3)
  10136. (or (> (match-beginning 3) (point))
  10137. (<= (match-end 3) (point)))
  10138. (org-element-lineage
  10139. (save-match-data (org-element-context))
  10140. '(link) t)))
  10141. (goto-char (match-beginning 0))
  10142. (setq type 'fuzzy)
  10143. (throw :fuzzy-match t)))
  10144. nil))
  10145. ;; All failed. Throw an error.
  10146. (t (goto-char origin)
  10147. (error "No match for fuzzy expression: %s" normalized))))))
  10148. ;; Disclose surroundings of match, if appropriate.
  10149. (when (and (derived-mode-p 'org-mode) (not stealth))
  10150. (org-show-context 'link-search))
  10151. type))
  10152. (defun org-get-buffer-for-internal-link (buffer)
  10153. "Return a buffer to be used for displaying the link target of internal links."
  10154. (cond
  10155. ((not org-display-internal-link-with-indirect-buffer)
  10156. buffer)
  10157. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10158. (message "Buffer is already a clone, not making another one")
  10159. ;; we also do not modify visibility in this case
  10160. buffer)
  10161. (t ; make a new indirect buffer for displaying the link
  10162. (let* ((bn (buffer-name buffer))
  10163. (ibn (concat bn "(Clone)"))
  10164. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10165. (with-current-buffer ib (org-overview))
  10166. ib))))
  10167. (defun org-do-occur (regexp &optional cleanup)
  10168. "Call the Emacs command `occur'.
  10169. If CLEANUP is non-nil, remove the printout of the regular expression
  10170. in the *Occur* buffer. This is useful if the regex is long and not useful
  10171. to read."
  10172. (occur regexp)
  10173. (when cleanup
  10174. (let ((cwin (selected-window)) win beg end)
  10175. (when (setq win (get-buffer-window "*Occur*"))
  10176. (select-window win))
  10177. (goto-char (point-min))
  10178. (when (re-search-forward "match[a-z]+" nil t)
  10179. (setq beg (match-end 0))
  10180. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10181. (setq end (1- (match-beginning 0)))))
  10182. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10183. (goto-char (point-min))
  10184. (select-window cwin))))
  10185. ;;; The mark ring for links jumps
  10186. (defvar org-mark-ring nil
  10187. "Mark ring for positions before jumps in Org mode.")
  10188. (defvar org-mark-ring-last-goto nil
  10189. "Last position in the mark ring used to go back.")
  10190. ;; Fill and close the ring
  10191. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10192. (dotimes (_ org-mark-ring-length)
  10193. (push (make-marker) org-mark-ring))
  10194. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10195. org-mark-ring)
  10196. (defun org-mark-ring-push (&optional pos buffer)
  10197. "Put the current position or POS into the mark ring and rotate it."
  10198. (interactive)
  10199. (setq pos (or pos (point)))
  10200. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10201. (move-marker (car org-mark-ring)
  10202. (or pos (point))
  10203. (or buffer (current-buffer)))
  10204. (message "%s"
  10205. (substitute-command-keys
  10206. "Position saved to mark ring, go back with \
  10207. `\\[org-mark-ring-goto]'.")))
  10208. (defun org-mark-ring-goto (&optional n)
  10209. "Jump to the previous position in the mark ring.
  10210. With prefix arg N, jump back that many stored positions. When
  10211. called several times in succession, walk through the entire ring.
  10212. Org mode commands jumping to a different position in the current file,
  10213. or to another Org file, automatically push the old position onto the ring."
  10214. (interactive "p")
  10215. (let (p m)
  10216. (if (eq last-command this-command)
  10217. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10218. (setq p org-mark-ring))
  10219. (setq org-mark-ring-last-goto p)
  10220. (setq m (car p))
  10221. (pop-to-buffer-same-window (marker-buffer m))
  10222. (goto-char m)
  10223. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10224. (defun org-add-angle-brackets (s)
  10225. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10226. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10227. s)
  10228. ;;; Following specific links
  10229. (defvar org-agenda-buffer-tmp-name)
  10230. (defvar org-agenda-start-on-weekday)
  10231. (defun org-follow-timestamp-link ()
  10232. "Open an agenda view for the time-stamp date/range at point."
  10233. (cond
  10234. ((org-at-date-range-p t)
  10235. (let ((org-agenda-start-on-weekday)
  10236. (t1 (match-string 1))
  10237. (t2 (match-string 2)) tt1 tt2)
  10238. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10239. tt2 (time-to-days (org-time-string-to-time t2)))
  10240. (let ((org-agenda-buffer-tmp-name
  10241. (format "*Org Agenda(a:%s)"
  10242. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10243. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10244. ((org-at-timestamp-p t)
  10245. (let ((org-agenda-buffer-tmp-name
  10246. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10247. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10248. (substring (match-string 1) 0 10)))
  10249. 1)))
  10250. (t (error "This should not happen"))))
  10251. ;;; Following file links
  10252. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10253. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10254. (declare-function mailcap-mime-info
  10255. "mailcap" (string &optional request no-decode))
  10256. (defvar org-wait nil)
  10257. (defun org-open-file (path &optional in-emacs line search)
  10258. "Open the file at PATH.
  10259. First, this expands any special file name abbreviations. Then the
  10260. configuration variable `org-file-apps' is checked if it contains an
  10261. entry for this file type, and if yes, the corresponding command is launched.
  10262. If no application is found, Emacs simply visits the file.
  10263. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10264. With a double \\[universal-argument] \\[universal-argument] \
  10265. prefix arg, Org tries to avoid opening in Emacs
  10266. and to use an external application to visit the file.
  10267. Optional LINE specifies a line to go to, optional SEARCH a string
  10268. to search for. If LINE or SEARCH is given, the file will be
  10269. opened in Emacs, unless an entry from org-file-apps that makes
  10270. use of groups in a regexp matches.
  10271. If you want to change the way frames are used when following a
  10272. link, please customize `org-link-frame-setup'.
  10273. If the file does not exist, an error is thrown."
  10274. (let* ((file (if (equal path "")
  10275. buffer-file-name
  10276. (substitute-in-file-name (expand-file-name path))))
  10277. (file-apps (append org-file-apps (org-default-apps)))
  10278. (apps (cl-remove-if
  10279. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10280. (apps-dlink (cl-remove-if-not
  10281. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10282. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10283. (dirp (unless remp (file-directory-p file)))
  10284. (file (if (and dirp org-open-directory-means-index-dot-org)
  10285. (concat (file-name-as-directory file) "index.org")
  10286. file))
  10287. (a-m-a-p (assq 'auto-mode apps))
  10288. (dfile (downcase file))
  10289. ;; Reconstruct the original link from the PATH, LINE and
  10290. ;; SEARCH args.
  10291. (link (cond (line (concat file "::" (number-to-string line)))
  10292. (search (concat file "::" search))
  10293. (t file)))
  10294. (dlink (downcase link))
  10295. (old-buffer (current-buffer))
  10296. (old-pos (point))
  10297. (old-mode major-mode)
  10298. (ext
  10299. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10300. (match-string 1 dfile)))
  10301. cmd link-match-data)
  10302. (cond
  10303. ((member in-emacs '((16) system))
  10304. (setq cmd (cdr (assq 'system apps))))
  10305. (in-emacs (setq cmd 'emacs))
  10306. (t
  10307. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10308. (and dirp (cdr (assq 'directory apps)))
  10309. ;; First, try matching against apps-dlink if we
  10310. ;; get a match here, store the match data for
  10311. ;; later.
  10312. (let ((match (assoc-default dlink apps-dlink
  10313. 'string-match)))
  10314. (if match
  10315. (progn (setq link-match-data (match-data))
  10316. match)
  10317. (progn (setq in-emacs (or in-emacs line search))
  10318. nil))) ; if we have no match in apps-dlink,
  10319. ; always open the file in emacs if line or search
  10320. ; is given (for backwards compatibility)
  10321. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10322. 'string-match)
  10323. (cdr (assoc ext apps))
  10324. (cdr (assq t apps))))))
  10325. (when (eq cmd 'system)
  10326. (setq cmd (cdr (assq 'system apps))))
  10327. (when (eq cmd 'default)
  10328. (setq cmd (cdr (assoc t apps))))
  10329. (when (eq cmd 'mailcap)
  10330. (require 'mailcap)
  10331. (mailcap-parse-mailcaps)
  10332. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10333. (command (mailcap-mime-info mime-type)))
  10334. (if (stringp command)
  10335. (setq cmd command)
  10336. (setq cmd 'emacs))))
  10337. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10338. (not (file-exists-p file))
  10339. (not org-open-non-existing-files))
  10340. (user-error "No such file: %s" file))
  10341. (cond
  10342. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10343. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10344. (while (string-match "['\"]%s['\"]" cmd)
  10345. (setq cmd (replace-match "%s" t t cmd)))
  10346. (setq cmd (replace-regexp-in-string
  10347. "%s"
  10348. (shell-quote-argument (convert-standard-filename file))
  10349. cmd
  10350. nil t))
  10351. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10352. (save-match-data
  10353. (let ((match-index 1)
  10354. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10355. (set-match-data link-match-data)
  10356. (while (<= match-index number-of-groups)
  10357. (let ((regex (concat "%" (number-to-string match-index)))
  10358. (replace-with (match-string match-index dlink)))
  10359. (while (string-match regex cmd)
  10360. (setq cmd (replace-match replace-with t t cmd))))
  10361. (setq match-index (+ match-index 1)))))
  10362. (save-window-excursion
  10363. (message "Running %s...done" cmd)
  10364. (start-process-shell-command cmd nil cmd)
  10365. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10366. ((or (stringp cmd)
  10367. (eq cmd 'emacs))
  10368. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10369. (widen)
  10370. (cond (line (org-goto-line line)
  10371. (when (derived-mode-p 'org-mode) (org-reveal)))
  10372. (search (org-link-search search))))
  10373. ((functionp cmd)
  10374. (save-match-data
  10375. (set-match-data link-match-data)
  10376. (condition-case nil
  10377. (funcall cmd file link)
  10378. ;; FIXME: Remove this check when most default installations
  10379. ;; of Emacs have at least Org 9.0.
  10380. ((debug wrong-number-of-arguments wrong-type-argument
  10381. invalid-function)
  10382. (user-error "Please see Org News for version 9.0 about \
  10383. `org-file-apps'--Lisp error: %S" cmd)))))
  10384. ((consp cmd)
  10385. ;; FIXME: Remove this check when most default installations of
  10386. ;; Emacs have at least Org 9.0.
  10387. ;; Heads-up instead of silently fall back to
  10388. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10389. ;; with sexp instead of a function for `cmd'.
  10390. (user-error "Please see Org News for version 9.0 about \
  10391. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10392. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10393. (and (derived-mode-p 'org-mode)
  10394. (eq old-mode 'org-mode)
  10395. (or (not (eq old-buffer (current-buffer)))
  10396. (not (eq old-pos (point))))
  10397. (org-mark-ring-push old-pos old-buffer))))
  10398. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10399. "This function returns non-nil if `entry' uses a regular
  10400. expression which should be matched against the whole link by
  10401. org-open-file.
  10402. It assumes that is the case when the entry uses a regular
  10403. expression which has at least one grouping construct and the
  10404. action is either a lisp form or a command string containing
  10405. `%1', i.e. using at least one subexpression match as a
  10406. parameter."
  10407. (let ((selector (car entry))
  10408. (action (cdr entry)))
  10409. (if (stringp selector)
  10410. (and (> (regexp-opt-depth selector) 0)
  10411. (or (and (stringp action)
  10412. (string-match "%[0-9]" action))
  10413. (consp action)))
  10414. nil)))
  10415. (defun org-default-apps ()
  10416. "Return the default applications for this operating system."
  10417. (cond
  10418. ((eq system-type 'darwin)
  10419. org-file-apps-defaults-macosx)
  10420. ((eq system-type 'windows-nt)
  10421. org-file-apps-defaults-windowsnt)
  10422. (t org-file-apps-defaults-gnu)))
  10423. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10424. "Convert extensions to regular expressions in the cars of LIST.
  10425. Also, weed out any non-string entries, because the return value is used
  10426. only for regexp matching.
  10427. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10428. point to the symbol `emacs', indicating that the file should
  10429. be opened in Emacs."
  10430. (append
  10431. (delq nil
  10432. (mapcar (lambda (x)
  10433. (unless (not (stringp (car x)))
  10434. (if (string-match "\\W" (car x))
  10435. x
  10436. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10437. list))
  10438. (when add-auto-mode
  10439. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10440. (defvar ange-ftp-name-format)
  10441. (defun org-file-remote-p (file)
  10442. "Test whether FILE specifies a location on a remote system.
  10443. Return non-nil if the location is indeed remote.
  10444. For example, the filename \"/user@host:/foo\" specifies a location
  10445. on the system \"/user@host:\"."
  10446. (cond ((fboundp 'file-remote-p)
  10447. (file-remote-p file))
  10448. ((fboundp 'tramp-handle-file-remote-p)
  10449. (tramp-handle-file-remote-p file))
  10450. ((and (boundp 'ange-ftp-name-format)
  10451. (string-match (car ange-ftp-name-format) file))
  10452. t)))
  10453. ;;;; Refiling
  10454. (defun org-get-org-file ()
  10455. "Read a filename, with default directory `org-directory'."
  10456. (let ((default (or org-default-notes-file remember-data-file)))
  10457. (read-file-name (format "File name [%s]: " default)
  10458. (file-name-as-directory org-directory)
  10459. default)))
  10460. (defun org-notes-order-reversed-p ()
  10461. "Check if the current file should receive notes in reversed order."
  10462. (cond
  10463. ((not org-reverse-note-order) nil)
  10464. ((eq t org-reverse-note-order) t)
  10465. ((not (listp org-reverse-note-order)) nil)
  10466. (t (catch 'exit
  10467. (dolist (entry org-reverse-note-order)
  10468. (when (string-match (car entry) buffer-file-name)
  10469. (throw 'exit (cdr entry))))))))
  10470. (defvar org-refile-target-table nil
  10471. "The list of refile targets, created by `org-refile'.")
  10472. (defvar org-agenda-new-buffers nil
  10473. "Buffers created to visit agenda files.")
  10474. (defvar org-refile-cache nil
  10475. "Cache for refile targets.")
  10476. (defvar org-refile-markers nil
  10477. "All the markers used for caching refile locations.")
  10478. (defun org-refile-marker (pos)
  10479. "Get a new refile marker, but only if caching is in use."
  10480. (if (not org-refile-use-cache)
  10481. pos
  10482. (let ((m (make-marker)))
  10483. (move-marker m pos)
  10484. (push m org-refile-markers)
  10485. m)))
  10486. (defun org-refile-cache-clear ()
  10487. "Clear the refile cache and disable all the markers."
  10488. (dolist (m org-refile-markers) (move-marker m nil))
  10489. (setq org-refile-markers nil)
  10490. (setq org-refile-cache nil)
  10491. (message "Refile cache has been cleared"))
  10492. (defun org-refile-cache-check-set (set)
  10493. "Check if all the markers in the cache still have live buffers."
  10494. (let (marker)
  10495. (catch 'exit
  10496. (while (and set (setq marker (nth 3 (pop set))))
  10497. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10498. (when (and marker (null (marker-buffer marker)))
  10499. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10500. (sit-for 3)
  10501. (throw 'exit nil)))
  10502. t)))
  10503. (defun org-refile-cache-put (set &rest identifiers)
  10504. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10505. (let* ((key (sha1 (prin1-to-string identifiers)))
  10506. (entry (assoc key org-refile-cache)))
  10507. (if entry
  10508. (setcdr entry set)
  10509. (push (cons key set) org-refile-cache))))
  10510. (defun org-refile-cache-get (&rest identifiers)
  10511. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10512. (cond
  10513. ((not org-refile-cache) nil)
  10514. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10515. (t
  10516. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10517. org-refile-cache))))
  10518. (and set (org-refile-cache-check-set set) set)))))
  10519. (defvar org-outline-path-cache nil
  10520. "Alist between buffer positions and outline paths.
  10521. It value is an alist (POSITION . PATH) where POSITION is the
  10522. buffer position at the beginning of an entry and PATH is a list
  10523. of strings describing the outline path for that entry, in reverse
  10524. order.")
  10525. (defun org-refile-get-targets (&optional default-buffer)
  10526. "Produce a table with refile targets."
  10527. (let ((case-fold-search nil)
  10528. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10529. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10530. targets tgs files desc descre)
  10531. (message "Getting targets...")
  10532. (with-current-buffer (or default-buffer (current-buffer))
  10533. (dolist (entry entries)
  10534. (setq files (car entry) desc (cdr entry))
  10535. (cond
  10536. ((null files) (setq files (list (current-buffer))))
  10537. ((eq files 'org-agenda-files)
  10538. (setq files (org-agenda-files 'unrestricted)))
  10539. ((and (symbolp files) (fboundp files))
  10540. (setq files (funcall files)))
  10541. ((and (symbolp files) (boundp files))
  10542. (setq files (symbol-value files))))
  10543. (when (stringp files) (setq files (list files)))
  10544. (cond
  10545. ((eq (car desc) :tag)
  10546. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10547. ((eq (car desc) :todo)
  10548. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10549. ((eq (car desc) :regexp)
  10550. (setq descre (cdr desc)))
  10551. ((eq (car desc) :level)
  10552. (setq descre (concat "^\\*\\{" (number-to-string
  10553. (if org-odd-levels-only
  10554. (1- (* 2 (cdr desc)))
  10555. (cdr desc)))
  10556. "\\}[ \t]")))
  10557. ((eq (car desc) :maxlevel)
  10558. (setq descre (concat "^\\*\\{1," (number-to-string
  10559. (if org-odd-levels-only
  10560. (1- (* 2 (cdr desc)))
  10561. (cdr desc)))
  10562. "\\}[ \t]")))
  10563. (t (error "Bad refiling target description %s" desc)))
  10564. (dolist (f files)
  10565. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10566. (or
  10567. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10568. (progn
  10569. (when (bufferp f)
  10570. (setq f (buffer-file-name (buffer-base-buffer f))))
  10571. (setq f (and f (expand-file-name f)))
  10572. (when (eq org-refile-use-outline-path 'file)
  10573. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10574. (org-with-wide-buffer
  10575. (goto-char (point-min))
  10576. (setq org-outline-path-cache nil)
  10577. (while (re-search-forward descre nil t)
  10578. (beginning-of-line)
  10579. (let ((case-fold-search nil))
  10580. (looking-at org-complex-heading-regexp))
  10581. (let ((begin (point))
  10582. (heading (match-string-no-properties 4)))
  10583. (unless (or (and
  10584. org-refile-target-verify-function
  10585. (not
  10586. (funcall org-refile-target-verify-function)))
  10587. (not heading))
  10588. (let ((re (format org-complex-heading-regexp-format
  10589. (regexp-quote heading)))
  10590. (target
  10591. (if (not org-refile-use-outline-path) heading
  10592. (mapconcat
  10593. #'org-protect-slash
  10594. (append
  10595. (pcase org-refile-use-outline-path
  10596. (`file (list (file-name-nondirectory
  10597. (buffer-file-name
  10598. (buffer-base-buffer)))))
  10599. (`full-file-path
  10600. (list (buffer-file-name
  10601. (buffer-base-buffer))))
  10602. (_ nil))
  10603. (org-get-outline-path t t))
  10604. "/"))))
  10605. (push (list target f re (org-refile-marker (point)))
  10606. tgs)))
  10607. (when (= (point) begin)
  10608. ;; Verification function has not moved point.
  10609. (end-of-line)))))))
  10610. (when org-refile-use-cache
  10611. (org-refile-cache-put tgs (buffer-file-name) descre))
  10612. (setq targets (append tgs targets))))))
  10613. (message "Getting targets...done")
  10614. (nreverse targets)))
  10615. (defun org-protect-slash (s)
  10616. (replace-regexp-in-string "/" "\\/" s nil t))
  10617. (defun org--get-outline-path-1 (&optional use-cache)
  10618. "Return outline path to current headline.
  10619. Outline path is a list of strings, in reverse order. When
  10620. optional argument USE-CACHE is non-nil, make use of a cache. See
  10621. `org-get-outline-path' for details.
  10622. Assume buffer is widened and point is on a headline."
  10623. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10624. (let ((p (point))
  10625. (heading (let ((case-fold-search nil))
  10626. (looking-at org-complex-heading-regexp)
  10627. (if (not (match-end 4)) ""
  10628. ;; Remove statistics cookies.
  10629. (org-trim
  10630. (org-link-display-format
  10631. (replace-regexp-in-string
  10632. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10633. (match-string-no-properties 4))))))))
  10634. (if (org-up-heading-safe)
  10635. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10636. (when use-cache
  10637. (push (cons p path) org-outline-path-cache))
  10638. path)
  10639. ;; This is a new root node. Since we assume we are moving
  10640. ;; forward, we can drop previous cache so as to limit number
  10641. ;; of associations there.
  10642. (let ((path (list heading)))
  10643. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10644. path)))))
  10645. (defun org-get-outline-path (&optional with-self use-cache)
  10646. "Return the outline path to the current entry.
  10647. An outline path is a list of ancestors for current headline, as
  10648. a list of strings. Statistics cookies are removed and links are
  10649. replaced with their description, if any, or their path otherwise.
  10650. When optional argument WITH-SELF is non-nil, the path also
  10651. includes the current headline.
  10652. When optional argument USE-CACHE is non-nil, cache outline paths
  10653. between calls to this function so as to avoid backtracking. This
  10654. argument is useful when planning to find more than one outline
  10655. path in the same document. In that case, there are two
  10656. conditions to satisfy:
  10657. - `org-outline-path-cache' is set to nil before starting the
  10658. process;
  10659. - outline paths are computed by increasing buffer positions."
  10660. (org-with-wide-buffer
  10661. (and (or (and with-self (org-back-to-heading t))
  10662. (org-up-heading-safe))
  10663. (reverse (org--get-outline-path-1 use-cache)))))
  10664. (defun org-format-outline-path (path &optional width prefix separator)
  10665. "Format the outline path PATH for display.
  10666. WIDTH is the maximum number of characters that is available.
  10667. PREFIX is a prefix to be included in the returned string,
  10668. such as the file name.
  10669. SEPARATOR is inserted between the different parts of the path,
  10670. the default is \"/\"."
  10671. (setq width (or width 79))
  10672. (setq path (delq nil path))
  10673. (unless (> width 0)
  10674. (user-error "Argument `width' must be positive"))
  10675. (setq separator (or separator "/"))
  10676. (let* ((org-odd-levels-only nil)
  10677. (fpath (concat
  10678. prefix (and prefix path separator)
  10679. (mapconcat
  10680. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10681. (cl-loop for head in path
  10682. for n from 0
  10683. collect (org-add-props
  10684. head nil 'face
  10685. (nth (% n org-n-level-faces) org-level-faces)))
  10686. separator))))
  10687. (when (> (length fpath) width)
  10688. (if (< width 7)
  10689. ;; It's unlikely that `width' will be this small, but don't
  10690. ;; waste characters by adding ".." if it is.
  10691. (setq fpath (substring fpath 0 width))
  10692. (setf (substring fpath (- width 2)) "..")))
  10693. fpath))
  10694. (defun org-display-outline-path (&optional file current separator just-return-string)
  10695. "Display the current outline path in the echo area.
  10696. If FILE is non-nil, prepend the output with the file name.
  10697. If CURRENT is non-nil, append the current heading to the output.
  10698. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10699. the different parts of the path and defaults to \"/\".
  10700. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10701. (interactive "P")
  10702. (let* (case-fold-search
  10703. (bfn (buffer-file-name (buffer-base-buffer)))
  10704. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10705. res)
  10706. (when current (setq path (append path
  10707. (save-excursion
  10708. (org-back-to-heading t)
  10709. (when (looking-at org-complex-heading-regexp)
  10710. (list (match-string 4)))))))
  10711. (setq res
  10712. (org-format-outline-path
  10713. path
  10714. (1- (frame-width))
  10715. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10716. separator))
  10717. (if just-return-string
  10718. (org-no-properties res)
  10719. (org-unlogged-message "%s" res))))
  10720. (defvar org-refile-history nil
  10721. "History for refiling operations.")
  10722. (defvar org-after-refile-insert-hook nil
  10723. "Hook run after `org-refile' has inserted its stuff at the new location.
  10724. Note that this is still *before* the stuff will be removed from
  10725. the *old* location.")
  10726. (defvar org-capture-last-stored-marker)
  10727. (defvar org-refile-keep nil
  10728. "Non-nil means `org-refile' will copy instead of refile.")
  10729. (defun org-copy ()
  10730. "Like `org-refile', but copy."
  10731. (interactive)
  10732. (let ((org-refile-keep t))
  10733. (funcall 'org-refile nil nil nil "Copy")))
  10734. (defun org-refile (&optional arg default-buffer rfloc msg)
  10735. "Move the entry or entries at point to another heading.
  10736. The list of target headings is compiled using the information in
  10737. `org-refile-targets', which see.
  10738. At the target location, the entry is filed as a subitem of the
  10739. target heading. Depending on `org-reverse-note-order', the new
  10740. subitem will either be the first or the last subitem.
  10741. If there is an active region, all entries in that region will be
  10742. refiled. However, the region must fulfill the requirement that
  10743. the first heading sets the top-level of the moved text.
  10744. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10745. location
  10746. and not actually move anything.
  10747. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10748. location where the last
  10749. refiling operation has put the subtree.
  10750. With a numeric prefix argument of `2', refile to the running clock.
  10751. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10752. being set to t and copy to the target location, don't move it.
  10753. Beware that keeping refiled entries may result in duplicated ID
  10754. properties.
  10755. RFLOC can be a refile location obtained in a different way.
  10756. MSG is a string to replace \"Refile\" in the default prompt with
  10757. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10758. See also `org-refile-use-outline-path'.
  10759. If you are using target caching (see `org-refile-use-cache'), you
  10760. have to clear the target cache in order to find new targets.
  10761. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10762. prefix argument (`C-u C-u C-u C-c C-w')."
  10763. (interactive "P")
  10764. (if (member arg '(0 (64)))
  10765. (org-refile-cache-clear)
  10766. (let* ((actionmsg (cond (msg msg)
  10767. ((equal arg 3) "Refile (and keep)")
  10768. (t "Refile")))
  10769. (regionp (org-region-active-p))
  10770. (region-start (and regionp (region-beginning)))
  10771. (region-end (and regionp (region-end)))
  10772. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10773. pos it nbuf file level reversed)
  10774. (setq last-command nil)
  10775. (when regionp
  10776. (goto-char region-start)
  10777. (or (bolp) (goto-char (point-at-bol)))
  10778. (setq region-start (point))
  10779. (unless (or (org-kill-is-subtree-p
  10780. (buffer-substring region-start region-end))
  10781. (prog1 org-refile-active-region-within-subtree
  10782. (let ((s (point-at-eol)))
  10783. (org-toggle-heading)
  10784. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10785. (user-error "The region is not a (sequence of) subtree(s)")))
  10786. (if (equal arg '(16))
  10787. (org-refile-goto-last-stored)
  10788. (when (or
  10789. (and (equal arg 2)
  10790. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10791. (prog1
  10792. (setq it (list (or org-clock-heading "running clock")
  10793. (buffer-file-name
  10794. (marker-buffer org-clock-hd-marker))
  10795. ""
  10796. (marker-position org-clock-hd-marker)))
  10797. (setq arg nil)))
  10798. (setq it
  10799. (or rfloc
  10800. (let (heading-text)
  10801. (save-excursion
  10802. (unless (and arg (listp arg))
  10803. (org-back-to-heading t)
  10804. (setq heading-text
  10805. (replace-regexp-in-string
  10806. org-bracket-link-regexp
  10807. "\\3"
  10808. (or (nth 4 (org-heading-components))
  10809. ""))))
  10810. (org-refile-get-location
  10811. (cond ((and arg (listp arg)) "Goto")
  10812. (regionp (concat actionmsg " region to"))
  10813. (t (concat actionmsg " subtree \""
  10814. heading-text "\" to")))
  10815. default-buffer
  10816. (and (not (equal '(4) arg))
  10817. org-refile-allow-creating-parent-nodes)))))))
  10818. (setq file (nth 1 it)
  10819. pos (nth 3 it))
  10820. (when (and (not arg)
  10821. pos
  10822. (equal (buffer-file-name) file)
  10823. (if regionp
  10824. (and (>= pos region-start)
  10825. (<= pos region-end))
  10826. (and (>= pos (point))
  10827. (< pos (save-excursion
  10828. (org-end-of-subtree t t))))))
  10829. (error "Cannot refile to position inside the tree or region"))
  10830. (setq nbuf (or (find-buffer-visiting file)
  10831. (find-file-noselect file)))
  10832. (if (and arg (not (equal arg 3)))
  10833. (progn
  10834. (pop-to-buffer-same-window nbuf)
  10835. (goto-char pos)
  10836. (org-show-context 'org-goto))
  10837. (if regionp
  10838. (progn
  10839. (org-kill-new (buffer-substring region-start region-end))
  10840. (org-save-markers-in-region region-start region-end))
  10841. (org-copy-subtree 1 nil t))
  10842. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10843. (find-file-noselect file)))
  10844. (setq reversed (org-notes-order-reversed-p))
  10845. (org-with-wide-buffer
  10846. (if pos
  10847. (progn
  10848. (goto-char pos)
  10849. (looking-at org-outline-regexp)
  10850. (setq level (org-get-valid-level (funcall outline-level) 1))
  10851. (goto-char
  10852. (if reversed
  10853. (or (outline-next-heading) (point-max))
  10854. (or (save-excursion (org-get-next-sibling))
  10855. (org-end-of-subtree t t)
  10856. (point-max)))))
  10857. (setq level 1)
  10858. (if (not reversed)
  10859. (goto-char (point-max))
  10860. (goto-char (point-min))
  10861. (or (outline-next-heading) (goto-char (point-max)))))
  10862. (unless (bolp) (newline))
  10863. (org-paste-subtree level nil nil t)
  10864. (when org-log-refile
  10865. (org-add-log-setup 'refile nil nil org-log-refile)
  10866. (unless (eq org-log-refile 'note)
  10867. (save-excursion (org-add-log-note))))
  10868. (and org-auto-align-tags
  10869. (let ((org-loop-over-headlines-in-active-region nil))
  10870. (org-set-tags nil t)))
  10871. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10872. :last-refile)))
  10873. (when bookmark-name
  10874. (with-demoted-errors
  10875. (bookmark-set bookmark-name))))
  10876. ;; If we are refiling for capture, make sure that the
  10877. ;; last-capture pointers point here
  10878. (when (bound-and-true-p org-capture-is-refiling)
  10879. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10880. :last-capture-marker)))
  10881. (when bookmark-name
  10882. (with-demoted-errors
  10883. (bookmark-set bookmark-name))))
  10884. (move-marker org-capture-last-stored-marker (point)))
  10885. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10886. (run-hooks 'org-after-refile-insert-hook)))
  10887. (unless org-refile-keep
  10888. (if regionp
  10889. (delete-region (point) (+ (point) (- region-end region-start)))
  10890. (delete-region
  10891. (and (org-back-to-heading t) (point))
  10892. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10893. (when (featurep 'org-inlinetask)
  10894. (org-inlinetask-remove-END-maybe))
  10895. (setq org-markers-to-move nil)
  10896. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10897. (defun org-refile-goto-last-stored ()
  10898. "Go to the location where the last refile was stored."
  10899. (interactive)
  10900. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10901. (message "This is the location of the last refile"))
  10902. (defun org-refile--get-location (refloc tbl)
  10903. "When user refile to REFLOC, find the associated target in TBL.
  10904. Also check `org-refile-target-table'."
  10905. (car (delq
  10906. nil
  10907. (mapcar
  10908. (lambda (r) (or (assoc r tbl)
  10909. (assoc r org-refile-target-table)))
  10910. (list (replace-regexp-in-string "/$" "" refloc)
  10911. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10912. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10913. "Prompt the user for a refile location, using PROMPT.
  10914. PROMPT should not be suffixed with a colon and a space, because
  10915. this function appends the default value from
  10916. `org-refile-history' automatically, if that is not empty."
  10917. (let ((org-refile-targets org-refile-targets)
  10918. (org-refile-use-outline-path org-refile-use-outline-path))
  10919. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10920. (unless org-refile-target-table
  10921. (user-error "No refile targets"))
  10922. (let* ((cbuf (current-buffer))
  10923. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10924. (cfunc (if (and org-refile-use-outline-path
  10925. org-outline-path-complete-in-steps)
  10926. #'org-olpath-completing-read
  10927. #'completing-read))
  10928. (extra (if org-refile-use-outline-path "/" ""))
  10929. (cbnex (concat (buffer-name) extra))
  10930. (filename (and cfn (expand-file-name cfn)))
  10931. (tbl (mapcar
  10932. (lambda (x)
  10933. (if (and (not (member org-refile-use-outline-path
  10934. '(file full-file-path)))
  10935. (not (equal filename (nth 1 x))))
  10936. (cons (concat (car x) extra " ("
  10937. (file-name-nondirectory (nth 1 x)) ")")
  10938. (cdr x))
  10939. (cons (concat (car x) extra) (cdr x))))
  10940. org-refile-target-table))
  10941. (completion-ignore-case t)
  10942. cdef
  10943. (prompt (concat prompt
  10944. (or (and (car org-refile-history)
  10945. (concat " (default " (car org-refile-history) ")"))
  10946. (and (assoc cbnex tbl) (setq cdef cbnex)
  10947. (concat " (default " cbnex ")"))) ": "))
  10948. pa answ parent-target child parent old-hist)
  10949. (setq old-hist org-refile-history)
  10950. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10951. nil 'org-refile-history (or cdef (car org-refile-history))))
  10952. (if (setq pa (org-refile--get-location answ tbl))
  10953. (progn
  10954. (org-refile-check-position pa)
  10955. (when (or (not org-refile-history)
  10956. (not (eq old-hist org-refile-history))
  10957. (not (equal (car pa) (car org-refile-history))))
  10958. (setq org-refile-history
  10959. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10960. org-refile-history
  10961. (cdr org-refile-history))))
  10962. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10963. (pop org-refile-history)))
  10964. pa)
  10965. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10966. (progn
  10967. (setq parent (match-string 1 answ)
  10968. child (match-string 2 answ))
  10969. (setq parent-target (org-refile--get-location parent tbl))
  10970. (when (and parent-target
  10971. (or (eq new-nodes t)
  10972. (and (eq new-nodes 'confirm)
  10973. (y-or-n-p (format "Create new node \"%s\"? "
  10974. child)))))
  10975. (org-refile-new-child parent-target child)))
  10976. (user-error "Invalid target location")))))
  10977. (declare-function org-string-nw-p "org-macs" (s))
  10978. (defun org-refile-check-position (refile-pointer)
  10979. "Check if the refile pointer matches the headline to which it points."
  10980. (let* ((file (nth 1 refile-pointer))
  10981. (re (nth 2 refile-pointer))
  10982. (pos (nth 3 refile-pointer))
  10983. buffer)
  10984. (if (and (not (markerp pos)) (not file))
  10985. (user-error "Please indicate a target file in the refile path")
  10986. (when (org-string-nw-p re)
  10987. (setq buffer (if (markerp pos)
  10988. (marker-buffer pos)
  10989. (or (find-buffer-visiting file)
  10990. (find-file-noselect file))))
  10991. (with-current-buffer buffer
  10992. (org-with-wide-buffer
  10993. (goto-char pos)
  10994. (beginning-of-line 1)
  10995. (unless (looking-at-p re)
  10996. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10997. (defun org-refile-new-child (parent-target child)
  10998. "Use refile target PARENT-TARGET to add new CHILD below it."
  10999. (unless parent-target
  11000. (error "Cannot find parent for new node"))
  11001. (let ((file (nth 1 parent-target))
  11002. (pos (nth 3 parent-target))
  11003. level)
  11004. (with-current-buffer (or (find-buffer-visiting file)
  11005. (find-file-noselect file))
  11006. (org-with-wide-buffer
  11007. (if pos
  11008. (goto-char pos)
  11009. (goto-char (point-max))
  11010. (unless (bolp) (newline)))
  11011. (when (looking-at org-outline-regexp)
  11012. (setq level (funcall outline-level))
  11013. (org-end-of-subtree t t))
  11014. (org-back-over-empty-lines)
  11015. (insert "\n" (make-string
  11016. (if pos (org-get-valid-level level 1) 1) ?*)
  11017. " " child "\n")
  11018. (beginning-of-line 0)
  11019. (list (concat (car parent-target) "/" child) file "" (point))))))
  11020. (defun org-olpath-completing-read (prompt collection &rest args)
  11021. "Read an outline path like a file name."
  11022. (let ((thetable collection))
  11023. (apply #'completing-read
  11024. prompt
  11025. (lambda (string predicate &optional flag)
  11026. (cond
  11027. ((eq flag nil) (try-completion string thetable))
  11028. ((eq flag t)
  11029. (let ((l (length string)))
  11030. (mapcar (lambda (x)
  11031. (let ((r (substring x l))
  11032. (f (if (string-match " ([^)]*)$" x)
  11033. (match-string 0 x)
  11034. "")))
  11035. (if (string-match "/" r)
  11036. (concat string (substring r 0 (match-end 0)) f)
  11037. x)))
  11038. (all-completions string thetable predicate))))
  11039. ;; Exact match?
  11040. ((eq flag 'lambda) (assoc string thetable))))
  11041. args)))
  11042. ;;;; Dynamic blocks
  11043. (defun org-find-dblock (name)
  11044. "Find the first dynamic block with name NAME in the buffer.
  11045. If not found, stay at current position and return nil."
  11046. (let ((case-fold-search t) pos)
  11047. (save-excursion
  11048. (goto-char (point-min))
  11049. (setq pos (and (re-search-forward
  11050. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11051. (match-beginning 0))))
  11052. (when pos (goto-char pos))
  11053. pos))
  11054. (defun org-create-dblock (plist)
  11055. "Create a dynamic block section, with parameters taken from PLIST.
  11056. PLIST must contain a :name entry which is used as the name of the block."
  11057. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11058. (end-of-line 1)
  11059. (newline))
  11060. (let ((col (current-column))
  11061. (name (plist-get plist :name)))
  11062. (insert "#+BEGIN: " name)
  11063. (while plist
  11064. (if (eq (car plist) :name)
  11065. (setq plist (cddr plist))
  11066. (insert " " (prin1-to-string (pop plist)))))
  11067. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11068. (beginning-of-line -2)))
  11069. (defun org-prepare-dblock ()
  11070. "Prepare dynamic block for refresh.
  11071. This empties the block, puts the cursor at the insert position and returns
  11072. the property list including an extra property :name with the block name."
  11073. (unless (looking-at org-dblock-start-re)
  11074. (user-error "Not at a dynamic block"))
  11075. (let* ((begdel (1+ (match-end 0)))
  11076. (name (org-no-properties (match-string 1)))
  11077. (params (append (list :name name)
  11078. (read (concat "(" (match-string 3) ")")))))
  11079. (save-excursion
  11080. (beginning-of-line 1)
  11081. (skip-chars-forward " \t")
  11082. (setq params (plist-put params :indentation-column (current-column))))
  11083. (unless (re-search-forward org-dblock-end-re nil t)
  11084. (error "Dynamic block not terminated"))
  11085. (setq params
  11086. (append params
  11087. (list :content (buffer-substring
  11088. begdel (match-beginning 0)))))
  11089. (delete-region begdel (match-beginning 0))
  11090. (goto-char begdel)
  11091. (open-line 1)
  11092. params))
  11093. (defun org-map-dblocks (&optional command)
  11094. "Apply COMMAND to all dynamic blocks in the current buffer.
  11095. If COMMAND is not given, use `org-update-dblock'."
  11096. (let ((cmd (or command 'org-update-dblock)))
  11097. (save-excursion
  11098. (goto-char (point-min))
  11099. (while (re-search-forward org-dblock-start-re nil t)
  11100. (goto-char (match-beginning 0))
  11101. (save-excursion
  11102. (condition-case nil
  11103. (funcall cmd)
  11104. (error (message "Error during update of dynamic block"))))
  11105. (unless (re-search-forward org-dblock-end-re nil t)
  11106. (error "Dynamic block not terminated"))))))
  11107. (defun org-dblock-update (&optional arg)
  11108. "User command for updating dynamic blocks.
  11109. Update the dynamic block at point. With prefix ARG, update all dynamic
  11110. blocks in the buffer."
  11111. (interactive "P")
  11112. (if arg
  11113. (org-update-all-dblocks)
  11114. (or (looking-at org-dblock-start-re)
  11115. (org-beginning-of-dblock))
  11116. (org-update-dblock)))
  11117. (defun org-update-dblock ()
  11118. "Update the dynamic block at point.
  11119. This means to empty the block, parse for parameters and then call
  11120. the correct writing function."
  11121. (interactive)
  11122. (save-excursion
  11123. (let* ((win (selected-window))
  11124. (pos (point))
  11125. (line (org-current-line))
  11126. (params (org-prepare-dblock))
  11127. (name (plist-get params :name))
  11128. (indent (plist-get params :indentation-column))
  11129. (cmd (intern (concat "org-dblock-write:" name))))
  11130. (message "Updating dynamic block `%s' at line %d..." name line)
  11131. (funcall cmd params)
  11132. (message "Updating dynamic block `%s' at line %d...done" name line)
  11133. (goto-char pos)
  11134. (when (and indent (> indent 0))
  11135. (setq indent (make-string indent ?\ ))
  11136. (save-excursion
  11137. (select-window win)
  11138. (org-beginning-of-dblock)
  11139. (forward-line 1)
  11140. (while (not (looking-at org-dblock-end-re))
  11141. (insert indent)
  11142. (beginning-of-line 2))
  11143. (when (looking-at org-dblock-end-re)
  11144. (and (looking-at "[ \t]+")
  11145. (replace-match ""))
  11146. (insert indent)))))))
  11147. (defun org-beginning-of-dblock ()
  11148. "Find the beginning of the dynamic block at point.
  11149. Error if there is no such block at point."
  11150. (let ((pos (point))
  11151. beg)
  11152. (end-of-line 1)
  11153. (if (and (re-search-backward org-dblock-start-re nil t)
  11154. (setq beg (match-beginning 0))
  11155. (re-search-forward org-dblock-end-re nil t)
  11156. (> (match-end 0) pos))
  11157. (goto-char beg)
  11158. (goto-char pos)
  11159. (error "Not in a dynamic block"))))
  11160. (defun org-update-all-dblocks ()
  11161. "Update all dynamic blocks in the buffer.
  11162. This function can be used in a hook."
  11163. (interactive)
  11164. (when (derived-mode-p 'org-mode)
  11165. (org-map-dblocks 'org-update-dblock)))
  11166. ;;;; Completion
  11167. (declare-function org-export-backend-options "ox" (cl-x) t)
  11168. (defun org-get-export-keywords ()
  11169. "Return a list of all currently understood export keywords.
  11170. Export keywords include options, block names, attributes and
  11171. keywords relative to each registered export back-end."
  11172. (let (keywords)
  11173. (dolist (backend
  11174. (bound-and-true-p org-export-registered-backends)
  11175. (delq nil keywords))
  11176. ;; Back-end name (for keywords, like #+LATEX:)
  11177. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11178. (dolist (option-entry (org-export-backend-options backend))
  11179. ;; Back-end options.
  11180. (push (nth 1 option-entry) keywords)))))
  11181. (defconst org-options-keywords
  11182. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11183. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11184. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11185. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11186. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11187. (defcustom org-structure-template-alist
  11188. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11189. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11190. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11191. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11192. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11193. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11194. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11195. ("L" "#+LaTeX: ")
  11196. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11197. ("H" "#+HTML: ")
  11198. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11199. ("A" "#+ASCII: ")
  11200. ("i" "#+INDEX: ?")
  11201. ("I" "#+INCLUDE: %file ?"))
  11202. "Structure completion elements.
  11203. This is a list of abbreviation keys and values. The value gets inserted
  11204. if you type `<' followed by the key and then press the completion key,
  11205. usually `TAB'. %file will be replaced by a file name after prompting
  11206. for the file using completion. The cursor will be placed at the position
  11207. of the `?' in the template.
  11208. There are two templates for each key, the first uses the original Org syntax,
  11209. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11210. the default when the /org-mtags.el/ module has been loaded. See also the
  11211. variable `org-mtags-prefer-muse-templates'."
  11212. :group 'org-completion
  11213. :type '(repeat
  11214. (list
  11215. (string :tag "Key")
  11216. (string :tag "Template")))
  11217. :version "25.2"
  11218. :package-version '(Org . "8.3"))
  11219. (defun org-try-structure-completion ()
  11220. "Try to complete a structure template before point.
  11221. This looks for strings like \"<e\" on an otherwise empty line and
  11222. expands them."
  11223. (let ((l (buffer-substring (point-at-bol) (point)))
  11224. a)
  11225. (when (and (looking-at "[ \t]*$")
  11226. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11227. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11228. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11229. (match-beginning 1)) a)
  11230. t)))
  11231. (defun org-complete-expand-structure-template (start cell)
  11232. "Expand a structure template."
  11233. (let ((rpl (nth 1 cell))
  11234. (ind ""))
  11235. (delete-region start (point))
  11236. (when (string-match "\\`[ \t]*#\\+" rpl)
  11237. (cond
  11238. ((bolp))
  11239. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11240. (setq ind (buffer-substring (point-at-bol) (point))))
  11241. (t (newline))))
  11242. (setq start (point))
  11243. (when (string-match "%file" rpl)
  11244. (setq rpl (replace-match
  11245. (concat
  11246. "\""
  11247. (save-match-data
  11248. (abbreviate-file-name (read-file-name "Include file: ")))
  11249. "\"")
  11250. t t rpl)))
  11251. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11252. (concat "\n" ind)))
  11253. (insert rpl)
  11254. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11255. ;;;; TODO, DEADLINE, Comments
  11256. (defun org-toggle-comment ()
  11257. "Change the COMMENT state of an entry."
  11258. (interactive)
  11259. (save-excursion
  11260. (org-back-to-heading)
  11261. (let ((case-fold-search nil))
  11262. (looking-at org-complex-heading-regexp))
  11263. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11264. (skip-chars-forward " \t")
  11265. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11266. (if (org-in-commented-heading-p t)
  11267. (delete-region (point)
  11268. (progn (search-forward " " (line-end-position) 'move)
  11269. (skip-chars-forward " \t")
  11270. (point)))
  11271. (insert org-comment-string)
  11272. (unless (eolp) (insert " ")))))
  11273. (defvar org-last-todo-state-is-todo nil
  11274. "This is non-nil when the last TODO state change led to a TODO state.
  11275. If the last change removed the TODO tag or switched to DONE, then
  11276. this is nil.")
  11277. (defvar org-setting-tags nil) ; dynamically skipped
  11278. (defvar org-todo-setup-filter-hook nil
  11279. "Hook for functions that pre-filter todo specs.
  11280. Each function takes a todo spec and returns either nil or the spec
  11281. transformed into canonical form." )
  11282. (defvar org-todo-get-default-hook nil
  11283. "Hook for functions that get a default item for todo.
  11284. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11285. nil or a string to be used for the todo mark." )
  11286. (defvar org-agenda-headline-snapshot-before-repeat)
  11287. (defun org-current-effective-time ()
  11288. "Return current time adjusted for `org-extend-today-until' variable."
  11289. (let* ((ct (org-current-time))
  11290. (dct (decode-time ct))
  11291. (ct1
  11292. (cond
  11293. (org-use-last-clock-out-time-as-effective-time
  11294. (or (org-clock-get-last-clock-out-time) ct))
  11295. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11296. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11297. (t ct))))
  11298. ct1))
  11299. (defun org-todo-yesterday (&optional arg)
  11300. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11301. (interactive "P")
  11302. (if (eq major-mode 'org-agenda-mode)
  11303. (apply 'org-agenda-todo-yesterday arg)
  11304. (let* ((org-use-effective-time t)
  11305. (hour (nth 2 (decode-time (org-current-time))))
  11306. (org-extend-today-until (1+ hour)))
  11307. (org-todo arg))))
  11308. (defvar org-block-entry-blocking ""
  11309. "First entry preventing the TODO state change.")
  11310. (defun org-cancel-repeater ()
  11311. "Cancel a repeater by setting its numeric value to zero."
  11312. (interactive)
  11313. (save-excursion
  11314. (org-back-to-heading t)
  11315. (let ((bound1 (point))
  11316. (bound0 (save-excursion (outline-next-heading) (point))))
  11317. (when (and (re-search-forward
  11318. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11319. org-deadline-time-regexp "\\)\\|\\("
  11320. org-ts-regexp "\\)")
  11321. bound0 t)
  11322. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11323. bound1 t))
  11324. (replace-match "0" t nil nil 1)))))
  11325. (defvar org-state) ;; dynamically scoped into this function
  11326. (defun org-todo (&optional arg)
  11327. "Change the TODO state of an item.
  11328. The state of an item is given by a keyword at the start of the heading,
  11329. like
  11330. *** TODO Write paper
  11331. *** DONE Call mom
  11332. The different keywords are specified in the variable `org-todo-keywords'.
  11333. By default the available states are \"TODO\" and \"DONE\". So, for this
  11334. example: when the item starts with TODO, it is changed to DONE.
  11335. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11336. DONE are present, add TODO at the beginning of the heading.
  11337. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11338. state.
  11339. With numeric prefix ARG, switch to that state.
  11340. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11341. next set of TODO \
  11342. keywords (nextset).
  11343. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11344. prefix, circumvent any state blocking.
  11345. With a numeric prefix arg of 0, inhibit note taking for the change.
  11346. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11347. When called through ELisp, arg is also interpreted in the following way:
  11348. `none' -> empty state
  11349. \"\" -> switch to empty state
  11350. `done' -> switch to DONE
  11351. `nextset' -> switch to the next set of keywords
  11352. `previousset' -> switch to the previous set of keywords
  11353. \"WAITING\" -> switch to the specified keyword, but only if it
  11354. really is a member of `org-todo-keywords'."
  11355. (interactive "P")
  11356. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11357. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11358. 'region-start-level 'region))
  11359. org-loop-over-headlines-in-active-region)
  11360. (org-map-entries
  11361. `(org-todo ,arg)
  11362. org-loop-over-headlines-in-active-region
  11363. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11364. (when (equal arg '(16)) (setq arg 'nextset))
  11365. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11366. (let ((org-blocker-hook org-blocker-hook)
  11367. commentp
  11368. case-fold-search)
  11369. (when (equal arg '(64))
  11370. (setq arg nil org-blocker-hook nil))
  11371. (when (and org-blocker-hook
  11372. (or org-inhibit-blocking
  11373. (org-entry-get nil "NOBLOCKING")))
  11374. (setq org-blocker-hook nil))
  11375. (save-excursion
  11376. (catch 'exit
  11377. (org-back-to-heading t)
  11378. (when (org-in-commented-heading-p t)
  11379. (org-toggle-comment)
  11380. (setq commentp t))
  11381. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11382. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11383. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11384. (let* ((match-data (match-data))
  11385. (startpos (point-at-bol))
  11386. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11387. (org-log-done org-log-done)
  11388. (org-log-repeat org-log-repeat)
  11389. (org-todo-log-states org-todo-log-states)
  11390. (org-inhibit-logging
  11391. (if (equal arg 0)
  11392. (progn (setq arg nil) 'note) org-inhibit-logging))
  11393. (this (match-string 1))
  11394. (hl-pos (match-beginning 0))
  11395. (head (org-get-todo-sequence-head this))
  11396. (ass (assoc head org-todo-kwd-alist))
  11397. (interpret (nth 1 ass))
  11398. (done-word (nth 3 ass))
  11399. (final-done-word (nth 4 ass))
  11400. (org-last-state (or this ""))
  11401. (completion-ignore-case t)
  11402. (member (member this org-todo-keywords-1))
  11403. (tail (cdr member))
  11404. (org-state (cond
  11405. ((and org-todo-key-trigger
  11406. (or (and (equal arg '(4))
  11407. (eq org-use-fast-todo-selection 'prefix))
  11408. (and (not arg) org-use-fast-todo-selection
  11409. (not (eq org-use-fast-todo-selection
  11410. 'prefix)))))
  11411. ;; Use fast selection
  11412. (org-fast-todo-selection))
  11413. ((and (equal arg '(4))
  11414. (or (not org-use-fast-todo-selection)
  11415. (not org-todo-key-trigger)))
  11416. ;; Read a state with completion
  11417. (completing-read
  11418. "State: " (mapcar #'list org-todo-keywords-1)
  11419. nil t))
  11420. ((eq arg 'right)
  11421. (if this
  11422. (if tail (car tail) nil)
  11423. (car org-todo-keywords-1)))
  11424. ((eq arg 'left)
  11425. (unless (equal member org-todo-keywords-1)
  11426. (if this
  11427. (nth (- (length org-todo-keywords-1)
  11428. (length tail) 2)
  11429. org-todo-keywords-1)
  11430. (org-last org-todo-keywords-1))))
  11431. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11432. (setq arg nil))) ; hack to fall back to cycling
  11433. (arg
  11434. ;; user or caller requests a specific state
  11435. (cond
  11436. ((equal arg "") nil)
  11437. ((eq arg 'none) nil)
  11438. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11439. ((eq arg 'nextset)
  11440. (or (car (cdr (member head org-todo-heads)))
  11441. (car org-todo-heads)))
  11442. ((eq arg 'previousset)
  11443. (let ((org-todo-heads (reverse org-todo-heads)))
  11444. (or (car (cdr (member head org-todo-heads)))
  11445. (car org-todo-heads))))
  11446. ((car (member arg org-todo-keywords-1)))
  11447. ((stringp arg)
  11448. (user-error "State `%s' not valid in this file" arg))
  11449. ((nth (1- (prefix-numeric-value arg))
  11450. org-todo-keywords-1))))
  11451. ((null member) (or head (car org-todo-keywords-1)))
  11452. ((equal this final-done-word) nil) ;; -> make empty
  11453. ((null tail) nil) ;; -> first entry
  11454. ((memq interpret '(type priority))
  11455. (if (eq this-command last-command)
  11456. (car tail)
  11457. (if (> (length tail) 0)
  11458. (or done-word (car org-done-keywords))
  11459. nil)))
  11460. (t
  11461. (car tail))))
  11462. (org-state (or
  11463. (run-hook-with-args-until-success
  11464. 'org-todo-get-default-hook org-state org-last-state)
  11465. org-state))
  11466. (next (if org-state (concat " " org-state " ") " "))
  11467. (change-plist (list :type 'todo-state-change :from this :to org-state
  11468. :position startpos))
  11469. dolog now-done-p)
  11470. (when org-blocker-hook
  11471. (setq org-last-todo-state-is-todo
  11472. (not (member this org-done-keywords)))
  11473. (unless (save-excursion
  11474. (save-match-data
  11475. (org-with-wide-buffer
  11476. (run-hook-with-args-until-failure
  11477. 'org-blocker-hook change-plist))))
  11478. (if (called-interactively-p 'interactive)
  11479. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11480. this org-state org-block-entry-blocking)
  11481. ;; fail silently
  11482. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11483. this org-state org-block-entry-blocking)
  11484. (throw 'exit nil))))
  11485. (store-match-data match-data)
  11486. (replace-match next t t)
  11487. (cond ((equal this org-state)
  11488. (message "TODO state was already %s" (org-trim next)))
  11489. ((pos-visible-in-window-p hl-pos)
  11490. (message "TODO state changed to %s" (org-trim next))))
  11491. (unless head
  11492. (setq head (org-get-todo-sequence-head org-state)
  11493. ass (assoc head org-todo-kwd-alist)
  11494. interpret (nth 1 ass)
  11495. done-word (nth 3 ass)
  11496. final-done-word (nth 4 ass)))
  11497. (when (memq arg '(nextset previousset))
  11498. (message "Keyword-Set %d/%d: %s"
  11499. (- (length org-todo-sets) -1
  11500. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11501. (length org-todo-sets)
  11502. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11503. (setq org-last-todo-state-is-todo
  11504. (not (member org-state org-done-keywords)))
  11505. (setq now-done-p (and (member org-state org-done-keywords)
  11506. (not (member this org-done-keywords))))
  11507. (and logging (org-local-logging logging))
  11508. (when (and (or org-todo-log-states org-log-done)
  11509. (not (eq org-inhibit-logging t))
  11510. (not (memq arg '(nextset previousset))))
  11511. ;; we need to look at recording a time and note
  11512. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11513. (nth 2 (assoc this org-todo-log-states))))
  11514. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11515. (setq dolog 'time))
  11516. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11517. (and org-state
  11518. (member org-state org-not-done-keywords)
  11519. (not (member this org-not-done-keywords))))
  11520. ;; This is now a todo state and was not one before
  11521. ;; If there was a CLOSED time stamp, get rid of it.
  11522. (org-add-planning-info nil nil 'closed))
  11523. (when (and now-done-p org-log-done)
  11524. ;; It is now done, and it was not done before
  11525. (org-add-planning-info 'closed (org-current-effective-time))
  11526. (when (and (not dolog) (eq 'note org-log-done))
  11527. (org-add-log-setup 'done org-state this 'note)))
  11528. (when (and org-state dolog)
  11529. ;; This is a non-nil state, and we need to log it
  11530. (org-add-log-setup 'state org-state this dolog)))
  11531. ;; Fixup tag positioning
  11532. (org-todo-trigger-tag-changes org-state)
  11533. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11534. (when org-provide-todo-statistics
  11535. (org-update-parent-todo-statistics))
  11536. (run-hooks 'org-after-todo-state-change-hook)
  11537. (when (and arg (not (member org-state org-done-keywords)))
  11538. (setq head (org-get-todo-sequence-head org-state)))
  11539. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11540. ;; Do we need to trigger a repeat?
  11541. (when now-done-p
  11542. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11543. ;; This is for the agenda, take a snapshot of the headline.
  11544. (save-match-data
  11545. (setq org-agenda-headline-snapshot-before-repeat
  11546. (org-get-heading))))
  11547. (org-auto-repeat-maybe org-state))
  11548. ;; Fixup cursor location if close to the keyword
  11549. (when (and (outline-on-heading-p)
  11550. (not (bolp))
  11551. (save-excursion (beginning-of-line 1)
  11552. (looking-at org-todo-line-regexp))
  11553. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11554. (goto-char (or (match-end 2) (match-end 1)))
  11555. (and (looking-at " ") (just-one-space)))
  11556. (when org-trigger-hook
  11557. (save-excursion
  11558. (run-hook-with-args 'org-trigger-hook change-plist)))
  11559. (when commentp (org-toggle-comment))))))))
  11560. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11561. "Block turning an entry into a TODO, using the hierarchy.
  11562. This checks whether the current task should be blocked from state
  11563. changes. Such blocking occurs when:
  11564. 1. The task has children which are not all in a completed state.
  11565. 2. A task has a parent with the property :ORDERED:, and there
  11566. are siblings prior to the current task with incomplete
  11567. status.
  11568. 3. The parent of the task is blocked because it has siblings that should
  11569. be done first, or is child of a block grandparent TODO entry."
  11570. (if (not org-enforce-todo-dependencies)
  11571. t ; if locally turned off don't block
  11572. (catch 'dont-block
  11573. ;; If this is not a todo state change, or if this entry is already DONE,
  11574. ;; do not block
  11575. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11576. (member (plist-get change-plist :from)
  11577. (cons 'done org-done-keywords))
  11578. (member (plist-get change-plist :to)
  11579. (cons 'todo org-not-done-keywords))
  11580. (not (plist-get change-plist :to)))
  11581. (throw 'dont-block t))
  11582. ;; If this task has children, and any are undone, it's blocked
  11583. (save-excursion
  11584. (org-back-to-heading t)
  11585. (let ((this-level (funcall outline-level)))
  11586. (outline-next-heading)
  11587. (let ((child-level (funcall outline-level)))
  11588. (while (and (not (eobp))
  11589. (> child-level this-level))
  11590. ;; this todo has children, check whether they are all
  11591. ;; completed
  11592. (when (and (not (org-entry-is-done-p))
  11593. (org-entry-is-todo-p))
  11594. (setq org-block-entry-blocking (org-get-heading))
  11595. (throw 'dont-block nil))
  11596. (outline-next-heading)
  11597. (setq child-level (funcall outline-level))))))
  11598. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11599. ;; any previous siblings are undone, it's blocked
  11600. (save-excursion
  11601. (org-back-to-heading t)
  11602. (let* ((pos (point))
  11603. (parent-pos (and (org-up-heading-safe) (point)))
  11604. (case-fold-search nil))
  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 (match-string 0))
  11610. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11611. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11612. (while t
  11613. (goto-char parent-pos)
  11614. (unless (looking-at org-not-done-heading-regexp)
  11615. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11616. (setq pos (point))
  11617. (setq parent-pos (and (org-up-heading-safe) (point)))
  11618. (unless parent-pos (throw 'dont-block t)) ; no parent
  11619. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11620. (forward-line 1)
  11621. (re-search-forward org-not-done-heading-regexp pos t)
  11622. (setq org-block-entry-blocking (org-get-heading)))
  11623. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11624. (defcustom org-track-ordered-property-with-tag nil
  11625. "Should the ORDERED property also be shown as a tag?
  11626. The ORDERED property decides if an entry should require subtasks to be
  11627. completed in sequence. Since a property is not very visible, setting
  11628. this option means that toggling the ORDERED property with the command
  11629. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11630. not relevant for the behavior, but it makes things more visible.
  11631. Note that toggling the tag with tags commands will not change the property
  11632. and therefore not influence behavior!
  11633. This can be t, meaning the tag ORDERED should be used, It can also be a
  11634. string to select a different tag for this task."
  11635. :group 'org-todo
  11636. :type '(choice
  11637. (const :tag "No tracking" nil)
  11638. (const :tag "Track with ORDERED tag" t)
  11639. (string :tag "Use other tag")))
  11640. (defun org-toggle-ordered-property ()
  11641. "Toggle the ORDERED property of the current entry.
  11642. For better visibility, you can track the value of this property with a tag.
  11643. See variable `org-track-ordered-property-with-tag'."
  11644. (interactive)
  11645. (let* ((t1 org-track-ordered-property-with-tag)
  11646. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11647. (save-excursion
  11648. (org-back-to-heading)
  11649. (if (org-entry-get nil "ORDERED")
  11650. (progn
  11651. (org-delete-property "ORDERED")
  11652. (and tag (org-toggle-tag tag 'off))
  11653. (message "Subtasks can be completed in arbitrary order"))
  11654. (org-entry-put nil "ORDERED" "t")
  11655. (and tag (org-toggle-tag tag 'on))
  11656. (message "Subtasks must be completed in sequence")))))
  11657. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11658. (defun org-block-todo-from-checkboxes (change-plist)
  11659. "Block turning an entry into a TODO, using checkboxes.
  11660. This checks whether the current task should be blocked from state
  11661. changes because there are unchecked boxes in this entry."
  11662. (if (not org-enforce-todo-checkbox-dependencies)
  11663. t ; if locally turned off don't block
  11664. (catch 'dont-block
  11665. ;; If this is not a todo state change, or if this entry is already DONE,
  11666. ;; do not block
  11667. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11668. (member (plist-get change-plist :from)
  11669. (cons 'done org-done-keywords))
  11670. (member (plist-get change-plist :to)
  11671. (cons 'todo org-not-done-keywords))
  11672. (not (plist-get change-plist :to)))
  11673. (throw 'dont-block t))
  11674. ;; If this task has checkboxes that are not checked, it's blocked
  11675. (save-excursion
  11676. (org-back-to-heading t)
  11677. (let ((beg (point)) end)
  11678. (outline-next-heading)
  11679. (setq end (point))
  11680. (goto-char beg)
  11681. (when (org-list-search-forward
  11682. (concat (org-item-beginning-re)
  11683. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11684. "\\[[- ]\\]")
  11685. end t)
  11686. (when (boundp 'org-blocked-by-checkboxes)
  11687. (setq org-blocked-by-checkboxes t))
  11688. (throw 'dont-block nil))))
  11689. t))) ; do not block
  11690. (defun org-entry-blocked-p ()
  11691. "Non-nil if entry at point is blocked."
  11692. (and (not (org-entry-get nil "NOBLOCKING"))
  11693. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11694. (not (run-hook-with-args-until-failure
  11695. 'org-blocker-hook
  11696. (list :type 'todo-state-change
  11697. :position (point)
  11698. :from 'todo
  11699. :to 'done)))))
  11700. (defun org-update-statistics-cookies (all)
  11701. "Update the statistics cookie, either from TODO or from checkboxes.
  11702. This should be called with the cursor in a line with a statistics
  11703. cookie. When called with a \\[universal-argument] prefix, update
  11704. all statistics cookies in the buffer."
  11705. (interactive "P")
  11706. (if all
  11707. (progn
  11708. (org-update-checkbox-count 'all)
  11709. (org-map-entries 'org-update-parent-todo-statistics))
  11710. (if (not (org-at-heading-p))
  11711. (org-update-checkbox-count)
  11712. (let ((pos (point-marker))
  11713. end l1 l2)
  11714. (ignore-errors (org-back-to-heading t))
  11715. (if (not (org-at-heading-p))
  11716. (org-update-checkbox-count)
  11717. (setq l1 (org-outline-level))
  11718. (setq end (save-excursion
  11719. (outline-next-heading)
  11720. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11721. (point)))
  11722. (if (and (save-excursion
  11723. (re-search-forward
  11724. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11725. (not (save-excursion (re-search-forward
  11726. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11727. (org-update-checkbox-count)
  11728. (if (and l2 (> l2 l1))
  11729. (progn
  11730. (goto-char end)
  11731. (org-update-parent-todo-statistics))
  11732. (goto-char pos)
  11733. (beginning-of-line 1)
  11734. (while (re-search-forward
  11735. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11736. (point-at-eol) t)
  11737. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11738. (goto-char pos)
  11739. (move-marker pos nil)))))
  11740. (defvar org-entry-property-inherited-from) ;; defined below
  11741. (defun org-update-parent-todo-statistics ()
  11742. "Update any statistics cookie in the parent of the current headline.
  11743. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11744. the entire subtree and this will travel up the hierarchy and update
  11745. statistics everywhere."
  11746. (let* ((prop (save-excursion (org-up-heading-safe)
  11747. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11748. (recursive (or (not org-hierarchical-todo-statistics)
  11749. (and prop (string-match "\\<recursive\\>" prop))))
  11750. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11751. 0))
  11752. (first t)
  11753. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11754. level ltoggle l1 new ndel
  11755. (cnt-all 0) (cnt-done 0) is-percent kwd
  11756. checkbox-beg cookie-present)
  11757. (catch 'exit
  11758. (save-excursion
  11759. (beginning-of-line 1)
  11760. (setq ltoggle (funcall outline-level))
  11761. ;; Three situations are to consider:
  11762. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11763. ;; to the top-level ancestor on the headline;
  11764. ;; 2. If parent has "recursive" property, repeat up to the
  11765. ;; headline setting that property, taking inheritance into
  11766. ;; account;
  11767. ;; 3. Else, move up to direct parent and proceed only once.
  11768. (while (and (setq level (org-up-heading-safe))
  11769. (or recursive first)
  11770. (>= (point) lim))
  11771. (setq first nil cookie-present nil)
  11772. (unless (and level
  11773. (not (string-match
  11774. "\\<checkbox\\>"
  11775. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11776. "")))))
  11777. (throw 'exit nil))
  11778. (while (re-search-forward box-re (point-at-eol) t)
  11779. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11780. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11781. (save-match-data
  11782. (unless (outline-next-heading) (throw 'exit nil))
  11783. (while (and (looking-at org-complex-heading-regexp)
  11784. (> (setq l1 (length (match-string 1))) level))
  11785. (setq kwd (and (or recursive (= l1 ltoggle))
  11786. (match-string 2)))
  11787. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11788. (and (eq org-provide-todo-statistics t)
  11789. (or (member kwd org-done-keywords)))
  11790. (and (listp org-provide-todo-statistics)
  11791. (stringp (car org-provide-todo-statistics))
  11792. (or (member kwd org-provide-todo-statistics)
  11793. (member kwd org-done-keywords)))
  11794. (and (listp org-provide-todo-statistics)
  11795. (listp (car org-provide-todo-statistics))
  11796. (or (member kwd (car org-provide-todo-statistics))
  11797. (and (member kwd org-done-keywords)
  11798. (member kwd (cadr org-provide-todo-statistics))))))
  11799. (setq cnt-all (1+ cnt-all))
  11800. (and (eq org-provide-todo-statistics t)
  11801. kwd
  11802. (setq cnt-all (1+ cnt-all))))
  11803. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11804. (member kwd org-done-keywords))
  11805. (and (listp org-provide-todo-statistics)
  11806. (listp (car org-provide-todo-statistics))
  11807. (member kwd org-done-keywords)
  11808. (member kwd (cadr org-provide-todo-statistics)))
  11809. (and (listp org-provide-todo-statistics)
  11810. (stringp (car org-provide-todo-statistics))
  11811. (member kwd org-done-keywords)))
  11812. (setq cnt-done (1+ cnt-done)))
  11813. (outline-next-heading)))
  11814. (setq new
  11815. (if is-percent
  11816. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11817. (max 1 cnt-all)))
  11818. (format "[%d/%d]" cnt-done cnt-all))
  11819. ndel (- (match-end 0) checkbox-beg))
  11820. (goto-char checkbox-beg)
  11821. (insert new)
  11822. (delete-region (point) (+ (point) ndel))
  11823. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11824. (when cookie-present
  11825. (run-hook-with-args 'org-after-todo-statistics-hook
  11826. cnt-done (- cnt-all cnt-done))))))
  11827. (run-hooks 'org-todo-statistics-hook)))
  11828. (defvar org-after-todo-statistics-hook nil
  11829. "Hook that is called after a TODO statistics cookie has been updated.
  11830. Each function is called with two arguments: the number of not-done entries
  11831. and the number of done entries.
  11832. For example, the following function, when added to this hook, will switch
  11833. an entry to DONE when all children are done, and back to TODO when new
  11834. entries are set to a TODO status. Note that this hook is only called
  11835. when there is a statistics cookie in the headline!
  11836. (defun org-summary-todo (n-done n-not-done)
  11837. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11838. (let (org-log-done org-log-states) ; turn off logging
  11839. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11840. ")
  11841. (defvar org-todo-statistics-hook nil
  11842. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11843. This hook runs even if there is no statistics cookie present, in which case
  11844. `org-after-todo-statistics-hook' would not run.")
  11845. (defun org-todo-trigger-tag-changes (state)
  11846. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11847. (let ((l org-todo-state-tags-triggers)
  11848. changes)
  11849. (when (or (not state) (equal state ""))
  11850. (setq changes (append changes (cdr (assoc "" l)))))
  11851. (when (and (stringp state) (> (length state) 0))
  11852. (setq changes (append changes (cdr (assoc state l)))))
  11853. (when (member state org-not-done-keywords)
  11854. (setq changes (append changes (cdr (assq 'todo l)))))
  11855. (when (member state org-done-keywords)
  11856. (setq changes (append changes (cdr (assq 'done l)))))
  11857. (dolist (c changes)
  11858. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11859. (defun org-local-logging (value)
  11860. "Get logging settings from a property VALUE."
  11861. ;; Directly set the variables, they are already local.
  11862. (setq org-log-done nil
  11863. org-log-repeat nil
  11864. org-todo-log-states nil)
  11865. (dolist (w (org-split-string value))
  11866. (let (a)
  11867. (cond
  11868. ((setq a (assoc w org-startup-options))
  11869. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11870. (set (nth 1 a) (nth 2 a))))
  11871. ((setq a (org-extract-log-state-settings w))
  11872. (and (member (car a) org-todo-keywords-1)
  11873. (push a org-todo-log-states)))))))
  11874. (defun org-get-todo-sequence-head (kwd)
  11875. "Return the head of the TODO sequence to which KWD belongs.
  11876. If KWD is not set, check if there is a text property remembering the
  11877. right sequence."
  11878. (let (p)
  11879. (cond
  11880. ((not kwd)
  11881. (or (get-text-property (point-at-bol) 'org-todo-head)
  11882. (progn
  11883. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11884. nil (point-at-eol)))
  11885. (get-text-property p 'org-todo-head))))
  11886. ((not (member kwd org-todo-keywords-1))
  11887. (car org-todo-keywords-1))
  11888. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11889. (defun org-fast-todo-selection ()
  11890. "Fast TODO keyword selection with single keys.
  11891. Returns the new TODO keyword, or nil if no state change should occur."
  11892. (let* ((fulltable org-todo-key-alist)
  11893. (done-keywords org-done-keywords) ;; needed for the faces.
  11894. (maxlen (apply 'max (mapcar
  11895. (lambda (x)
  11896. (if (stringp (car x)) (string-width (car x)) 0))
  11897. fulltable)))
  11898. (expert nil)
  11899. (fwidth (+ maxlen 3 1 3))
  11900. (ncol (/ (- (window-width) 4) fwidth))
  11901. tg cnt e c tbl
  11902. groups ingroup)
  11903. (save-excursion
  11904. (save-window-excursion
  11905. (if expert
  11906. (set-buffer (get-buffer-create " *Org todo*"))
  11907. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11908. (erase-buffer)
  11909. (setq-local org-done-keywords done-keywords)
  11910. (setq tbl fulltable cnt 0)
  11911. (while (setq e (pop tbl))
  11912. (cond
  11913. ((equal e '(:startgroup))
  11914. (push '() groups) (setq ingroup t)
  11915. (unless (= cnt 0)
  11916. (setq cnt 0)
  11917. (insert "\n"))
  11918. (insert "{ "))
  11919. ((equal e '(:endgroup))
  11920. (setq ingroup nil cnt 0)
  11921. (insert "}\n"))
  11922. ((equal e '(:newline))
  11923. (unless (= cnt 0)
  11924. (setq cnt 0)
  11925. (insert "\n")
  11926. (setq e (car tbl))
  11927. (while (equal (car tbl) '(:newline))
  11928. (insert "\n")
  11929. (setq tbl (cdr tbl)))))
  11930. (t
  11931. (setq tg (car e) c (cdr e))
  11932. (when ingroup (push tg (car groups)))
  11933. (setq tg (org-add-props tg nil 'face
  11934. (org-get-todo-face tg)))
  11935. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11936. (insert "[" c "] " tg (make-string
  11937. (- fwidth 4 (length tg)) ?\ ))
  11938. (when (= (setq cnt (1+ cnt)) ncol)
  11939. (insert "\n")
  11940. (when ingroup (insert " "))
  11941. (setq cnt 0)))))
  11942. (insert "\n")
  11943. (goto-char (point-min))
  11944. (unless expert (org-fit-window-to-buffer))
  11945. (message "[a-z..]:Set [SPC]:clear")
  11946. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11947. (cond
  11948. ((or (= c ?\C-g)
  11949. (and (= c ?q) (not (rassoc c fulltable))))
  11950. (setq quit-flag t))
  11951. ((= c ?\ ) nil)
  11952. ((setq e (rassoc c fulltable) tg (car e))
  11953. tg)
  11954. (t (setq quit-flag t)))))))
  11955. (defun org-entry-is-todo-p ()
  11956. (member (org-get-todo-state) org-not-done-keywords))
  11957. (defun org-entry-is-done-p ()
  11958. (member (org-get-todo-state) org-done-keywords))
  11959. (defun org-get-todo-state ()
  11960. "Return the TODO keyword of the current subtree."
  11961. (save-excursion
  11962. (org-back-to-heading t)
  11963. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11964. (match-end 2)
  11965. (match-string 2))))
  11966. (defun org-at-date-range-p (&optional inactive-ok)
  11967. "Non-nil if point is inside a date range.
  11968. When optional argument INACTIVE-OK is non-nil, also consider
  11969. inactive time ranges.
  11970. When this function returns a non-nil value, match data is set
  11971. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11972. on INACTIVE-OK."
  11973. (interactive)
  11974. (save-excursion
  11975. (catch 'exit
  11976. (let ((pos (point)))
  11977. (skip-chars-backward "^[<\r\n")
  11978. (skip-chars-backward "<[")
  11979. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11980. (>= (match-end 0) pos)
  11981. (throw 'exit t))
  11982. (skip-chars-backward "^<[\r\n")
  11983. (skip-chars-backward "<[")
  11984. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11985. (>= (match-end 0) pos)
  11986. (throw 'exit t)))
  11987. nil)))
  11988. (defun org-get-repeat (&optional tagline)
  11989. "Check if there is a deadline/schedule with repeater in this entry."
  11990. (save-match-data
  11991. (save-excursion
  11992. (org-back-to-heading t)
  11993. (and (re-search-forward (if tagline
  11994. (concat tagline "\\s-*" org-repeat-re)
  11995. org-repeat-re)
  11996. (org-entry-end-position) t)
  11997. (match-string-no-properties 1)))))
  11998. (defvar org-last-changed-timestamp)
  11999. (defvar org-last-inserted-timestamp)
  12000. (defvar org-log-post-message)
  12001. (defvar org-log-note-purpose)
  12002. (defvar org-log-note-how nil)
  12003. (defvar org-log-note-extra)
  12004. (defun org-auto-repeat-maybe (done-word)
  12005. "Check if the current headline contains a repeated time-stamp.
  12006. If yes, set TODO state back to what it was and change the base date
  12007. of repeating deadline/scheduled time stamps to new date.
  12008. This function is run automatically after each state change to a DONE state."
  12009. (let* ((repeat (org-get-repeat))
  12010. (aa (assoc org-last-state org-todo-kwd-alist))
  12011. (interpret (nth 1 aa))
  12012. (head (nth 2 aa))
  12013. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  12014. (msg "Entry repeats: ")
  12015. (org-log-done nil)
  12016. (org-todo-log-states nil))
  12017. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  12018. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  12019. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  12020. org-todo-repeat-to-state)))
  12021. (unless (and to-state (member to-state org-todo-keywords-1))
  12022. (setq to-state (if (eq interpret 'type) org-last-state head)))
  12023. (org-todo to-state))
  12024. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  12025. (org-entry-put nil "LAST_REPEAT" (format-time-string
  12026. (org-time-stamp-format t t))))
  12027. (when org-log-repeat
  12028. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  12029. (memq 'org-add-log-note post-command-hook))
  12030. ;; We are already setup for some record.
  12031. (when (eq org-log-repeat 'note)
  12032. ;; Make sure we take a note, not only a time stamp.
  12033. (setq org-log-note-how 'note))
  12034. ;; Set up for taking a record.
  12035. (org-add-log-setup 'state
  12036. (or done-word (car org-done-keywords))
  12037. org-last-state
  12038. org-log-repeat)))
  12039. (org-back-to-heading t)
  12040. (org-add-planning-info nil nil 'closed)
  12041. (let ((end (save-excursion (outline-next-heading) (point))))
  12042. (while (re-search-forward org-ts-regexp end t)
  12043. (when (save-match-data
  12044. (or (org-at-planning-p)
  12045. (org-at-property-p)
  12046. (eq (org-element-type (save-excursion
  12047. (backward-char)
  12048. (org-element-context)))
  12049. 'timestamp)))
  12050. (let ((type (cond ((match-end 1) org-scheduled-string)
  12051. ((match-end 3) org-deadline-string)
  12052. (t "Plain:")))
  12053. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  12054. (cond
  12055. ((not
  12056. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12057. ;; Time-stamps without a repeater are usually skipped.
  12058. ;; However, a SCHEDULED time-stamp without one is
  12059. ;; removed, as it is considered as no longer relevant.
  12060. (when (equal type org-scheduled-string)
  12061. (org-remove-timestamp-with-keyword type)))
  12062. (t
  12063. (let ((n (string-to-number (match-string 2 ts)))
  12064. (what (match-string 3 ts)))
  12065. (when (equal what "w") (setq n (* n 7) what "d"))
  12066. (when (and (equal what "h")
  12067. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12068. ts)))
  12069. (user-error
  12070. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12071. has been set"
  12072. n))
  12073. ;; Preparation, see if we need to modify the start
  12074. ;; date for the change.
  12075. (when (match-end 1)
  12076. (let ((time (save-match-data (org-time-string-to-time ts))))
  12077. (cond
  12078. ((equal (match-string 1 ts) ".")
  12079. ;; Shift starting date to today
  12080. (org-timestamp-change
  12081. (- (org-today) (time-to-days time))
  12082. 'day))
  12083. ((equal (match-string 1 ts) "+")
  12084. (let ((nshiftmax 10)
  12085. (nshift 0))
  12086. (while (or (= nshift 0)
  12087. (not (time-less-p (current-time) time)))
  12088. (when (= (cl-incf nshift) nshiftmax)
  12089. (or (y-or-n-p
  12090. (format "%d repeater intervals were not \
  12091. enough to shift date past today. Continue? "
  12092. nshift))
  12093. (user-error "Abort")))
  12094. (org-timestamp-change n (cdr (assoc what whata)))
  12095. (org-at-timestamp-p t)
  12096. (setq ts (match-string 1))
  12097. (setq time
  12098. (save-match-data
  12099. (org-time-string-to-time ts)))))
  12100. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12101. ;; Rematch, so that we have everything in
  12102. ;; place for the real shift.
  12103. (org-at-timestamp-p t)
  12104. (setq ts (match-string 1))
  12105. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12106. ts)))))
  12107. (save-excursion
  12108. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12109. (setq msg
  12110. (concat
  12111. msg type " " org-last-changed-timestamp " ")))))))))
  12112. (setq org-log-post-message msg)
  12113. (message "%s" msg))))
  12114. (defun org-show-todo-tree (arg)
  12115. "Make a compact tree which shows all headlines marked with TODO.
  12116. The tree will show the lines where the regexp matches, and all higher
  12117. headlines above the match.
  12118. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12119. With a numeric prefix N, construct a sparse tree for the Nth element
  12120. of `org-todo-keywords-1'."
  12121. (interactive "P")
  12122. (let ((case-fold-search nil)
  12123. (kwd-re
  12124. (cond ((null arg) org-not-done-regexp)
  12125. ((equal arg '(4))
  12126. (let ((kwd
  12127. (completing-read "Keyword (or KWD1|KWD2|...): "
  12128. (mapcar #'list org-todo-keywords-1))))
  12129. (concat "\\("
  12130. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12131. "\\)\\>")))
  12132. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12133. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12134. org-todo-keywords-1)))
  12135. (t (user-error "Invalid prefix argument: %s" arg)))))
  12136. (message "%d TODO entries found"
  12137. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12138. (defun org-deadline (arg &optional time)
  12139. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12140. With one universal prefix argument, remove any deadline from the item.
  12141. With two universal prefix arguments, prompt for a warning delay.
  12142. With argument TIME, set the deadline at the corresponding date. TIME
  12143. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12144. (interactive "P")
  12145. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12146. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12147. 'region-start-level 'region))
  12148. org-loop-over-headlines-in-active-region)
  12149. (org-map-entries
  12150. `(org-deadline ',arg ,time)
  12151. org-loop-over-headlines-in-active-region
  12152. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12153. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12154. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12155. (repeater (and old-date
  12156. (string-match
  12157. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12158. old-date)
  12159. (match-string 1 old-date))))
  12160. (cond
  12161. ((equal arg '(4))
  12162. (when (and old-date org-log-redeadline)
  12163. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12164. (org-remove-timestamp-with-keyword org-deadline-string)
  12165. (message "Item no longer has a deadline."))
  12166. ((equal arg '(16))
  12167. (save-excursion
  12168. (org-back-to-heading t)
  12169. (if (re-search-forward
  12170. org-deadline-time-regexp
  12171. (save-excursion (outline-next-heading) (point)) t)
  12172. (let* ((rpl0 (match-string 1))
  12173. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12174. (replace-match
  12175. (concat org-deadline-string
  12176. " <" rpl
  12177. (format " -%dd"
  12178. (abs
  12179. (- (time-to-days
  12180. (save-match-data
  12181. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12182. (time-to-days old-date-time))))
  12183. ">") t t))
  12184. (user-error "No deadline information to update"))))
  12185. (t
  12186. (org-add-planning-info 'deadline time 'closed)
  12187. (when (and old-date
  12188. org-log-redeadline
  12189. (not (equal old-date org-last-inserted-timestamp)))
  12190. (org-add-log-setup
  12191. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12192. (when repeater
  12193. (save-excursion
  12194. (org-back-to-heading t)
  12195. (when (re-search-forward (concat org-deadline-string " "
  12196. org-last-inserted-timestamp)
  12197. (save-excursion
  12198. (outline-next-heading) (point)) t)
  12199. (goto-char (1- (match-end 0)))
  12200. (insert " " repeater)
  12201. (setq org-last-inserted-timestamp
  12202. (concat (substring org-last-inserted-timestamp 0 -1)
  12203. " " repeater
  12204. (substring org-last-inserted-timestamp -1))))))
  12205. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12206. (defun org-schedule (arg &optional time)
  12207. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12208. With one universal prefix argument, remove any scheduling date from the item.
  12209. With two universal prefix arguments, prompt for a delay cookie.
  12210. With argument TIME, scheduled at the corresponding date. TIME can
  12211. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12212. (interactive "P")
  12213. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12214. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12215. 'region-start-level 'region))
  12216. org-loop-over-headlines-in-active-region)
  12217. (org-map-entries
  12218. `(org-schedule ',arg ,time)
  12219. org-loop-over-headlines-in-active-region
  12220. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12221. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12222. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12223. (repeater (and old-date
  12224. (string-match
  12225. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12226. old-date)
  12227. (match-string 1 old-date))))
  12228. (cond
  12229. ((equal arg '(4))
  12230. (progn
  12231. (when (and old-date org-log-reschedule)
  12232. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12233. (org-remove-timestamp-with-keyword org-scheduled-string)
  12234. (message "Item is no longer scheduled.")))
  12235. ((equal arg '(16))
  12236. (save-excursion
  12237. (org-back-to-heading t)
  12238. (if (re-search-forward
  12239. org-scheduled-time-regexp
  12240. (save-excursion (outline-next-heading) (point)) t)
  12241. (let* ((rpl0 (match-string 1))
  12242. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12243. (replace-match
  12244. (concat org-scheduled-string
  12245. " <" rpl
  12246. (format " -%dd"
  12247. (abs
  12248. (- (time-to-days
  12249. (save-match-data
  12250. (org-read-date nil t nil "Delay until" old-date-time)))
  12251. (time-to-days old-date-time))))
  12252. ">") t t))
  12253. (user-error "No scheduled information to update"))))
  12254. (t
  12255. (org-add-planning-info 'scheduled time 'closed)
  12256. (when (and old-date
  12257. org-log-reschedule
  12258. (not (equal old-date org-last-inserted-timestamp)))
  12259. (org-add-log-setup
  12260. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12261. (when repeater
  12262. (save-excursion
  12263. (org-back-to-heading t)
  12264. (when (re-search-forward (concat org-scheduled-string " "
  12265. org-last-inserted-timestamp)
  12266. (save-excursion
  12267. (outline-next-heading) (point)) t)
  12268. (goto-char (1- (match-end 0)))
  12269. (insert " " repeater)
  12270. (setq org-last-inserted-timestamp
  12271. (concat (substring org-last-inserted-timestamp 0 -1)
  12272. " " repeater
  12273. (substring org-last-inserted-timestamp -1))))))
  12274. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12275. (defun org-get-scheduled-time (pom &optional inherit)
  12276. "Get the scheduled time as a time tuple, of a format suitable
  12277. for calling org-schedule with, or if there is no scheduling,
  12278. returns nil."
  12279. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12280. (when time
  12281. (apply 'encode-time (org-parse-time-string time)))))
  12282. (defun org-get-deadline-time (pom &optional inherit)
  12283. "Get the deadline as a time tuple, of a format suitable for
  12284. calling org-deadline with, or if there is no scheduling, returns
  12285. nil."
  12286. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12287. (when time
  12288. (apply 'encode-time (org-parse-time-string time)))))
  12289. (defun org-remove-timestamp-with-keyword (keyword)
  12290. "Remove all time stamps with KEYWORD in the current entry."
  12291. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12292. beg)
  12293. (save-excursion
  12294. (org-back-to-heading t)
  12295. (setq beg (point))
  12296. (outline-next-heading)
  12297. (while (re-search-backward re beg t)
  12298. (replace-match "")
  12299. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12300. (equal (char-before) ?\ ))
  12301. (backward-delete-char 1)
  12302. (when (string-match "^[ \t]*$" (buffer-substring
  12303. (point-at-bol) (point-at-eol)))
  12304. (delete-region (point-at-bol)
  12305. (min (point-max) (1+ (point-at-eol))))))))))
  12306. (defvar org-time-was-given) ; dynamically scoped parameter
  12307. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12308. (defun org-at-planning-p ()
  12309. "Non-nil when point is on a planning info line."
  12310. ;; This is as accurate and faster than `org-element-at-point' since
  12311. ;; planning info location is fixed in the section.
  12312. (org-with-wide-buffer
  12313. (beginning-of-line)
  12314. (and (looking-at-p org-planning-line-re)
  12315. (eq (point)
  12316. (ignore-errors
  12317. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12318. (org-back-to-heading t)
  12319. (org-with-limited-levels (org-back-to-heading t)))
  12320. (line-beginning-position 2))))))
  12321. (defun org-add-planning-info (what &optional time &rest remove)
  12322. "Insert new timestamp with keyword in the planning line.
  12323. WHAT indicates what kind of time stamp to add. It is a symbol
  12324. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12325. the time to use. If none is given, the user is prompted for
  12326. a date. REMOVE indicates what kind of entries to remove. An old
  12327. WHAT entry will also be removed."
  12328. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12329. (catch 'exit
  12330. (when (and (memq what '(scheduled deadline))
  12331. (or (not time)
  12332. (and (stringp time)
  12333. (string-match "^[-+]+[0-9]" time))))
  12334. ;; Try to get a default date/time from existing timestamp
  12335. (save-excursion
  12336. (org-back-to-heading t)
  12337. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12338. (when (re-search-forward (if (eq what 'scheduled)
  12339. org-scheduled-time-regexp
  12340. org-deadline-time-regexp)
  12341. end t)
  12342. (setq ts (match-string 1)
  12343. default-time (apply 'encode-time (org-parse-time-string ts))
  12344. default-input (and ts (org-get-compact-tod ts)))))))
  12345. (when what
  12346. (setq time
  12347. (if (stringp time)
  12348. ;; This is a string (relative or absolute), set
  12349. ;; proper date.
  12350. (apply #'encode-time
  12351. (org-read-date-analyze
  12352. time default-time (decode-time default-time)))
  12353. ;; If necessary, get the time from the user
  12354. (or time (org-read-date nil 'to-time nil nil
  12355. default-time default-input)))))
  12356. (org-with-wide-buffer
  12357. (org-back-to-heading t)
  12358. (forward-line)
  12359. (unless (bolp) (insert "\n"))
  12360. (cond ((looking-at-p org-planning-line-re)
  12361. ;; Move to current indentation.
  12362. (skip-chars-forward " \t")
  12363. ;; Check if we have to remove something.
  12364. (dolist (type (if what (cons what remove) remove))
  12365. (save-excursion
  12366. (when (re-search-forward
  12367. (cl-case type
  12368. (closed org-closed-time-regexp)
  12369. (deadline org-deadline-time-regexp)
  12370. (scheduled org-scheduled-time-regexp)
  12371. (otherwise
  12372. (error "Invalid planning type: %s" type)))
  12373. (line-end-position) t)
  12374. ;; Delete until next keyword or end of line.
  12375. (delete-region
  12376. (match-beginning 0)
  12377. (if (re-search-forward org-keyword-time-not-clock-regexp
  12378. (line-end-position)
  12379. t)
  12380. (match-beginning 0)
  12381. (line-end-position))))))
  12382. ;; If there is nothing more to add and no more keyword
  12383. ;; is left, remove the line completely.
  12384. (if (and (looking-at-p "[ \t]*$") (not what))
  12385. (delete-region (line-beginning-position)
  12386. (line-beginning-position 2))
  12387. ;; If we removed last keyword, do not leave trailing
  12388. ;; white space at the end of line.
  12389. (let ((p (point)))
  12390. (save-excursion
  12391. (end-of-line)
  12392. (unless (= (skip-chars-backward " \t" p) 0)
  12393. (delete-region (point) (line-end-position)))))))
  12394. ((not what) (throw 'exit nil)) ; Nothing to do.
  12395. (t (insert-before-markers "\n")
  12396. (backward-char 1)
  12397. (when org-adapt-indentation
  12398. (indent-to-column (1+ (org-outline-level))))))
  12399. (when what
  12400. ;; Insert planning keyword.
  12401. (insert (cl-case what
  12402. (closed org-closed-string)
  12403. (deadline org-deadline-string)
  12404. (scheduled org-scheduled-string)
  12405. (otherwise (error "Invalid planning type: %s" what)))
  12406. " ")
  12407. ;; Insert associated timestamp.
  12408. (let ((ts (org-insert-time-stamp
  12409. time
  12410. (or org-time-was-given
  12411. (and (eq what 'closed) org-log-done-with-time))
  12412. (eq what 'closed)
  12413. nil nil (list org-end-time-was-given))))
  12414. (unless (eolp) (insert " "))
  12415. ts))))))
  12416. (defvar org-log-note-marker (make-marker)
  12417. "Marker pointing at the entry where the note is to be inserted.")
  12418. (defvar org-log-note-purpose nil)
  12419. (defvar org-log-note-state nil)
  12420. (defvar org-log-note-previous-state nil)
  12421. (defvar org-log-note-extra nil)
  12422. (defvar org-log-note-window-configuration nil)
  12423. (defvar org-log-note-return-to (make-marker))
  12424. (defvar org-log-note-effective-time nil
  12425. "Remembered current time so that dynamically scoped
  12426. `org-extend-today-until' affects timestamps in state change log")
  12427. (defvar org-log-post-message nil
  12428. "Message to be displayed after a log note has been stored.
  12429. The auto-repeater uses this.")
  12430. (defun org-add-note ()
  12431. "Add a note to the current entry.
  12432. This is done in the same way as adding a state change note."
  12433. (interactive)
  12434. (org-add-log-setup 'note))
  12435. (defun org-log-beginning (&optional create)
  12436. "Return expected start of log notes in current entry.
  12437. When optional argument CREATE is non-nil, the function creates
  12438. a drawer to store notes, if necessary. Returned position ignores
  12439. narrowing."
  12440. (org-with-wide-buffer
  12441. (let ((drawer (org-log-into-drawer)))
  12442. (cond
  12443. (drawer
  12444. (org-end-of-meta-data)
  12445. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12446. (end (if (org-at-heading-p) (point)
  12447. (save-excursion (outline-next-heading) (point))))
  12448. (case-fold-search t))
  12449. (catch 'exit
  12450. ;; Try to find existing drawer.
  12451. (while (re-search-forward regexp end t)
  12452. (let ((element (org-element-at-point)))
  12453. (when (eq (org-element-type element) 'drawer)
  12454. (let ((cend (org-element-property :contents-end element)))
  12455. (when (and (not org-log-states-order-reversed) cend)
  12456. (goto-char cend)))
  12457. (throw 'exit nil))))
  12458. ;; No drawer found. Create one, if permitted.
  12459. (when create
  12460. (unless (bolp) (insert "\n"))
  12461. (let ((beg (point)))
  12462. (insert ":" drawer ":\n:END:\n")
  12463. (org-indent-region beg (point)))
  12464. (end-of-line -1)))))
  12465. (t
  12466. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12467. (skip-chars-forward " \t\n")
  12468. (beginning-of-line)
  12469. (unless org-log-states-order-reversed
  12470. (org-skip-over-state-notes)
  12471. (skip-chars-backward " \t\n")
  12472. (forward-line)))))
  12473. (if (bolp) (point) (line-beginning-position 2))))
  12474. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12475. "Set up the post command hook to take a note.
  12476. If this is about to TODO state change, the new state is expected in STATE.
  12477. HOW is an indicator what kind of note should be created.
  12478. EXTRA is additional text that will be inserted into the notes buffer."
  12479. (move-marker org-log-note-marker (point))
  12480. (setq org-log-note-purpose purpose
  12481. org-log-note-state state
  12482. org-log-note-previous-state prev-state
  12483. org-log-note-how how
  12484. org-log-note-extra extra
  12485. org-log-note-effective-time (org-current-effective-time))
  12486. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12487. (defun org-skip-over-state-notes ()
  12488. "Skip past the list of State notes in an entry."
  12489. (when (ignore-errors (goto-char (org-in-item-p)))
  12490. (let* ((struct (org-list-struct))
  12491. (prevs (org-list-prevs-alist struct))
  12492. (regexp
  12493. (concat "[ \t]*- +"
  12494. (replace-regexp-in-string
  12495. " +" " +"
  12496. (org-replace-escapes
  12497. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12498. `(("%d" . ,org-ts-regexp-inactive)
  12499. ("%D" . ,org-ts-regexp)
  12500. ("%s" . "\"\\S-+\"")
  12501. ("%S" . "\"\\S-+\"")
  12502. ("%t" . ,org-ts-regexp-inactive)
  12503. ("%T" . ,org-ts-regexp)
  12504. ("%u" . ".*?")
  12505. ("%U" . ".*?")))))))
  12506. (while (looking-at-p regexp)
  12507. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12508. (org-list-get-item-end (point) struct)))))))
  12509. (defun org-add-log-note (&optional _purpose)
  12510. "Pop up a window for taking a note, and add this note later."
  12511. (remove-hook 'post-command-hook 'org-add-log-note)
  12512. (setq org-log-note-window-configuration (current-window-configuration))
  12513. (delete-other-windows)
  12514. (move-marker org-log-note-return-to (point))
  12515. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12516. (goto-char org-log-note-marker)
  12517. (org-switch-to-buffer-other-window "*Org Note*")
  12518. (erase-buffer)
  12519. (if (memq org-log-note-how '(time state))
  12520. (let (current-prefix-arg) (org-store-log-note))
  12521. (let ((org-inhibit-startup t)) (org-mode))
  12522. (insert (format "# Insert note for %s.
  12523. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12524. (cond
  12525. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12526. ((eq org-log-note-purpose 'done) "closed todo item")
  12527. ((eq org-log-note-purpose 'state)
  12528. (format "state change from \"%s\" to \"%s\""
  12529. (or org-log-note-previous-state "")
  12530. (or org-log-note-state "")))
  12531. ((eq org-log-note-purpose 'reschedule)
  12532. "rescheduling")
  12533. ((eq org-log-note-purpose 'delschedule)
  12534. "no longer scheduled")
  12535. ((eq org-log-note-purpose 'redeadline)
  12536. "changing deadline")
  12537. ((eq org-log-note-purpose 'deldeadline)
  12538. "removing deadline")
  12539. ((eq org-log-note-purpose 'refile)
  12540. "refiling")
  12541. ((eq org-log-note-purpose 'note)
  12542. "this entry")
  12543. (t (error "This should not happen")))))
  12544. (when org-log-note-extra (insert org-log-note-extra))
  12545. (setq-local org-finish-function 'org-store-log-note)
  12546. (run-hooks 'org-log-buffer-setup-hook)))
  12547. (defvar org-note-abort nil) ; dynamically scoped
  12548. (defun org-store-log-note ()
  12549. "Finish taking a log note, and insert it to where it belongs."
  12550. (let ((txt (prog1 (buffer-string)
  12551. (kill-buffer)))
  12552. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12553. lines)
  12554. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12555. (setq txt (replace-match "" t t txt)))
  12556. (when (string-match "\\s-+\\'" txt)
  12557. (setq txt (replace-match "" t t txt)))
  12558. (setq lines (org-split-string txt "\n"))
  12559. (when (org-string-nw-p note)
  12560. (setq note
  12561. (org-replace-escapes
  12562. note
  12563. (list (cons "%u" (user-login-name))
  12564. (cons "%U" user-full-name)
  12565. (cons "%t" (format-time-string
  12566. (org-time-stamp-format 'long 'inactive)
  12567. org-log-note-effective-time))
  12568. (cons "%T" (format-time-string
  12569. (org-time-stamp-format 'long nil)
  12570. org-log-note-effective-time))
  12571. (cons "%d" (format-time-string
  12572. (org-time-stamp-format nil 'inactive)
  12573. org-log-note-effective-time))
  12574. (cons "%D" (format-time-string
  12575. (org-time-stamp-format nil nil)
  12576. org-log-note-effective-time))
  12577. (cons "%s" (cond
  12578. ((not org-log-note-state) "")
  12579. ((string-match-p org-ts-regexp
  12580. org-log-note-state)
  12581. (format "\"[%s]\""
  12582. (substring org-log-note-state 1 -1)))
  12583. (t (format "\"%s\"" org-log-note-state))))
  12584. (cons "%S"
  12585. (cond
  12586. ((not org-log-note-previous-state) "")
  12587. ((string-match-p org-ts-regexp
  12588. org-log-note-previous-state)
  12589. (format "\"[%s]\""
  12590. (substring
  12591. org-log-note-previous-state 1 -1)))
  12592. (t (format "\"%s\""
  12593. org-log-note-previous-state)))))))
  12594. (when lines (setq note (concat note " \\\\")))
  12595. (push note lines))
  12596. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12597. (with-current-buffer (marker-buffer org-log-note-marker)
  12598. (org-with-wide-buffer
  12599. ;; Find location for the new note.
  12600. (goto-char org-log-note-marker)
  12601. (set-marker org-log-note-marker nil)
  12602. (goto-char (org-log-beginning t))
  12603. ;; Make sure point is at the beginning of an empty line.
  12604. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12605. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12606. ;; In an existing list, add a new item at the top level.
  12607. ;; Otherwise, indent line like a regular one.
  12608. (let ((itemp (org-in-item-p)))
  12609. (if itemp
  12610. (indent-line-to
  12611. (let ((struct (save-excursion
  12612. (goto-char itemp) (org-list-struct))))
  12613. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12614. (org-indent-line)))
  12615. (insert (org-list-bullet-string "-") (pop lines))
  12616. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12617. (dolist (line lines)
  12618. (insert "\n")
  12619. (indent-line-to ind)
  12620. (insert line)))
  12621. (message "Note stored")
  12622. (org-back-to-heading t)
  12623. (org-cycle-hide-drawers 'children))
  12624. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12625. ;; from within `org-add-log-note' because `buffer-undo-list'
  12626. ;; is then modified outside of `org-with-remote-undo'.
  12627. (when (eq this-command 'org-agenda-todo)
  12628. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12629. ;; Don't add undo information when called from `org-agenda-todo'.
  12630. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12631. (set-window-configuration org-log-note-window-configuration)
  12632. (with-current-buffer (marker-buffer org-log-note-return-to)
  12633. (goto-char org-log-note-return-to))
  12634. (move-marker org-log-note-return-to nil)
  12635. (when org-log-post-message (message "%s" org-log-post-message))))
  12636. (defun org-remove-empty-drawer-at (pos)
  12637. "Remove an empty drawer at position POS.
  12638. POS may also be a marker."
  12639. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12640. (org-with-wide-buffer
  12641. (goto-char pos)
  12642. (let ((drawer (org-element-at-point)))
  12643. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12644. (not (org-element-property :contents-begin drawer)))
  12645. (delete-region (org-element-property :begin drawer)
  12646. (progn (goto-char (org-element-property :end drawer))
  12647. (skip-chars-backward " \r\t\n")
  12648. (forward-line)
  12649. (point))))))))
  12650. (defvar org-ts-type nil)
  12651. (defun org-sparse-tree (&optional arg type)
  12652. "Create a sparse tree, prompt for the details.
  12653. This command can create sparse trees. You first need to select the type
  12654. of match used to create the tree:
  12655. t Show all TODO entries.
  12656. T Show entries with a specific TODO keyword.
  12657. m Show entries selected by a tags/property match.
  12658. p Enter a property name and its value (both with completion on existing
  12659. names/values) and show entries with that property.
  12660. r Show entries matching a regular expression (`/' can be used as well).
  12661. b Show deadlines and scheduled items before a date.
  12662. a Show deadlines and scheduled items after a date.
  12663. d Show deadlines due within `org-deadline-warning-days'.
  12664. D Show deadlines and scheduled items between a date range."
  12665. (interactive "P")
  12666. (setq type (or type org-sparse-tree-default-date-type))
  12667. (setq org-ts-type type)
  12668. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12669. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12670. \[c]ycle through date types: %s"
  12671. (cl-case type
  12672. (all "all timestamps")
  12673. (scheduled "only scheduled")
  12674. (deadline "only deadline")
  12675. (active "only active timestamps")
  12676. (inactive "only inactive timestamps")
  12677. (closed "with a closed time-stamp")
  12678. (otherwise "scheduled/deadline")))
  12679. (let ((answer (read-char-exclusive)))
  12680. (cl-case answer
  12681. (?c
  12682. (org-sparse-tree
  12683. arg
  12684. (cadr
  12685. (memq type '(nil all scheduled deadline active inactive closed)))))
  12686. (?d (call-interactively 'org-check-deadlines))
  12687. (?b (call-interactively 'org-check-before-date))
  12688. (?a (call-interactively 'org-check-after-date))
  12689. (?D (call-interactively 'org-check-dates-range))
  12690. (?t (call-interactively 'org-show-todo-tree))
  12691. (?T (org-show-todo-tree '(4)))
  12692. (?m (call-interactively 'org-match-sparse-tree))
  12693. ((?p ?P)
  12694. (let* ((kwd (completing-read
  12695. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12696. (value (completing-read
  12697. "Value: " (mapcar #'list (org-property-values kwd)))))
  12698. (unless (string-match "\\`{.*}\\'" value)
  12699. (setq value (concat "\"" value "\"")))
  12700. (org-match-sparse-tree arg (concat kwd "=" value))))
  12701. ((?r ?R ?/) (call-interactively 'org-occur))
  12702. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12703. (defvar-local org-occur-highlights nil
  12704. "List of overlays used for occur matches.")
  12705. (defvar-local org-occur-parameters nil
  12706. "Parameters of the active org-occur calls.
  12707. This is a list, each call to org-occur pushes as cons cell,
  12708. containing the regular expression and the callback, onto the list.
  12709. The list can contain several entries if `org-occur' has been called
  12710. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12711. will only contain one set of parameters. When the highlights are
  12712. removed (for example with `C-c C-c', or with the next edit (depending
  12713. on `org-remove-highlights-with-change'), this variable is emptied
  12714. as well.")
  12715. (defun org-occur (regexp &optional keep-previous callback)
  12716. "Make a compact tree which shows all matches of REGEXP.
  12717. The tree will show the lines where the regexp matches, and any other context
  12718. defined in `org-show-context-detail', which see.
  12719. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12720. done by a previous call to `org-occur' will be kept, to allow stacking of
  12721. calls to this command.
  12722. Optional argument CALLBACK can be a function of no argument. In this case,
  12723. it is called with point at the end of the match, match data being set
  12724. accordingly. Current match is shown only if the return value is non-nil.
  12725. The function must neither move point nor alter narrowing."
  12726. (interactive "sRegexp: \nP")
  12727. (when (equal regexp "")
  12728. (user-error "Regexp cannot be empty"))
  12729. (unless keep-previous
  12730. (org-remove-occur-highlights nil nil t))
  12731. (push (cons regexp callback) org-occur-parameters)
  12732. (let ((cnt 0))
  12733. (save-excursion
  12734. (goto-char (point-min))
  12735. (when (or (not keep-previous) ; do not want to keep
  12736. (not org-occur-highlights)) ; no previous matches
  12737. ;; hide everything
  12738. (org-overview))
  12739. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12740. (isearch-no-upper-case-p regexp t)
  12741. org-occur-case-fold-search)))
  12742. (while (re-search-forward regexp nil t)
  12743. (when (or (not callback)
  12744. (save-match-data (funcall callback)))
  12745. (setq cnt (1+ cnt))
  12746. (when org-highlight-sparse-tree-matches
  12747. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12748. (org-show-context 'occur-tree)))))
  12749. (when org-remove-highlights-with-change
  12750. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12751. nil 'local))
  12752. (unless org-sparse-tree-open-archived-trees
  12753. (org-hide-archived-subtrees (point-min) (point-max)))
  12754. (run-hooks 'org-occur-hook)
  12755. (when (called-interactively-p 'interactive)
  12756. (message "%d match(es) for regexp %s" cnt regexp))
  12757. cnt))
  12758. (defun org-occur-next-match (&optional n _reset)
  12759. "Function for `next-error-function' to find sparse tree matches.
  12760. N is the number of matches to move, when negative move backwards.
  12761. This function always goes back to the starting point when no
  12762. match is found."
  12763. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12764. (search-func (if (< n 0)
  12765. 'previous-single-char-property-change
  12766. 'next-single-char-property-change))
  12767. (n (abs n))
  12768. (pos (point))
  12769. p1)
  12770. (catch 'exit
  12771. (while (setq p1 (funcall search-func (point) 'org-type))
  12772. (when (equal p1 limit)
  12773. (goto-char pos)
  12774. (user-error "No more matches"))
  12775. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12776. (setq n (1- n))
  12777. (when (= n 0)
  12778. (goto-char p1)
  12779. (throw 'exit (point))))
  12780. (goto-char p1))
  12781. (goto-char p1)
  12782. (user-error "No more matches"))))
  12783. (defun org-show-context (&optional key)
  12784. "Make sure point and context are visible.
  12785. Optional argument KEY, when non-nil, is a symbol. See
  12786. `org-show-context-detail' for allowed values and how much is to
  12787. be shown."
  12788. (org-show-set-visibility
  12789. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12790. ((cdr (assq key org-show-context-detail)))
  12791. (t (cdr (assq 'default org-show-context-detail))))))
  12792. (defun org-show-set-visibility (detail)
  12793. "Set visibility around point according to DETAIL.
  12794. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12795. `tree', `canonical' or t. See `org-show-context-detail' for more
  12796. information."
  12797. ;; Show current heading and possibly its entry, following headline
  12798. ;; or all children.
  12799. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12800. (org-flag-heading nil)
  12801. (org-show-entry)
  12802. ;; If point is hidden within a drawer or a block, make sure to
  12803. ;; expose it.
  12804. (dolist (o (overlays-at (point)))
  12805. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12806. (delete-overlay o)))
  12807. (unless (org-before-first-heading-p)
  12808. (org-with-limited-levels
  12809. (cl-case detail
  12810. ((tree canonical t) (org-show-children))
  12811. ((nil minimal ancestors))
  12812. (t (save-excursion
  12813. (outline-next-heading)
  12814. (org-flag-heading nil)))))))
  12815. ;; Show all siblings.
  12816. (when (eq detail 'lineage) (org-show-siblings))
  12817. ;; Show ancestors, possibly with their children.
  12818. (when (memq detail '(ancestors lineage tree canonical t))
  12819. (save-excursion
  12820. (while (org-up-heading-safe)
  12821. (org-flag-heading nil)
  12822. (when (memq detail '(canonical t)) (org-show-entry))
  12823. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12824. (defvar org-reveal-start-hook nil
  12825. "Hook run before revealing a location.")
  12826. (defun org-reveal (&optional siblings)
  12827. "Show current entry, hierarchy above it, and the following headline.
  12828. This can be used to show a consistent set of context around
  12829. locations exposed with `org-show-context'.
  12830. With optional argument SIBLINGS, on each level of the hierarchy all
  12831. siblings are shown. This repairs the tree structure to what it would
  12832. look like when opened with hierarchical calls to `org-cycle'.
  12833. With a \\[universal-argument] \\[universal-argument] prefix, \
  12834. go to the parent and show the entire tree."
  12835. (interactive "P")
  12836. (run-hooks 'org-reveal-start-hook)
  12837. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12838. ((equal siblings '(16))
  12839. (save-excursion
  12840. (when (org-up-heading-safe)
  12841. (org-show-subtree)
  12842. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12843. (t (org-show-set-visibility 'lineage))))
  12844. (defun org-highlight-new-match (beg end)
  12845. "Highlight from BEG to END and mark the highlight is an occur headline."
  12846. (let ((ov (make-overlay beg end)))
  12847. (overlay-put ov 'face 'secondary-selection)
  12848. (overlay-put ov 'org-type 'org-occur)
  12849. (push ov org-occur-highlights)))
  12850. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12851. "Remove the occur highlights from the buffer.
  12852. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12853. from the `before-change-functions' in the current buffer."
  12854. (interactive)
  12855. (unless org-inhibit-highlight-removal
  12856. (mapc #'delete-overlay org-occur-highlights)
  12857. (setq org-occur-highlights nil)
  12858. (setq org-occur-parameters nil)
  12859. (unless noremove
  12860. (remove-hook 'before-change-functions
  12861. 'org-remove-occur-highlights 'local))))
  12862. ;;;; Priorities
  12863. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12864. "Regular expression matching the priority indicator.")
  12865. (defvar org-remove-priority-next-time nil)
  12866. (defun org-priority-up ()
  12867. "Increase the priority of the current item."
  12868. (interactive)
  12869. (org-priority 'up))
  12870. (defun org-priority-down ()
  12871. "Decrease the priority of the current item."
  12872. (interactive)
  12873. (org-priority 'down))
  12874. (defun org-priority (&optional action _show)
  12875. "Change the priority of an item.
  12876. ACTION can be `set', `up', `down', or a character."
  12877. (interactive "P")
  12878. (if (equal action '(4))
  12879. (org-show-priority)
  12880. (unless org-enable-priority-commands
  12881. (user-error "Priority commands are disabled"))
  12882. (setq action (or action 'set))
  12883. (let (current new news have remove)
  12884. (save-excursion
  12885. (org-back-to-heading t)
  12886. (when (looking-at org-priority-regexp)
  12887. (setq current (string-to-char (match-string 2))
  12888. have t))
  12889. (cond
  12890. ((eq action 'remove)
  12891. (setq remove t new ?\ ))
  12892. ((or (eq action 'set)
  12893. (integerp action))
  12894. (if (not (eq action 'set))
  12895. (setq new action)
  12896. (message "Priority %c-%c, SPC to remove: "
  12897. org-highest-priority org-lowest-priority)
  12898. (save-match-data
  12899. (setq new (read-char-exclusive))))
  12900. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12901. (= (upcase org-lowest-priority) org-lowest-priority))
  12902. (setq new (upcase new)))
  12903. (cond ((equal new ?\ ) (setq remove t))
  12904. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12905. (user-error "Priority must be between `%c' and `%c'"
  12906. org-highest-priority org-lowest-priority))))
  12907. ((eq action 'up)
  12908. (setq new (if have
  12909. (1- current) ; normal cycling
  12910. ;; last priority was empty
  12911. (if (eq last-command this-command)
  12912. org-lowest-priority ; wrap around empty to lowest
  12913. ;; default
  12914. (if org-priority-start-cycle-with-default
  12915. org-default-priority
  12916. (1- org-default-priority))))))
  12917. ((eq action 'down)
  12918. (setq new (if have
  12919. (1+ current) ; normal cycling
  12920. ;; last priority was empty
  12921. (if (eq last-command this-command)
  12922. org-highest-priority ; wrap around empty to highest
  12923. ;; default
  12924. (if org-priority-start-cycle-with-default
  12925. org-default-priority
  12926. (1+ org-default-priority))))))
  12927. (t (user-error "Invalid action")))
  12928. (when (or (< (upcase new) org-highest-priority)
  12929. (> (upcase new) org-lowest-priority))
  12930. (if (and (memq action '(up down))
  12931. (not have) (not (eq last-command this-command)))
  12932. ;; `new' is from default priority
  12933. (error
  12934. "The default can not be set, see `org-default-priority' why")
  12935. ;; normal cycling: `new' is beyond highest/lowest priority
  12936. ;; and is wrapped around to the empty priority
  12937. (setq remove t)))
  12938. (setq news (format "%c" new))
  12939. (if have
  12940. (if remove
  12941. (replace-match "" t t nil 1)
  12942. (replace-match news t t nil 2))
  12943. (if remove
  12944. (user-error "No priority cookie found in line")
  12945. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12946. (if (match-end 2)
  12947. (progn
  12948. (goto-char (match-end 2))
  12949. (insert " [#" news "]"))
  12950. (goto-char (match-beginning 3))
  12951. (insert "[#" news "] "))))
  12952. (org-set-tags nil 'align))
  12953. (if remove
  12954. (message "Priority removed")
  12955. (message "Priority of current item set to %s" news)))))
  12956. (defun org-show-priority ()
  12957. "Show the priority of the current item.
  12958. This priority is composed of the main priority given with the [#A] cookies,
  12959. and by additional input from the age of a schedules or deadline entry."
  12960. (interactive)
  12961. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12962. (org-get-at-bol 'priority)
  12963. (save-excursion
  12964. (save-match-data
  12965. (beginning-of-line)
  12966. (and (looking-at org-heading-regexp)
  12967. (org-get-priority (match-string 0))))))))
  12968. (message "Priority is %d" (if pri pri -1000))))
  12969. (defun org-get-priority (s)
  12970. "Find priority cookie and return priority."
  12971. (save-match-data
  12972. (if (functionp org-get-priority-function)
  12973. (funcall org-get-priority-function)
  12974. (if (not (string-match org-priority-regexp s))
  12975. (* 1000 (- org-lowest-priority org-default-priority))
  12976. (* 1000 (- org-lowest-priority
  12977. (string-to-char (match-string 2 s))))))))
  12978. ;;;; Tags
  12979. (defvar org-agenda-archives-mode)
  12980. (defvar org-map-continue-from nil
  12981. "Position from where mapping should continue.
  12982. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12983. (defvar org-scanner-tags nil
  12984. "The current tag list while the tags scanner is running.")
  12985. (defvar org-trust-scanner-tags nil
  12986. "Should `org-get-tags-at' use the tags for the scanner.
  12987. This is for internal dynamical scoping only.
  12988. When this is non-nil, the function `org-get-tags-at' will return the value
  12989. of `org-scanner-tags' instead of building the list by itself. This
  12990. can lead to large speed-ups when the tags scanner is used in a file with
  12991. many entries, and when the list of tags is retrieved, for example to
  12992. obtain a list of properties. Building the tags list for each entry in such
  12993. a file becomes an N^2 operation - but with this variable set, it scales
  12994. as N.")
  12995. (defvar org--matcher-tags-todo-only nil)
  12996. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12997. "Scan headline tags with inheritance and produce output ACTION.
  12998. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12999. or `agenda' to produce an entry list for an agenda view. It can also be
  13000. a Lisp form or a function that should be called at each matched headline, in
  13001. this case the return value is a list of all return values from these calls.
  13002. MATCHER is a function accepting three arguments, returning
  13003. a non-nil value whenever a given set of tags qualifies a headline
  13004. for inclusion. See `org-make-tags-matcher' for more information.
  13005. As a special case, it can also be set to t (respectively nil) in
  13006. order to match all (respectively none) headline.
  13007. When TODO-ONLY is non-nil, only lines with a not-done TODO
  13008. keyword are included in the output.
  13009. START-LEVEL can be a string with asterisks, reducing the scope to
  13010. headlines matching this string."
  13011. (require 'org-agenda)
  13012. (let* ((re (concat "^"
  13013. (if start-level
  13014. ;; Get the correct level to match
  13015. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  13016. org-outline-regexp)
  13017. " *\\(\\<\\("
  13018. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  13019. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  13020. (props (list 'face 'default
  13021. 'done-face 'org-agenda-done
  13022. 'undone-face 'default
  13023. 'mouse-face 'highlight
  13024. 'org-not-done-regexp org-not-done-regexp
  13025. 'org-todo-regexp org-todo-regexp
  13026. 'org-complex-heading-regexp org-complex-heading-regexp
  13027. 'help-echo
  13028. (format "mouse-2 or RET jump to org file %s"
  13029. (abbreviate-file-name
  13030. (or (buffer-file-name (buffer-base-buffer))
  13031. (buffer-name (buffer-base-buffer)))))))
  13032. (org-map-continue-from nil)
  13033. lspos tags tags-list
  13034. (tags-alist (list (cons 0 org-file-tags)))
  13035. (llast 0) rtn rtn1 level category i txt
  13036. todo marker entry priority
  13037. ts-date ts-date-type ts-date-pair)
  13038. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  13039. (setq action (list 'lambda nil action)))
  13040. (save-excursion
  13041. (goto-char (point-min))
  13042. (when (eq action 'sparse-tree)
  13043. (org-overview)
  13044. (org-remove-occur-highlights))
  13045. (while (let (case-fold-search)
  13046. (re-search-forward re nil t))
  13047. (setq org-map-continue-from nil)
  13048. (catch :skip
  13049. (setq todo
  13050. ;; TODO: is the 1-2 difference a bug?
  13051. (when (match-end 1) (match-string-no-properties 2))
  13052. tags (when (match-end 4) (match-string-no-properties 4)))
  13053. (goto-char (setq lspos (match-beginning 0)))
  13054. (setq level (org-reduced-level (org-outline-level))
  13055. category (org-get-category))
  13056. (when (eq action 'agenda)
  13057. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13058. ts-date (car ts-date-pair)
  13059. ts-date-type (cdr ts-date-pair)))
  13060. (setq i llast llast level)
  13061. ;; remove tag lists from same and sublevels
  13062. (while (>= i level)
  13063. (when (setq entry (assoc i tags-alist))
  13064. (setq tags-alist (delete entry tags-alist)))
  13065. (setq i (1- i)))
  13066. ;; add the next tags
  13067. (when tags
  13068. (setq tags (org-split-string tags ":")
  13069. tags-alist
  13070. (cons (cons level tags) tags-alist)))
  13071. ;; compile tags for current headline
  13072. (setq tags-list
  13073. (if org-use-tag-inheritance
  13074. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13075. tags)
  13076. org-scanner-tags tags-list)
  13077. (when org-use-tag-inheritance
  13078. (setcdr (car tags-alist)
  13079. (mapcar (lambda (x)
  13080. (setq x (copy-sequence x))
  13081. (org-add-prop-inherited x))
  13082. (cdar tags-alist))))
  13083. (when (and tags org-use-tag-inheritance
  13084. (or (not (eq t org-use-tag-inheritance))
  13085. org-tags-exclude-from-inheritance))
  13086. ;; Selective inheritance, remove uninherited ones.
  13087. (setcdr (car tags-alist)
  13088. (org-remove-uninherited-tags (cdar tags-alist))))
  13089. (when (and
  13090. ;; eval matcher only when the todo condition is OK
  13091. (and (or (not todo-only) (member todo org-not-done-keywords))
  13092. (if (functionp matcher)
  13093. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13094. (funcall matcher todo tags-list level))
  13095. matcher))
  13096. ;; Call the skipper, but return t if it does not
  13097. ;; skip, so that the `and' form continues evaluating.
  13098. (progn
  13099. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13100. t)
  13101. ;; Check if timestamps are deselecting this entry
  13102. (or (not todo-only)
  13103. (and (member todo org-not-done-keywords)
  13104. (or (not org-agenda-tags-todo-honor-ignore-options)
  13105. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13106. ;; select this headline
  13107. (cond
  13108. ((eq action 'sparse-tree)
  13109. (and org-highlight-sparse-tree-matches
  13110. (org-get-heading) (match-end 0)
  13111. (org-highlight-new-match
  13112. (match-beginning 1) (match-end 1)))
  13113. (org-show-context 'tags-tree))
  13114. ((eq action 'agenda)
  13115. (setq txt (org-agenda-format-item
  13116. ""
  13117. (concat
  13118. (if (eq org-tags-match-list-sublevels 'indented)
  13119. (make-string (1- level) ?.) "")
  13120. (org-get-heading))
  13121. (make-string level ?\s)
  13122. category
  13123. tags-list)
  13124. priority (org-get-priority txt))
  13125. (goto-char lspos)
  13126. (setq marker (org-agenda-new-marker))
  13127. (org-add-props txt props
  13128. 'org-marker marker 'org-hd-marker marker 'org-category category
  13129. 'todo-state todo
  13130. 'ts-date ts-date
  13131. 'priority priority
  13132. 'type (concat "tagsmatch" ts-date-type))
  13133. (push txt rtn))
  13134. ((functionp action)
  13135. (setq org-map-continue-from nil)
  13136. (save-excursion
  13137. (setq rtn1 (funcall action))
  13138. (push rtn1 rtn)))
  13139. (t (user-error "Invalid action")))
  13140. ;; if we are to skip sublevels, jump to end of subtree
  13141. (unless org-tags-match-list-sublevels
  13142. (org-end-of-subtree t)
  13143. (backward-char 1))))
  13144. ;; Get the correct position from where to continue
  13145. (if org-map-continue-from
  13146. (goto-char org-map-continue-from)
  13147. (and (= (point) lspos) (end-of-line 1)))))
  13148. (when (and (eq action 'sparse-tree)
  13149. (not org-sparse-tree-open-archived-trees))
  13150. (org-hide-archived-subtrees (point-min) (point-max)))
  13151. (nreverse rtn)))
  13152. (defun org-remove-uninherited-tags (tags)
  13153. "Remove all tags that are not inherited from the list TAGS."
  13154. (cond
  13155. ((eq org-use-tag-inheritance t)
  13156. (if org-tags-exclude-from-inheritance
  13157. (org-delete-all org-tags-exclude-from-inheritance tags)
  13158. tags))
  13159. ((not org-use-tag-inheritance) nil)
  13160. ((stringp org-use-tag-inheritance)
  13161. (delq nil (mapcar
  13162. (lambda (x)
  13163. (if (and (string-match org-use-tag-inheritance x)
  13164. (not (member x org-tags-exclude-from-inheritance)))
  13165. x nil))
  13166. tags)))
  13167. ((listp org-use-tag-inheritance)
  13168. (delq nil (mapcar
  13169. (lambda (x)
  13170. (if (member x org-use-tag-inheritance) x nil))
  13171. tags)))))
  13172. (defun org-match-sparse-tree (&optional todo-only match)
  13173. "Create a sparse tree according to tags string MATCH.
  13174. MATCH is a string with match syntax. It can contain a selection
  13175. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13176. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13177. those. See the manual for details.
  13178. If optional argument TODO-ONLY is non-nil, only select lines that
  13179. are also TODO tasks."
  13180. (interactive "P")
  13181. (org-agenda-prepare-buffers (list (current-buffer)))
  13182. (let ((org--matcher-tags-todo-only todo-only))
  13183. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13184. org--matcher-tags-todo-only)))
  13185. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13186. (defvar org-cached-props nil)
  13187. (defun org-cached-entry-get (pom property)
  13188. (if (or (eq t org-use-property-inheritance)
  13189. (and (stringp org-use-property-inheritance)
  13190. (let ((case-fold-search t))
  13191. (string-match-p org-use-property-inheritance property)))
  13192. (and (listp org-use-property-inheritance)
  13193. (member-ignore-case property org-use-property-inheritance)))
  13194. ;; Caching is not possible, check it directly.
  13195. (org-entry-get pom property 'inherit)
  13196. ;; Get all properties, so we can do complicated checks easily.
  13197. (cdr (assoc-string property
  13198. (or org-cached-props
  13199. (setq org-cached-props (org-entry-properties pom)))
  13200. t))))
  13201. (defun org-global-tags-completion-table (&optional files)
  13202. "Return the list of all tags in all agenda buffer/files.
  13203. Optional FILES argument is a list of files which can be used
  13204. instead of the agenda files."
  13205. (save-excursion
  13206. (org-uniquify
  13207. (delq nil
  13208. (apply #'append
  13209. (mapcar
  13210. (lambda (file)
  13211. (set-buffer (find-file-noselect file))
  13212. (mapcar (lambda (x)
  13213. (and (stringp (car-safe x))
  13214. (list (car-safe x))))
  13215. (or org-current-tag-alist (org-get-buffer-tags))))
  13216. (if (car-safe files) files
  13217. (org-agenda-files))))))))
  13218. (defun org-make-tags-matcher (match)
  13219. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13220. Returns a cons of the selection string MATCH and a function
  13221. implementing the matcher.
  13222. The matcher is to be called at an Org entry, with point on the
  13223. headline, and returns non-nil if the entry matches the selection
  13224. string MATCH. It must be called with three arguments: the TODO
  13225. keyword at the entry (or nil if none), the list of all tags at
  13226. the entry including inherited ones and the reduced level of the
  13227. headline. Additionally, the category of the entry, if any, must
  13228. be specified as the text property `org-category' on the headline.
  13229. This function sets the variable `org--matcher-tags-todo-only' to
  13230. a non-nil value if the matcher restricts matching to TODO
  13231. entries, otherwise it is not touched.
  13232. See also `org-scan-tags'."
  13233. (unless match
  13234. ;; Get a new match request, with completion against the global
  13235. ;; tags table and the local tags in current buffer.
  13236. (let ((org-last-tags-completion-table
  13237. (org-uniquify
  13238. (delq nil (append (org-get-buffer-tags)
  13239. (org-global-tags-completion-table))))))
  13240. (setq match
  13241. (completing-read
  13242. "Match: "
  13243. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13244. (let ((match0 match)
  13245. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13246. (start 0)
  13247. tagsmatch todomatch tagsmatcher todomatcher)
  13248. ;; Expand group tags.
  13249. (setq match (org-tags-expand match))
  13250. ;; Check if there is a TODO part of this match, which would be the
  13251. ;; part after a "/". To make sure that this slash is not part of
  13252. ;; a property value to be matched against, we also check that
  13253. ;; there is no / after that slash. First, find the last slash.
  13254. (let ((s 0))
  13255. (while (string-match "/+" match s)
  13256. (setq start (match-beginning 0))
  13257. (setq s (match-end 0))))
  13258. (if (and (string-match "/+" match start)
  13259. (not (string-match-p "\"" match start)))
  13260. ;; Match contains also a TODO-matching request.
  13261. (progn
  13262. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13263. (setq todomatch (substring match (match-end 0)))
  13264. (when (string-prefix-p "!" todomatch)
  13265. (setq org--matcher-tags-todo-only t)
  13266. (setq todomatch (substring todomatch 1)))
  13267. (when (string-match "\\`\\s-*\\'" todomatch)
  13268. (setq todomatch nil)))
  13269. ;; Only matching tags.
  13270. (setq tagsmatch match)
  13271. (setq todomatch nil))
  13272. ;; Make the tags matcher.
  13273. (when (org-string-nw-p tagsmatch)
  13274. (let ((orlist nil)
  13275. (orterms (org-split-string tagsmatch "|"))
  13276. term)
  13277. (while (setq term (pop orterms))
  13278. (while (and (equal (substring term -1) "\\") orterms)
  13279. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13280. (while (string-match re term)
  13281. (let* ((rest (substring term (match-end 0)))
  13282. (minus (and (match-end 1)
  13283. (equal (match-string 1 term) "-")))
  13284. (tag (save-match-data
  13285. (replace-regexp-in-string
  13286. "\\\\-" "-" (match-string 2 term))))
  13287. (regexp (eq (string-to-char tag) ?{))
  13288. (levelp (match-end 4))
  13289. (propp (match-end 5))
  13290. (mm
  13291. (cond
  13292. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13293. (levelp
  13294. `(,(org-op-to-function (match-string 3 term))
  13295. level
  13296. ,(string-to-number (match-string 4 term))))
  13297. (propp
  13298. (let* ((gv (pcase (upcase (match-string 5 term))
  13299. ("CATEGORY"
  13300. '(get-text-property (point) 'org-category))
  13301. ("TODO" 'todo)
  13302. (p `(org-cached-entry-get nil ,p))))
  13303. (pv (match-string 7 term))
  13304. (regexp (eq (string-to-char pv) ?{))
  13305. (strp (eq (string-to-char pv) ?\"))
  13306. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13307. (po (org-op-to-function (match-string 6 term)
  13308. (if timep 'time strp))))
  13309. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13310. (when timep (setq pv (org-matcher-time pv)))
  13311. (cond ((and regexp (eq po 'org<>))
  13312. `(not (string-match ,pv (or ,gv ""))))
  13313. (regexp `(string-match ,pv (or ,gv "")))
  13314. (strp `(,po (or ,gv "") ,pv))
  13315. (t
  13316. `(,po
  13317. (string-to-number (or ,gv ""))
  13318. ,(string-to-number pv))))))
  13319. (t `(member ,tag tags-list)))))
  13320. (push (if minus `(not ,mm) mm) tagsmatcher)
  13321. (setq term rest)))
  13322. (push `(and ,@tagsmatcher) orlist)
  13323. (setq tagsmatcher nil))
  13324. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13325. ;; Make the TODO matcher.
  13326. (when (org-string-nw-p todomatch)
  13327. (let ((orlist nil))
  13328. (dolist (term (org-split-string todomatch "|"))
  13329. (while (string-match re term)
  13330. (let* ((minus (and (match-end 1)
  13331. (equal (match-string 1 term) "-")))
  13332. (kwd (match-string 2 term))
  13333. (regexp (eq (string-to-char kwd) ?{))
  13334. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13335. `(equal todo ,kwd))))
  13336. (push (if minus `(not ,mm) mm) todomatcher))
  13337. (setq term (substring term (match-end 0))))
  13338. (push (if (> (length todomatcher) 1)
  13339. (cons 'and todomatcher)
  13340. (car todomatcher))
  13341. orlist)
  13342. (setq todomatcher nil))
  13343. (setq todomatcher (cons 'or orlist))))
  13344. ;; Return the string and function of the matcher. If no
  13345. ;; tags-specific or todo-specific matcher exists, match
  13346. ;; everything.
  13347. (let ((matcher (if (and tagsmatcher todomatcher)
  13348. `(and ,tagsmatcher ,todomatcher)
  13349. (or tagsmatcher todomatcher t))))
  13350. (when org--matcher-tags-todo-only
  13351. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13352. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13353. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13354. "Expand group tags in MATCH.
  13355. This replaces every group tag in MATCH with a regexp tag search.
  13356. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13357. will be replaced like this:
  13358. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13359. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13360. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13361. Replacing by a regexp preserves the structure of the match.
  13362. E.g., this expansion
  13363. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13364. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13365. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13366. A group tag in MATCH can contain regular expressions of its own.
  13367. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13368. will be replaced like this:
  13369. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13370. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13371. assumed to be a single group tag, and the function will return
  13372. the list of tags in this group.
  13373. When DOWNCASE is non-nil, expand downcased TAGS."
  13374. (if org-group-tags
  13375. (let* ((case-fold-search t)
  13376. (stable org-mode-syntax-table)
  13377. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13378. (taggroups (if downcased
  13379. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13380. taggroups)
  13381. taggroups))
  13382. (taggroups-keys (mapcar #'car taggroups))
  13383. (return-match (if downcased (downcase match) match))
  13384. (count 0)
  13385. (work-already-expanded tags-already-expanded)
  13386. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13387. ;; @ and _ are allowed as word-components in tags.
  13388. (modify-syntax-entry ?@ "w" stable)
  13389. (modify-syntax-entry ?_ "w" stable)
  13390. ;; Temporarily replace regexp-expressions in the match-expression.
  13391. (while (string-match "{.+?}" return-match)
  13392. (cl-incf count)
  13393. (push (match-string 0 return-match) regexps-in-match)
  13394. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13395. (while (and taggroups-keys
  13396. (with-syntax-table stable
  13397. (string-match
  13398. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13399. (regexp-opt taggroups-keys) "\\>\\)")
  13400. return-match)))
  13401. (let* ((dir (match-string 1 return-match))
  13402. (tag (match-string 2 return-match))
  13403. (tag (if downcased (downcase tag) tag)))
  13404. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13405. (member tag work-already-expanded))
  13406. (setq tags-in-group (assoc tag taggroups))
  13407. (push tag work-already-expanded)
  13408. ;; Recursively expand each tag in the group, if the tag hasn't
  13409. ;; already been expanded. Restore the match-data after all recursive calls.
  13410. (save-match-data
  13411. (let (tags-expanded)
  13412. (dolist (x (cdr tags-in-group))
  13413. (if (and (member x taggroups-keys)
  13414. (not (member x work-already-expanded)))
  13415. (setq tags-expanded
  13416. (delete-dups
  13417. (append
  13418. (org-tags-expand x t downcased
  13419. work-already-expanded)
  13420. tags-expanded)))
  13421. (setq tags-expanded
  13422. (append (list x) tags-expanded)))
  13423. (setq work-already-expanded
  13424. (delete-dups
  13425. (append tags-expanded
  13426. work-already-expanded))))
  13427. (setq tags-in-group
  13428. (delete-dups (cons (car tags-in-group)
  13429. tags-expanded)))))
  13430. ;; Filter tag-regexps from tags.
  13431. (setq regexp-in-group-escaped
  13432. (delq nil (mapcar (lambda (x)
  13433. (if (stringp x)
  13434. (and (equal "{" (substring x 0 1))
  13435. (equal "}" (substring x -1))
  13436. x)
  13437. x))
  13438. tags-in-group))
  13439. regexp-in-group
  13440. (mapcar (lambda (x)
  13441. (substring x 1 -1))
  13442. regexp-in-group-escaped)
  13443. tags-in-group
  13444. (delq nil (mapcar (lambda (x)
  13445. (if (stringp x)
  13446. (and (not (equal "{" (substring x 0 1)))
  13447. (not (equal "}" (substring x -1)))
  13448. x)
  13449. x))
  13450. tags-in-group)))
  13451. ;; If single-as-list, do no more in the while-loop.
  13452. (if (not single-as-list)
  13453. (progn
  13454. (when regexp-in-group
  13455. (setq regexp-in-group
  13456. (concat "\\|"
  13457. (mapconcat 'identity regexp-in-group
  13458. "\\|"))))
  13459. (setq tags-in-group
  13460. (concat dir
  13461. "{\\<"
  13462. (regexp-opt tags-in-group)
  13463. "\\>"
  13464. regexp-in-group
  13465. "}"))
  13466. (when (stringp tags-in-group)
  13467. (org-add-props tags-in-group '(grouptag t)))
  13468. (setq return-match
  13469. (replace-match tags-in-group t t return-match)))
  13470. (setq tags-in-group
  13471. (append regexp-in-group-escaped tags-in-group))))
  13472. (setq taggroups-keys (delete tag taggroups-keys))))
  13473. ;; Add the regular expressions back into the match-expression again.
  13474. (while regexps-in-match
  13475. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13476. (pop regexps-in-match)
  13477. return-match t t))
  13478. (cl-decf count))
  13479. (if single-as-list
  13480. (if tags-in-group tags-in-group (list return-match))
  13481. return-match))
  13482. (if single-as-list
  13483. (list (if downcased (downcase match) match))
  13484. match)))
  13485. (defun org-op-to-function (op &optional stringp)
  13486. "Turn an operator into the appropriate function."
  13487. (setq op
  13488. (cond
  13489. ((equal op "<" ) '(< string< org-time<))
  13490. ((equal op ">" ) '(> org-string> org-time>))
  13491. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13492. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13493. ((member op '("=" "==")) '(= string= org-time=))
  13494. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13495. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13496. (defun org<> (a b) (not (= a b)))
  13497. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13498. (defun org-string>= (a b) (not (string< a b)))
  13499. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13500. (defun org-string<> (a b) (not (string= a b)))
  13501. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13502. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13503. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13504. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13505. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13506. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13507. (defun org-2ft (s)
  13508. "Convert S to a floating point time.
  13509. If S is already a number, just return it. If it is a string, parse
  13510. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13511. (cond
  13512. ((numberp s) s)
  13513. ((stringp s)
  13514. (condition-case nil
  13515. (float-time (apply 'encode-time (org-parse-time-string s)))
  13516. (error 0.)))
  13517. (t 0.)))
  13518. (defun org-time-today ()
  13519. "Time in seconds today at 0:00.
  13520. Returns the float number of seconds since the beginning of the
  13521. epoch to the beginning of today (00:00)."
  13522. (float-time (apply 'encode-time
  13523. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13524. (defun org-matcher-time (s)
  13525. "Interpret a time comparison value."
  13526. (save-match-data
  13527. (cond
  13528. ((string= s "<now>") (float-time))
  13529. ((string= s "<today>") (org-time-today))
  13530. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13531. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13532. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13533. (+ (org-time-today)
  13534. (* (string-to-number (match-string 1 s))
  13535. (cdr (assoc (match-string 2 s)
  13536. '(("d" . 86400.0) ("w" . 604800.0)
  13537. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13538. (t (org-2ft s)))))
  13539. (defun org-match-any-p (re list)
  13540. "Does re match any element of list?"
  13541. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13542. (delq nil list))
  13543. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13544. (defvar org-tags-overlay (make-overlay 1 1))
  13545. (delete-overlay org-tags-overlay)
  13546. (defun org-get-local-tags-at (&optional pos)
  13547. "Get a list of tags defined in the current headline."
  13548. (org-get-tags-at pos 'local))
  13549. (defun org-get-local-tags ()
  13550. "Get a list of tags defined in the current headline."
  13551. (org-get-tags-at nil 'local))
  13552. (defun org-get-tags-at (&optional pos local)
  13553. "Get a list of all headline tags applicable at POS.
  13554. POS defaults to point. If tags are inherited, the list contains
  13555. the targets in the same sequence as the headlines appear, i.e.
  13556. the tags of the current headline come last.
  13557. When LOCAL is non-nil, only return tags from the current headline,
  13558. ignore inherited ones."
  13559. (interactive)
  13560. (if (and org-trust-scanner-tags
  13561. (or (not pos) (equal pos (point)))
  13562. (not local))
  13563. org-scanner-tags
  13564. (let (tags ltags lastpos parent)
  13565. (save-excursion
  13566. (save-restriction
  13567. (widen)
  13568. (goto-char (or pos (point)))
  13569. (save-match-data
  13570. (catch 'done
  13571. (condition-case nil
  13572. (progn
  13573. (org-back-to-heading t)
  13574. (while (not (equal lastpos (point)))
  13575. (setq lastpos (point))
  13576. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13577. (setq ltags (org-split-string
  13578. (match-string-no-properties 1) ":"))
  13579. (when parent
  13580. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13581. (setq tags (append
  13582. (if parent
  13583. (org-remove-uninherited-tags ltags)
  13584. ltags)
  13585. tags)))
  13586. (or org-use-tag-inheritance (throw 'done t))
  13587. (when local (throw 'done t))
  13588. (or (org-up-heading-safe) (error nil))
  13589. (setq parent t)))
  13590. (error nil)))))
  13591. (if local
  13592. tags
  13593. (reverse (delete-dups
  13594. (reverse (append
  13595. (org-remove-uninherited-tags
  13596. org-file-tags)
  13597. tags)))))))))
  13598. (defun org-add-prop-inherited (s)
  13599. (add-text-properties 0 (length s) '(inherited t) s)
  13600. s)
  13601. (defun org-toggle-tag (tag &optional onoff)
  13602. "Toggle the tag TAG for the current line.
  13603. If ONOFF is `on' or `off', don't toggle but set to this state."
  13604. (let (res current)
  13605. (save-excursion
  13606. (org-back-to-heading t)
  13607. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13608. (point-at-eol) t)
  13609. (progn
  13610. (setq current (match-string 1))
  13611. (replace-match ""))
  13612. (setq current ""))
  13613. (setq current (nreverse (org-split-string current ":")))
  13614. (cond
  13615. ((eq onoff 'on)
  13616. (setq res t)
  13617. (or (member tag current) (push tag current)))
  13618. ((eq onoff 'off)
  13619. (or (not (member tag current)) (setq current (delete tag current))))
  13620. (t (if (member tag current)
  13621. (setq current (delete tag current))
  13622. (setq res t)
  13623. (push tag current))))
  13624. (end-of-line 1)
  13625. (if current
  13626. (progn
  13627. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13628. (org-set-tags nil t))
  13629. (delete-horizontal-space))
  13630. (run-hooks 'org-after-tags-change-hook))
  13631. res))
  13632. (defun org--align-tags-here (to-col)
  13633. "Align tags on the current headline to TO-COL.
  13634. Assume point is on a headline."
  13635. (let ((pos (point)))
  13636. (beginning-of-line)
  13637. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13638. (>= pos (match-beginning 2)))
  13639. ;; No tags or point within tags: do not align.
  13640. (goto-char pos)
  13641. (goto-char (match-beginning 1))
  13642. (let ((shift (max (- (if (>= to-col 0) to-col
  13643. (- (abs to-col) (string-width (match-string 2))))
  13644. (current-column))
  13645. 1)))
  13646. (replace-match (make-string shift ?\s) nil nil nil 1)
  13647. ;; Preserve initial position, if possible. In any case, stop
  13648. ;; before tags.
  13649. (when (< pos (point)) (goto-char pos))))))
  13650. (defun org-set-tags-command (&optional arg just-align)
  13651. "Call the set-tags command for the current entry."
  13652. (interactive "P")
  13653. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13654. (org-set-tags arg just-align)
  13655. (save-excursion
  13656. (unless (and (org-region-active-p)
  13657. org-loop-over-headlines-in-active-region)
  13658. (org-back-to-heading t))
  13659. (org-set-tags arg just-align))))
  13660. (defun org-set-tags-to (data)
  13661. "Set the tags of the current entry to DATA, replacing the current tags.
  13662. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13663. If DATA is nil or the empty string, any tags will be removed."
  13664. (interactive "sTags: ")
  13665. (setq data
  13666. (cond
  13667. ((eq data nil) "")
  13668. ((equal data "") "")
  13669. ((stringp data)
  13670. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13671. ":"))
  13672. ((listp data)
  13673. (concat ":" (mapconcat 'identity data ":") ":"))))
  13674. (when data
  13675. (save-excursion
  13676. (org-back-to-heading t)
  13677. (when (let ((case-fold-search nil))
  13678. (looking-at org-complex-heading-regexp))
  13679. (if (match-end 5)
  13680. (progn
  13681. (goto-char (match-beginning 5))
  13682. (insert data)
  13683. (delete-region (point) (point-at-eol))
  13684. (org-set-tags nil 'align))
  13685. (goto-char (point-at-eol))
  13686. (insert " " data)
  13687. (org-set-tags nil 'align)))
  13688. (beginning-of-line 1)
  13689. (when (looking-at ".*?\\([ \t]+\\)$")
  13690. (delete-region (match-beginning 1) (match-end 1))))))
  13691. (defun org-align-all-tags ()
  13692. "Align the tags in all headings."
  13693. (interactive)
  13694. (save-excursion
  13695. (or (ignore-errors (org-back-to-heading t))
  13696. (outline-next-heading))
  13697. (if (org-at-heading-p)
  13698. (org-set-tags t)
  13699. (message "No headings"))))
  13700. (defvar org-indent-indentation-per-level)
  13701. (defun org-set-tags (&optional arg just-align)
  13702. "Set the tags for the current headline.
  13703. With prefix ARG, realign all tags in headings in the current buffer.
  13704. When JUST-ALIGN is non-nil, only align tags."
  13705. (interactive "P")
  13706. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13707. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13708. 'region-start-level
  13709. 'region))
  13710. org-loop-over-headlines-in-active-region)
  13711. (org-map-entries
  13712. ;; We don't use ARG and JUST-ALIGN here because these args
  13713. ;; are not useful when looping over headlines.
  13714. #'org-set-tags
  13715. org-loop-over-headlines-in-active-region
  13716. cl
  13717. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13718. (let ((org-setting-tags t))
  13719. (if arg
  13720. (save-excursion
  13721. (goto-char (point-min))
  13722. (while (re-search-forward org-outline-regexp-bol nil t)
  13723. (org-set-tags nil t)
  13724. (end-of-line))
  13725. (message "All tags realigned to column %d" org-tags-column))
  13726. (let* ((current (org-get-tags-string))
  13727. (tags
  13728. (if just-align current
  13729. ;; Get a new set of tags from the user.
  13730. (save-excursion
  13731. (let* ((seen)
  13732. (table
  13733. (setq
  13734. org-last-tags-completion-table
  13735. ;; Uniquify tags in alists, yet preserve
  13736. ;; structure (i.e., keywords).
  13737. (delq nil
  13738. (mapcar
  13739. (lambda (pair)
  13740. (let ((head (car pair)))
  13741. (cond ((symbolp head) pair)
  13742. ((member head seen) nil)
  13743. (t (push head seen)
  13744. pair))))
  13745. (append
  13746. (or org-current-tag-alist
  13747. (org-get-buffer-tags))
  13748. (and
  13749. org-complete-tags-always-offer-all-agenda-tags
  13750. (org-global-tags-completion-table
  13751. (org-agenda-files))))))))
  13752. (current-tags (org-split-string current ":"))
  13753. (inherited-tags
  13754. (nreverse (nthcdr (length current-tags)
  13755. (nreverse (org-get-tags-at))))))
  13756. (replace-regexp-in-string
  13757. "\\([-+&]+\\|,\\)"
  13758. ":"
  13759. (if (or (eq t org-use-fast-tag-selection)
  13760. (and org-use-fast-tag-selection
  13761. (delq nil (mapcar #'cdr table))))
  13762. (org-fast-tag-selection
  13763. current-tags inherited-tags table
  13764. (and org-fast-tag-selection-include-todo
  13765. org-todo-key-alist))
  13766. (let ((org-add-colon-after-tag-completion
  13767. (< 1 (length table))))
  13768. (org-trim
  13769. (completing-read
  13770. "Tags: "
  13771. #'org-tags-completion-function
  13772. nil nil current 'org-tags-history))))))))))
  13773. (when org-tags-sort-function
  13774. (setq tags
  13775. (mapconcat
  13776. #'identity
  13777. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13778. org-tags-sort-function)
  13779. ":")))
  13780. (if (not (org-string-nw-p tags)) (setq tags "")
  13781. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13782. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13783. ;; Insert new tags at the correct column.
  13784. (unless (equal current tags)
  13785. (save-excursion
  13786. (beginning-of-line)
  13787. (let ((case-fold-search nil))
  13788. (looking-at org-complex-heading-regexp))
  13789. ;; Remove current tags, if any.
  13790. (when (match-end 5) (replace-match "" nil nil nil 5))
  13791. ;; Insert new tags, if any. Otherwise, remove trailing
  13792. ;; white spaces.
  13793. (end-of-line)
  13794. (if (not (equal tags ""))
  13795. (insert " " tags)
  13796. (skip-chars-backward " \t")
  13797. (delete-region (point) (line-end-position)))))
  13798. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13799. ;; is on.
  13800. (unless (equal tags "")
  13801. (let* ((level (save-excursion
  13802. (beginning-of-line)
  13803. (skip-chars-forward "\\*")))
  13804. (offset (if (bound-and-true-p org-indent-mode)
  13805. (* (1- org-indent-indentation-per-level)
  13806. (1- level))
  13807. 0))
  13808. (tags-column
  13809. (+ org-tags-column
  13810. (if (> org-tags-column 0) (- offset) offset))))
  13811. (org--align-tags-here tags-column))))
  13812. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13813. (defun org-change-tag-in-region (beg end tag off)
  13814. "Add or remove TAG for each entry in the region.
  13815. This works in the agenda, and also in an Org buffer."
  13816. (interactive
  13817. (list (region-beginning) (region-end)
  13818. (let ((org-last-tags-completion-table
  13819. (if (derived-mode-p 'org-mode)
  13820. (org-uniquify
  13821. (delq nil (append (org-get-buffer-tags)
  13822. (org-global-tags-completion-table))))
  13823. (org-global-tags-completion-table))))
  13824. (completing-read
  13825. "Tag: " 'org-tags-completion-function nil nil nil
  13826. 'org-tags-history))
  13827. (progn
  13828. (message "[s]et or [r]emove? ")
  13829. (equal (read-char-exclusive) ?r))))
  13830. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13831. (let ((agendap (equal major-mode 'org-agenda-mode))
  13832. l1 l2 m buf pos newhead (cnt 0))
  13833. (goto-char end)
  13834. (setq l2 (1- (org-current-line)))
  13835. (goto-char beg)
  13836. (setq l1 (org-current-line))
  13837. (cl-loop for l from l1 to l2 do
  13838. (org-goto-line l)
  13839. (setq m (get-text-property (point) 'org-hd-marker))
  13840. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13841. (and agendap m))
  13842. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13843. pos (if agendap m (point)))
  13844. (with-current-buffer buf
  13845. (save-excursion
  13846. (save-restriction
  13847. (goto-char pos)
  13848. (setq cnt (1+ cnt))
  13849. (org-toggle-tag tag (if off 'off 'on))
  13850. (setq newhead (org-get-heading)))))
  13851. (and agendap (org-agenda-change-all-lines newhead m))))
  13852. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13853. (defun org-tags-completion-function (string _predicate &optional flag)
  13854. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13855. (confirm (lambda (x) (stringp (car x)))))
  13856. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13857. (setq s1 (match-string 1 string)
  13858. s2 (match-string 2 string))
  13859. (setq s1 "" s2 string))
  13860. (cond
  13861. ((eq flag nil)
  13862. ;; try completion
  13863. (setq rtn (try-completion s2 ctable confirm))
  13864. (when (stringp rtn)
  13865. (setq rtn
  13866. (concat s1 s2 (substring rtn (length s2))
  13867. (if (and org-add-colon-after-tag-completion
  13868. (assoc rtn ctable))
  13869. ":" ""))))
  13870. rtn)
  13871. ((eq flag t)
  13872. ;; all-completions
  13873. (all-completions s2 ctable confirm))
  13874. ((eq flag 'lambda)
  13875. ;; exact match?
  13876. (assoc s2 ctable)))))
  13877. (defun org-fast-tag-insert (kwd tags face &optional end)
  13878. "Insert KDW, and the TAGS, the latter with face FACE.
  13879. Also insert END."
  13880. (insert (format "%-12s" (concat kwd ":"))
  13881. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13882. (or end "")))
  13883. (defun org-fast-tag-show-exit (flag)
  13884. (save-excursion
  13885. (org-goto-line 3)
  13886. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13887. (replace-match ""))
  13888. (when flag
  13889. (end-of-line 1)
  13890. (org-move-to-column (- (window-width) 19) t)
  13891. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13892. (defun org-set-current-tags-overlay (current prefix)
  13893. "Add an overlay to CURRENT tag with PREFIX."
  13894. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13895. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13896. (org-overlay-display org-tags-overlay (concat prefix s))))
  13897. (defvar org-last-tag-selection-key nil)
  13898. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13899. "Fast tag selection with single keys.
  13900. CURRENT is the current list of tags in the headline, INHERITED is the
  13901. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13902. possibly with grouping information. TODO-TABLE is a similar table with
  13903. TODO keywords, should these have keys assigned to them.
  13904. If the keys are nil, a-z are automatically assigned.
  13905. Returns the new tags string, or nil to not change the current settings."
  13906. (let* ((fulltable (append table todo-table))
  13907. (maxlen (apply 'max (mapcar
  13908. (lambda (x)
  13909. (if (stringp (car x)) (string-width (car x)) 0))
  13910. fulltable)))
  13911. (buf (current-buffer))
  13912. (expert (eq org-fast-tag-selection-single-key 'expert))
  13913. (buffer-tags nil)
  13914. (fwidth (+ maxlen 3 1 3))
  13915. (ncol (/ (- (window-width) 4) fwidth))
  13916. (i-face 'org-done)
  13917. (c-face 'org-todo)
  13918. tg cnt e c char c1 c2 ntable tbl rtn
  13919. ov-start ov-end ov-prefix
  13920. (exit-after-next org-fast-tag-selection-single-key)
  13921. (done-keywords org-done-keywords)
  13922. groups ingroup intaggroup)
  13923. (save-excursion
  13924. (beginning-of-line 1)
  13925. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13926. (setq ov-start (match-beginning 1)
  13927. ov-end (match-end 1)
  13928. ov-prefix "")
  13929. (setq ov-start (1- (point-at-eol))
  13930. ov-end (1+ ov-start))
  13931. (skip-chars-forward "^\n\r")
  13932. (setq ov-prefix
  13933. (concat
  13934. (buffer-substring (1- (point)) (point))
  13935. (if (> (current-column) org-tags-column)
  13936. " "
  13937. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13938. (move-overlay org-tags-overlay ov-start ov-end)
  13939. (save-window-excursion
  13940. (if expert
  13941. (set-buffer (get-buffer-create " *Org tags*"))
  13942. (delete-other-windows)
  13943. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13944. (org-switch-to-buffer-other-window " *Org tags*"))
  13945. (erase-buffer)
  13946. (setq-local org-done-keywords done-keywords)
  13947. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13948. (org-fast-tag-insert "Current" current c-face "\n\n")
  13949. (org-fast-tag-show-exit exit-after-next)
  13950. (org-set-current-tags-overlay current ov-prefix)
  13951. (setq tbl fulltable char ?a cnt 0)
  13952. (while (setq e (pop tbl))
  13953. (cond
  13954. ((eq (car e) :startgroup)
  13955. (push '() groups) (setq ingroup t)
  13956. (unless (zerop cnt)
  13957. (setq cnt 0)
  13958. (insert "\n"))
  13959. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13960. ((eq (car e) :endgroup)
  13961. (setq ingroup nil cnt 0)
  13962. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13963. ((eq (car e) :startgrouptag)
  13964. (setq intaggroup t)
  13965. (unless (zerop cnt)
  13966. (setq cnt 0)
  13967. (insert "\n"))
  13968. (insert "[ "))
  13969. ((eq (car e) :endgrouptag)
  13970. (setq intaggroup nil cnt 0)
  13971. (insert "]\n"))
  13972. ((equal e '(:newline))
  13973. (unless (zerop cnt)
  13974. (setq cnt 0)
  13975. (insert "\n")
  13976. (setq e (car tbl))
  13977. (while (equal (car tbl) '(:newline))
  13978. (insert "\n")
  13979. (setq tbl (cdr tbl)))))
  13980. ((equal e '(:grouptags)) (insert " : "))
  13981. (t
  13982. (setq tg (copy-sequence (car e)) c2 nil)
  13983. (if (cdr e)
  13984. (setq c (cdr e))
  13985. ;; automatically assign a character.
  13986. (setq c1 (string-to-char
  13987. (downcase (substring
  13988. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13989. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13990. (while (or (rassoc char ntable) (rassoc char table))
  13991. (setq char (1+ char)))
  13992. (setq c2 c1))
  13993. (setq c (or c2 char)))
  13994. (when ingroup (push tg (car groups)))
  13995. (setq tg (org-add-props tg nil 'face
  13996. (cond
  13997. ((not (assoc tg table))
  13998. (org-get-todo-face tg))
  13999. ((member tg current) c-face)
  14000. ((member tg inherited) i-face))))
  14001. (when (equal (caar tbl) :grouptags)
  14002. (org-add-props tg nil 'face 'org-tag-group))
  14003. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  14004. (insert "[" c "] " tg (make-string
  14005. (- fwidth 4 (length tg)) ?\ ))
  14006. (push (cons tg c) ntable)
  14007. (when (= (cl-incf cnt) ncol)
  14008. (insert "\n")
  14009. (when (or ingroup intaggroup) (insert " "))
  14010. (setq cnt 0)))))
  14011. (setq ntable (nreverse ntable))
  14012. (insert "\n")
  14013. (goto-char (point-min))
  14014. (unless expert (org-fit-window-to-buffer))
  14015. (setq rtn
  14016. (catch 'exit
  14017. (while t
  14018. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  14019. (if (not groups) "no " "")
  14020. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  14021. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  14022. (setq org-last-tag-selection-key c)
  14023. (cond
  14024. ((= c ?\r) (throw 'exit t))
  14025. ((= c ?!)
  14026. (setq groups (not groups))
  14027. (goto-char (point-min))
  14028. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  14029. ((= c ?\C-c)
  14030. (if (not expert)
  14031. (org-fast-tag-show-exit
  14032. (setq exit-after-next (not exit-after-next)))
  14033. (setq expert nil)
  14034. (delete-other-windows)
  14035. (set-window-buffer (split-window-vertically) " *Org tags*")
  14036. (org-switch-to-buffer-other-window " *Org tags*")
  14037. (org-fit-window-to-buffer)))
  14038. ((or (= c ?\C-g)
  14039. (and (= c ?q) (not (rassoc c ntable))))
  14040. (delete-overlay org-tags-overlay)
  14041. (setq quit-flag t))
  14042. ((= c ?\ )
  14043. (setq current nil)
  14044. (when exit-after-next (setq exit-after-next 'now)))
  14045. ((= c ?\t)
  14046. (condition-case nil
  14047. (setq tg (completing-read
  14048. "Tag: "
  14049. (or buffer-tags
  14050. (with-current-buffer buf
  14051. (setq buffer-tags
  14052. (org-get-buffer-tags))))))
  14053. (quit (setq tg "")))
  14054. (when (string-match "\\S-" tg)
  14055. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14056. (if (member tg current)
  14057. (setq current (delete tg current))
  14058. (push tg current)))
  14059. (when exit-after-next (setq exit-after-next 'now)))
  14060. ((setq e (rassoc c todo-table) tg (car e))
  14061. (with-current-buffer buf
  14062. (save-excursion (org-todo tg)))
  14063. (when exit-after-next (setq exit-after-next 'now)))
  14064. ((setq e (rassoc c ntable) tg (car e))
  14065. (if (member tg current)
  14066. (setq current (delete tg current))
  14067. (cl-loop for g in groups do
  14068. (when (member tg g)
  14069. (dolist (x g) (setq current (delete x current)))))
  14070. (push tg current))
  14071. (when exit-after-next (setq exit-after-next 'now))))
  14072. ;; Create a sorted list
  14073. (setq current
  14074. (sort current
  14075. (lambda (a b)
  14076. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14077. (when (eq exit-after-next 'now) (throw 'exit t))
  14078. (goto-char (point-min))
  14079. (beginning-of-line 2)
  14080. (delete-region (point) (point-at-eol))
  14081. (org-fast-tag-insert "Current" current c-face)
  14082. (org-set-current-tags-overlay current ov-prefix)
  14083. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14084. (setq tg (match-string 1))
  14085. (add-text-properties
  14086. (match-beginning 1) (match-end 1)
  14087. (list 'face
  14088. (cond
  14089. ((member tg current) c-face)
  14090. ((member tg inherited) i-face)
  14091. (t (get-text-property (match-beginning 1) 'face))))))
  14092. (goto-char (point-min)))))
  14093. (delete-overlay org-tags-overlay)
  14094. (if rtn
  14095. (mapconcat 'identity current ":")
  14096. nil))))
  14097. (defun org-get-tags-string ()
  14098. "Get the TAGS string in the current headline."
  14099. (unless (org-at-heading-p t)
  14100. (user-error "Not on a heading"))
  14101. (save-excursion
  14102. (beginning-of-line 1)
  14103. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14104. (match-string-no-properties 1)
  14105. "")))
  14106. (defun org-get-tags ()
  14107. "Get the list of tags specified in the current headline."
  14108. (org-split-string (org-get-tags-string) ":"))
  14109. (defun org-get-buffer-tags ()
  14110. "Get a table of all tags used in the buffer, for completion."
  14111. (org-with-wide-buffer
  14112. (goto-char (point-min))
  14113. (let ((tag-re (concat org-outline-regexp-bol
  14114. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14115. tags)
  14116. (while (re-search-forward tag-re nil t)
  14117. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14118. (push tag tags)))
  14119. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14120. ;;;; The mapping API
  14121. (defvar org-agenda-skip-comment-trees)
  14122. (defvar org-agenda-skip-function)
  14123. (defun org-map-entries (func &optional match scope &rest skip)
  14124. "Call FUNC at each headline selected by MATCH in SCOPE.
  14125. FUNC is a function or a lisp form. The function will be called without
  14126. arguments, with the cursor positioned at the beginning of the headline.
  14127. The return values of all calls to the function will be collected and
  14128. returned as a list.
  14129. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14130. does not need to preserve point. After evaluation, the cursor will be
  14131. moved to the end of the line (presumably of the headline of the
  14132. processed entry) and search continues from there. Under some
  14133. circumstances, this may not produce the wanted results. For example,
  14134. if you have removed (e.g. archived) the current (sub)tree it could
  14135. mean that the next entry will be skipped entirely. In such cases, you
  14136. can specify the position from where search should continue by making
  14137. FUNC set the variable `org-map-continue-from' to the desired buffer
  14138. position.
  14139. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14140. Only headlines that are matched by this query will be considered during
  14141. the iteration. When MATCH is nil or t, all headlines will be
  14142. visited by the iteration.
  14143. SCOPE determines the scope of this command. It can be any of:
  14144. nil The current buffer, respecting the restriction if any
  14145. tree The subtree started with the entry at point
  14146. region The entries within the active region, if any
  14147. region-start-level
  14148. The entries within the active region, but only those at
  14149. the same level than the first one.
  14150. file The current buffer, without restriction
  14151. file-with-archives
  14152. The current buffer, and any archives associated with it
  14153. agenda All agenda files
  14154. agenda-with-archives
  14155. All agenda files with any archive files associated with them
  14156. \(file1 file2 ...)
  14157. If this is a list, all files in the list will be scanned
  14158. The remaining args are treated as settings for the skipping facilities of
  14159. the scanner. The following items can be given here:
  14160. archive skip trees with the archive tag
  14161. comment skip trees with the COMMENT keyword
  14162. function or Emacs Lisp form:
  14163. will be used as value for `org-agenda-skip-function', so
  14164. whenever the function returns a position, FUNC will not be
  14165. called for that entry and search will continue from the
  14166. position returned
  14167. If your function needs to retrieve the tags including inherited tags
  14168. at the *current* entry, you can use the value of the variable
  14169. `org-scanner-tags' which will be much faster than getting the value
  14170. with `org-get-tags-at'. If your function gets properties with
  14171. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14172. to t around the call to `org-entry-properties' to get the same speedup.
  14173. Note that if your function moves around to retrieve tags and properties at
  14174. a *different* entry, you cannot use these techniques."
  14175. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14176. (not (org-region-active-p)))
  14177. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14178. (org-agenda-skip-archived-trees (memq 'archive skip))
  14179. (org-agenda-skip-comment-trees (memq 'comment skip))
  14180. (org-agenda-skip-function
  14181. (car (org-delete-all '(comment archive) skip)))
  14182. (org-tags-match-list-sublevels t)
  14183. (start-level (eq scope 'region-start-level))
  14184. matcher res
  14185. org-todo-keywords-for-agenda
  14186. org-done-keywords-for-agenda
  14187. org-todo-keyword-alist-for-agenda
  14188. org-tag-alist-for-agenda
  14189. org--matcher-tags-todo-only)
  14190. (cond
  14191. ((eq match t) (setq matcher t))
  14192. ((eq match nil) (setq matcher t))
  14193. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14194. (save-excursion
  14195. (save-restriction
  14196. (cond ((eq scope 'tree)
  14197. (org-back-to-heading t)
  14198. (org-narrow-to-subtree)
  14199. (setq scope nil))
  14200. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14201. (org-region-active-p))
  14202. ;; If needed, set start-level to a string like "2"
  14203. (when start-level
  14204. (save-excursion
  14205. (goto-char (region-beginning))
  14206. (unless (org-at-heading-p) (outline-next-heading))
  14207. (setq start-level (org-current-level))))
  14208. (narrow-to-region (region-beginning)
  14209. (save-excursion
  14210. (goto-char (region-end))
  14211. (unless (and (bolp) (org-at-heading-p))
  14212. (outline-next-heading))
  14213. (point)))
  14214. (setq scope nil)))
  14215. (if (not scope)
  14216. (progn
  14217. (org-agenda-prepare-buffers
  14218. (and buffer-file-name (list buffer-file-name)))
  14219. (setq res
  14220. (org-scan-tags
  14221. func matcher org--matcher-tags-todo-only start-level)))
  14222. ;; Get the right scope
  14223. (cond
  14224. ((and scope (listp scope) (symbolp (car scope)))
  14225. (setq scope (eval scope)))
  14226. ((eq scope 'agenda)
  14227. (setq scope (org-agenda-files t)))
  14228. ((eq scope 'agenda-with-archives)
  14229. (setq scope (org-agenda-files t))
  14230. (setq scope (org-add-archive-files scope)))
  14231. ((eq scope 'file)
  14232. (setq scope (and buffer-file-name (list buffer-file-name))))
  14233. ((eq scope 'file-with-archives)
  14234. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14235. (org-agenda-prepare-buffers scope)
  14236. (dolist (file scope)
  14237. (with-current-buffer (org-find-base-buffer-visiting file)
  14238. (org-with-wide-buffer
  14239. (goto-char (point-min))
  14240. (setq res
  14241. (append
  14242. res
  14243. (org-scan-tags
  14244. func matcher org--matcher-tags-todo-only)))))))))
  14245. res)))
  14246. ;;; Properties API
  14247. (defconst org-special-properties
  14248. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14249. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14250. "The special properties valid in Org mode.
  14251. These are properties that are not defined in the property drawer,
  14252. but in some other way.")
  14253. (defconst org-default-properties
  14254. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14255. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14256. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14257. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14258. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14259. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14260. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14261. "Some properties that are used by Org mode for various purposes.
  14262. Being in this list makes sure that they are offered for completion.")
  14263. (defun org--valid-property-p (property)
  14264. "Non nil when string PROPERTY is a valid property name."
  14265. (not
  14266. (or (equal property "")
  14267. (string-match-p "\\s-" property))))
  14268. (defun org--update-property-plist (key val props)
  14269. "Associate KEY to VAL in alist PROPS.
  14270. Modifications are made by side-effect. Return new alist."
  14271. (let* ((appending (string= (substring key -1) "+"))
  14272. (key (if appending (substring key 0 -1) key))
  14273. (old (assoc-string key props t)))
  14274. (if (not old) (cons (cons key val) props)
  14275. (setcdr old (if appending (concat (cdr old) " " val) val))
  14276. props)))
  14277. (defun org-get-property-block (&optional beg force)
  14278. "Return the (beg . end) range of the body of the property drawer.
  14279. BEG is the beginning of the current subtree, or of the part
  14280. before the first headline. If it is not given, it will be found.
  14281. If the drawer does not exist, create it if FORCE is non-nil, or
  14282. return nil."
  14283. (org-with-wide-buffer
  14284. (when beg (goto-char beg))
  14285. (unless (org-before-first-heading-p)
  14286. (let ((beg (cond (beg)
  14287. ((or (not (featurep 'org-inlinetask))
  14288. (org-inlinetask-in-task-p))
  14289. (org-back-to-heading t))
  14290. (t (org-with-limited-levels (org-back-to-heading t))))))
  14291. (forward-line)
  14292. (when (looking-at-p org-planning-line-re) (forward-line))
  14293. (cond ((looking-at org-property-drawer-re)
  14294. (forward-line)
  14295. (cons (point) (progn (goto-char (match-end 0))
  14296. (line-beginning-position))))
  14297. (force
  14298. (goto-char beg)
  14299. (org-insert-property-drawer)
  14300. (let ((pos (save-excursion (search-forward ":END:")
  14301. (line-beginning-position))))
  14302. (cons pos pos))))))))
  14303. (defun org-at-property-p ()
  14304. "Non-nil when point is inside a property drawer.
  14305. See `org-property-re' for match data, if applicable."
  14306. (save-excursion
  14307. (beginning-of-line)
  14308. (and (looking-at org-property-re)
  14309. (let ((property-drawer (save-match-data (org-get-property-block))))
  14310. (and property-drawer
  14311. (>= (point) (car property-drawer))
  14312. (< (point) (cdr property-drawer)))))))
  14313. (defun org-property-action ()
  14314. "Do an action on properties."
  14315. (interactive)
  14316. (unless (org-at-property-p) (user-error "Not at a property"))
  14317. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14318. (let ((c (read-char-exclusive)))
  14319. (cl-case c
  14320. (?s (call-interactively #'org-set-property))
  14321. (?d (call-interactively #'org-delete-property))
  14322. (?D (call-interactively #'org-delete-property-globally))
  14323. (?c (call-interactively #'org-compute-property-at-point))
  14324. (otherwise (user-error "No such property action %c" c)))))
  14325. (defun org-inc-effort ()
  14326. "Increment the value of the effort property in the current entry."
  14327. (interactive)
  14328. (org-set-effort nil t))
  14329. (defvar org-clock-effort) ; Defined in org-clock.el.
  14330. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14331. (defun org-set-effort (&optional value increment)
  14332. "Set the effort property of the current entry.
  14333. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14334. 10th allowed value.
  14335. When INCREMENT is non-nil, set the property to the next allowed value."
  14336. (interactive "P")
  14337. (when (equal value 0) (setq value 10))
  14338. (let* ((completion-ignore-case t)
  14339. (prop org-effort-property)
  14340. (cur (org-entry-get nil prop))
  14341. (allowed (org-property-get-allowed-values nil prop 'table))
  14342. (existing (mapcar 'list (org-property-values prop)))
  14343. (heading (nth 4 (org-heading-components)))
  14344. rpl
  14345. (val (cond
  14346. ((stringp value) value)
  14347. ((and allowed (integerp value))
  14348. (or (car (nth (1- value) allowed))
  14349. (car (org-last allowed))))
  14350. ((and allowed increment)
  14351. (or (cl-caadr (member (list cur) allowed))
  14352. (user-error "Allowed effort values are not set")))
  14353. (allowed
  14354. (message "Select 1-9,0, [RET%s]: %s"
  14355. (if cur (concat "=" cur) "")
  14356. (mapconcat 'car allowed " "))
  14357. (setq rpl (read-char-exclusive))
  14358. (if (equal rpl ?\r)
  14359. cur
  14360. (setq rpl (- rpl ?0))
  14361. (when (equal rpl 0) (setq rpl 10))
  14362. (if (and (> rpl 0) (<= rpl (length allowed)))
  14363. (car (nth (1- rpl) allowed))
  14364. (org-completing-read "Effort: " allowed nil))))
  14365. (t
  14366. (org-completing-read
  14367. (concat "Effort" (and cur (string-match "\\S-" cur)
  14368. (concat " [" cur "]"))
  14369. ": ")
  14370. existing nil nil "" nil cur)))))
  14371. (unless (equal (org-entry-get nil prop) val)
  14372. (org-entry-put nil prop val))
  14373. (org-refresh-property
  14374. '((effort . identity)
  14375. (effort-minutes . org-duration-string-to-minutes))
  14376. val)
  14377. (when (equal heading (bound-and-true-p org-clock-current-task))
  14378. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14379. (org-clock-update-mode-line))
  14380. (message "%s is now %s" prop val)))
  14381. (defun org-entry-properties (&optional pom which)
  14382. "Get all properties of the current entry.
  14383. When POM is a buffer position, get all properties from the entry
  14384. there instead.
  14385. This includes the TODO keyword, the tags, time strings for
  14386. deadline, scheduled, and clocking, and any additional properties
  14387. defined in the entry.
  14388. If WHICH is nil or `all', get all properties. If WHICH is
  14389. `special' or `standard', only get that subclass. If WHICH is
  14390. a string, only get that property.
  14391. Return value is an alist. Keys are properties, as upcased
  14392. strings."
  14393. (org-with-point-at pom
  14394. (when (and (derived-mode-p 'org-mode)
  14395. (ignore-errors (org-back-to-heading t)))
  14396. (catch 'exit
  14397. (let* ((beg (point))
  14398. (specific (and (stringp which) (upcase which)))
  14399. (which (cond ((not specific) which)
  14400. ((member specific org-special-properties) 'special)
  14401. (t 'standard)))
  14402. props)
  14403. ;; Get the special properties, like TODO and TAGS.
  14404. (when (memq which '(nil all special))
  14405. (when (or (not specific) (string= specific "CLOCKSUM"))
  14406. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14407. (when clocksum
  14408. (push (cons "CLOCKSUM"
  14409. (org-minutes-to-clocksum-string clocksum))
  14410. props)))
  14411. (when specific (throw 'exit props)))
  14412. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14413. (let ((clocksumt (get-text-property (point)
  14414. :org-clock-minutes-today)))
  14415. (when clocksumt
  14416. (push (cons "CLOCKSUM_T"
  14417. (org-minutes-to-clocksum-string clocksumt))
  14418. props)))
  14419. (when specific (throw 'exit props)))
  14420. (when (or (not specific) (string= specific "ITEM"))
  14421. (let ((case-fold-search nil))
  14422. (when (looking-at org-complex-heading-regexp)
  14423. (push (cons "ITEM"
  14424. (let ((title (match-string-no-properties 4)))
  14425. (if (org-string-nw-p title)
  14426. (org-remove-tabs title)
  14427. "")))
  14428. props)))
  14429. (when specific (throw 'exit props)))
  14430. (when (or (not specific) (string= specific "TODO"))
  14431. (let ((case-fold-search nil))
  14432. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14433. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14434. (when specific (throw 'exit props)))
  14435. (when (or (not specific) (string= specific "PRIORITY"))
  14436. (push (cons "PRIORITY"
  14437. (if (looking-at org-priority-regexp)
  14438. (match-string-no-properties 2)
  14439. (char-to-string org-default-priority)))
  14440. props)
  14441. (when specific (throw 'exit props)))
  14442. (when (or (not specific) (string= specific "FILE"))
  14443. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14444. props)
  14445. (when specific (throw 'exit props)))
  14446. (when (or (not specific) (string= specific "TAGS"))
  14447. (let ((value (org-string-nw-p (org-get-tags-string))))
  14448. (when value (push (cons "TAGS" value) props)))
  14449. (when specific (throw 'exit props)))
  14450. (when (or (not specific) (string= specific "ALLTAGS"))
  14451. (let ((value (org-get-tags-at)))
  14452. (when value
  14453. (push (cons "ALLTAGS"
  14454. (format ":%s:" (mapconcat #'identity value ":")))
  14455. props)))
  14456. (when specific (throw 'exit props)))
  14457. (when (or (not specific) (string= specific "BLOCKED"))
  14458. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14459. (when specific (throw 'exit props)))
  14460. (when (or (not specific)
  14461. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14462. (forward-line)
  14463. (when (looking-at-p org-planning-line-re)
  14464. (end-of-line)
  14465. (let ((bol (line-beginning-position))
  14466. ;; Backward compatibility: time keywords used to
  14467. ;; be configurable (before 8.3). Make sure we
  14468. ;; get the correct keyword.
  14469. (key-assoc `(("CLOSED" . ,org-closed-string)
  14470. ("DEADLINE" . ,org-deadline-string)
  14471. ("SCHEDULED" . ,org-scheduled-string))))
  14472. (dolist (pair (if specific (list (assoc specific key-assoc))
  14473. key-assoc))
  14474. (save-excursion
  14475. (when (search-backward (cdr pair) bol t)
  14476. (goto-char (match-end 0))
  14477. (skip-chars-forward " \t")
  14478. (and (looking-at org-ts-regexp-both)
  14479. (push (cons (car pair)
  14480. (match-string-no-properties 0))
  14481. props)))))))
  14482. (when specific (throw 'exit props)))
  14483. (when (or (not specific)
  14484. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14485. (let ((find-ts
  14486. (lambda (end ts)
  14487. ;; Fix next time-stamp before END. TS is the
  14488. ;; list of time-stamps found so far.
  14489. (let ((ts ts)
  14490. (regexp (cond
  14491. ((string= specific "TIMESTAMP")
  14492. org-ts-regexp)
  14493. ((string= specific "TIMESTAMP_IA")
  14494. org-ts-regexp-inactive)
  14495. ((assoc "TIMESTAMP_IA" ts)
  14496. org-ts-regexp)
  14497. ((assoc "TIMESTAMP" ts)
  14498. org-ts-regexp-inactive)
  14499. (t org-ts-regexp-both))))
  14500. (catch 'next
  14501. (while (re-search-forward regexp end t)
  14502. (backward-char)
  14503. (let ((object (org-element-context)))
  14504. ;; Accept to match timestamps in node
  14505. ;; properties, too.
  14506. (when (memq (org-element-type object)
  14507. '(node-property timestamp))
  14508. (let ((type
  14509. (org-element-property :type object)))
  14510. (cond
  14511. ((and (memq type '(active active-range))
  14512. (not (equal specific "TIMESTAMP_IA")))
  14513. (unless (assoc "TIMESTAMP" ts)
  14514. (push (cons "TIMESTAMP"
  14515. (org-element-property
  14516. :raw-value object))
  14517. ts)
  14518. (when specific (throw 'exit ts))))
  14519. ((and (memq type '(inactive inactive-range))
  14520. (not (string= specific "TIMESTAMP")))
  14521. (unless (assoc "TIMESTAMP_IA" ts)
  14522. (push (cons "TIMESTAMP_IA"
  14523. (org-element-property
  14524. :raw-value object))
  14525. ts)
  14526. (when specific (throw 'exit ts))))))
  14527. ;; Both timestamp types are found,
  14528. ;; move to next part.
  14529. (when (= (length ts) 2) (throw 'next ts)))))
  14530. ts)))))
  14531. (goto-char beg)
  14532. ;; First look for timestamps within headline.
  14533. (let ((ts (funcall find-ts (line-end-position) nil)))
  14534. (if (= (length ts) 2) (setq props (nconc ts props))
  14535. (forward-line)
  14536. ;; Then find timestamps in the section, skipping
  14537. ;; planning line.
  14538. (when (looking-at-p org-planning-line-re)
  14539. (forward-line))
  14540. (let ((end (save-excursion (outline-next-heading))))
  14541. (setq props (nconc (funcall find-ts end ts) props))))))))
  14542. ;; Get the standard properties, like :PROP:.
  14543. (when (memq which '(nil all standard))
  14544. ;; If we are looking after a specific property, delegate
  14545. ;; to `org-entry-get', which is faster. However, make an
  14546. ;; exception for "CATEGORY", since it can be also set
  14547. ;; through keywords (i.e. #+CATEGORY).
  14548. (if (and specific (not (equal specific "CATEGORY")))
  14549. (let ((value (org-entry-get beg specific nil t)))
  14550. (throw 'exit (and value (list (cons specific value)))))
  14551. (let ((range (org-get-property-block beg)))
  14552. (when range
  14553. (let ((end (cdr range)) seen-base)
  14554. (goto-char (car range))
  14555. ;; Unlike to `org--update-property-plist', we
  14556. ;; handle the case where base values is found
  14557. ;; after its extension. We also forbid standard
  14558. ;; properties to be named as special properties.
  14559. (while (re-search-forward org-property-re end t)
  14560. (let* ((key (upcase (match-string-no-properties 2)))
  14561. (extendp (string-match-p "\\+\\'" key))
  14562. (key-base (if extendp (substring key 0 -1) key))
  14563. (value (match-string-no-properties 3)))
  14564. (cond
  14565. ((member-ignore-case key-base org-special-properties))
  14566. (extendp
  14567. (setq props
  14568. (org--update-property-plist key value props)))
  14569. ((member key seen-base))
  14570. (t (push key seen-base)
  14571. (let ((p (assoc-string key props t)))
  14572. (if p (setcdr p (concat value " " (cdr p)))
  14573. (push (cons key value) props))))))))))))
  14574. (unless (assoc "CATEGORY" props)
  14575. (push (cons "CATEGORY" (org-get-category beg)) props)
  14576. (when (string= specific "CATEGORY") (throw 'exit props)))
  14577. ;; Return value.
  14578. props)))))
  14579. (defun org-property--local-values (property literal-nil)
  14580. "Return value for PROPERTY in current entry.
  14581. Value is a list whose car is the base value for PROPERTY and cdr
  14582. a list of accumulated values. Return nil if neither is found in
  14583. the entry. Also return nil when PROPERTY is set to \"nil\",
  14584. unless LITERAL-NIL is non-nil."
  14585. (let ((range (org-get-property-block)))
  14586. (when range
  14587. (goto-char (car range))
  14588. (let* ((case-fold-search t)
  14589. (end (cdr range))
  14590. (value
  14591. ;; Base value.
  14592. (save-excursion
  14593. (let ((v (and (re-search-forward
  14594. (org-re-property property nil t) end t)
  14595. (match-string-no-properties 3))))
  14596. (list (if literal-nil v (org-not-nil v)))))))
  14597. ;; Find additional values.
  14598. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14599. (while (re-search-forward property+ end t)
  14600. (push (match-string-no-properties 3) value)))
  14601. ;; Return final values.
  14602. (and (not (equal value '(nil))) (nreverse value))))))
  14603. (defun org-entry-get (pom property &optional inherit literal-nil)
  14604. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14605. If INHERIT is non-nil and the entry does not have the property,
  14606. then also check higher levels of the hierarchy. If INHERIT is
  14607. the symbol `selective', use inheritance only if the setting in
  14608. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14609. If the property is present but empty, the return value is the
  14610. empty string. If the property is not present at all, nil is
  14611. returned. In any other case, return the value as a string.
  14612. Search is case-insensitive.
  14613. If LITERAL-NIL is set, return the string value \"nil\" as
  14614. a string, do not interpret it as the list atom nil. This is used
  14615. for inheritance when a \"nil\" value can supersede a non-nil
  14616. value higher up the hierarchy."
  14617. (org-with-point-at pom
  14618. (cond
  14619. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14620. ;; We need a special property. Use `org-entry-properties' to
  14621. ;; retrieve it, but specify the wanted property.
  14622. (cdr (assoc-string property (org-entry-properties nil property))))
  14623. ((and inherit
  14624. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14625. (org-entry-get-with-inheritance property literal-nil))
  14626. (t
  14627. (let* ((local (org-property--local-values property literal-nil))
  14628. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14629. (if literal-nil value (org-not-nil value)))))))
  14630. (defun org-property-or-variable-value (var &optional inherit)
  14631. "Check if there is a property fixing the value of VAR.
  14632. If yes, return this value. If not, return the current value of the variable."
  14633. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14634. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14635. (read prop)
  14636. (symbol-value var))))
  14637. (defun org-entry-delete (pom property)
  14638. "Delete PROPERTY from entry at point-or-marker POM.
  14639. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14640. non-nil when a property was removed."
  14641. (unless (member property org-special-properties)
  14642. (org-with-point-at pom
  14643. (let ((range (org-get-property-block)))
  14644. (when range
  14645. (let* ((begin (car range))
  14646. (origin (cdr range))
  14647. (end (copy-marker origin))
  14648. (re (org-re-property
  14649. (concat (regexp-quote property) "\\+?") t t)))
  14650. (goto-char begin)
  14651. (while (re-search-forward re end t)
  14652. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14653. ;; If drawer is empty, remove it altogether.
  14654. (when (= begin end)
  14655. (delete-region (line-beginning-position 0)
  14656. (line-beginning-position 2)))
  14657. ;; Return non-nil if some property was removed.
  14658. (prog1 (/= end origin) (set-marker end nil))))))))
  14659. ;; Multi-values properties are properties that contain multiple values
  14660. ;; These values are assumed to be single words, separated by whitespace.
  14661. (defun org-entry-add-to-multivalued-property (pom property value)
  14662. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14663. (let* ((old (org-entry-get pom property))
  14664. (values (and old (org-split-string old "[ \t]"))))
  14665. (setq value (org-entry-protect-space value))
  14666. (unless (member value values)
  14667. (setq values (append values (list value)))
  14668. (org-entry-put pom property
  14669. (mapconcat 'identity values " ")))))
  14670. (defun org-entry-remove-from-multivalued-property (pom property value)
  14671. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14672. (let* ((old (org-entry-get pom property))
  14673. (values (and old (org-split-string old "[ \t]"))))
  14674. (setq value (org-entry-protect-space value))
  14675. (when (member value values)
  14676. (setq values (delete value values))
  14677. (org-entry-put pom property
  14678. (mapconcat 'identity values " ")))))
  14679. (defun org-entry-member-in-multivalued-property (pom property value)
  14680. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14681. (let* ((old (org-entry-get pom property))
  14682. (values (and old (org-split-string old "[ \t]"))))
  14683. (setq value (org-entry-protect-space value))
  14684. (member value values)))
  14685. (defun org-entry-get-multivalued-property (pom property)
  14686. "Return a list of values in a multivalued property."
  14687. (let* ((value (org-entry-get pom property))
  14688. (values (and value (org-split-string value "[ \t]"))))
  14689. (mapcar 'org-entry-restore-space values)))
  14690. (defun org-entry-put-multivalued-property (pom property &rest values)
  14691. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14692. VALUES should be a list of strings. Spaces will be protected."
  14693. (org-entry-put pom property
  14694. (mapconcat 'org-entry-protect-space values " "))
  14695. (let* ((value (org-entry-get pom property))
  14696. (values (and value (org-split-string value "[ \t]"))))
  14697. (mapcar 'org-entry-restore-space values)))
  14698. (defun org-entry-protect-space (s)
  14699. "Protect spaces and newline in string S."
  14700. (while (string-match " " s)
  14701. (setq s (replace-match "%20" t t s)))
  14702. (while (string-match "\n" s)
  14703. (setq s (replace-match "%0A" t t s)))
  14704. s)
  14705. (defun org-entry-restore-space (s)
  14706. "Restore spaces and newline in string S."
  14707. (while (string-match "%20" s)
  14708. (setq s (replace-match " " t t s)))
  14709. (while (string-match "%0A" s)
  14710. (setq s (replace-match "\n" t t s)))
  14711. s)
  14712. (defvar org-entry-property-inherited-from (make-marker)
  14713. "Marker pointing to the entry from where a property was inherited.
  14714. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14715. location of the entry where the inheritance search matched. If there was
  14716. no match, the marker will point nowhere.
  14717. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14718. is set.")
  14719. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14720. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14721. The search will stop at the first ancestor which has the property defined.
  14722. If the value found is \"nil\", return nil to show that the property
  14723. should be considered as undefined (this is the meaning of nil here).
  14724. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14725. (move-marker org-entry-property-inherited-from nil)
  14726. (org-with-wide-buffer
  14727. (let (value)
  14728. (catch 'exit
  14729. (while t
  14730. (let ((v (org-property--local-values property literal-nil)))
  14731. (when v
  14732. (setq value
  14733. (concat (mapconcat #'identity (delq nil v) " ")
  14734. (and value " ")
  14735. value)))
  14736. (cond
  14737. ((car v)
  14738. (org-back-to-heading t)
  14739. (move-marker org-entry-property-inherited-from (point))
  14740. (throw 'exit nil))
  14741. ((org-up-heading-safe))
  14742. (t
  14743. (let ((global
  14744. (cdr (or (assoc-string property org-file-properties t)
  14745. (assoc-string property org-global-properties t)
  14746. (assoc-string property org-global-properties-fixed t)))))
  14747. (cond ((not global))
  14748. (value (setq value (concat global " " value)))
  14749. (t (setq value global))))
  14750. (throw 'exit nil))))))
  14751. (if literal-nil value (org-not-nil value)))))
  14752. (defvar org-property-changed-functions nil
  14753. "Hook called when the value of a property has changed.
  14754. Each hook function should accept two arguments, the name of the property
  14755. and the new value.")
  14756. (defun org-entry-put (pom property value)
  14757. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14758. If the value is nil, it is converted to the empty string. If it
  14759. is not a string, an error is raised. Also raise an error on
  14760. invalid property names.
  14761. PROPERTY can be any regular property (see
  14762. `org-special-properties'). It can also be \"TODO\",
  14763. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14764. For the last two properties, VALUE may have any of the special
  14765. values \"earlier\" and \"later\". The function then increases or
  14766. decreases scheduled or deadline date by one day."
  14767. (cond ((null value) (setq value ""))
  14768. ((not (stringp value)) (error "Properties values should be strings"))
  14769. ((not (org--valid-property-p property))
  14770. (user-error "Invalid property name: \"%s\"" property)))
  14771. (org-with-point-at pom
  14772. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14773. (org-back-to-heading t)
  14774. (org-with-limited-levels (org-back-to-heading t)))
  14775. (let ((beg (point)))
  14776. (cond
  14777. ((equal property "TODO")
  14778. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14779. ((not (member value org-todo-keywords-1))
  14780. (user-error "\"%s\" is not a valid TODO state" value)))
  14781. (org-todo value)
  14782. (org-set-tags nil 'align))
  14783. ((equal property "PRIORITY")
  14784. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14785. (org-set-tags nil 'align))
  14786. ((equal property "SCHEDULED")
  14787. (forward-line)
  14788. (if (and (looking-at-p org-planning-line-re)
  14789. (re-search-forward
  14790. org-scheduled-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-schedule '(4)))
  14794. (t (org-schedule nil value)))
  14795. (if (member value '("earlier" "later" ""))
  14796. (call-interactively #'org-schedule)
  14797. (org-schedule nil value))))
  14798. ((equal property "DEADLINE")
  14799. (forward-line)
  14800. (if (and (looking-at-p org-planning-line-re)
  14801. (re-search-forward
  14802. org-deadline-time-regexp (line-end-position) t))
  14803. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14804. ((string= value "later") (org-timestamp-change 1 'day))
  14805. ((string= value "") (org-deadline '(4)))
  14806. (t (org-deadline nil value)))
  14807. (if (member value '("earlier" "later" ""))
  14808. (call-interactively #'org-deadline)
  14809. (org-deadline nil value))))
  14810. ((member property org-special-properties)
  14811. (error "The %s property cannot be set with `org-entry-put'" property))
  14812. (t
  14813. (let* ((range (org-get-property-block beg 'force))
  14814. (end (cdr range))
  14815. (case-fold-search t))
  14816. (goto-char (car range))
  14817. (if (re-search-forward (org-re-property property nil t) end t)
  14818. (progn (delete-region (match-beginning 0) (match-end 0))
  14819. (goto-char (match-beginning 0)))
  14820. (goto-char end)
  14821. (insert "\n")
  14822. (backward-char))
  14823. (insert ":" property ":")
  14824. (when value (insert " " value))
  14825. (org-indent-line)))))
  14826. (run-hook-with-args 'org-property-changed-functions property value)))
  14827. (defun org-buffer-property-keys
  14828. (&optional specials defaults columns ignore-malformed)
  14829. "Get all property keys in the current buffer.
  14830. When SPECIALS is non-nil, also list the special properties that
  14831. reflect things like tags and TODO state.
  14832. When DEFAULTS is non-nil, also include properties that has
  14833. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14834. DESCRIPTION, LOCATION, and LOGGING and others.
  14835. When COLUMNS in non-nil, also include property names given in
  14836. COLUMN formats in the current buffer.
  14837. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14838. automatically performed, such drawers will be silently ignored."
  14839. (let ((case-fold-search t)
  14840. (props (append
  14841. (and specials org-special-properties)
  14842. (and defaults (cons org-effort-property org-default-properties))
  14843. nil)))
  14844. (org-with-wide-buffer
  14845. (goto-char (point-min))
  14846. (while (re-search-forward org-property-start-re nil t)
  14847. (let ((range (org-get-property-block)))
  14848. (catch 'skip
  14849. (unless range
  14850. (when (and (not ignore-malformed)
  14851. (not (org-before-first-heading-p))
  14852. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14853. (line-beginning-position))))
  14854. (org-get-property-block nil t))
  14855. (throw 'skip nil))
  14856. (goto-char (car range))
  14857. (let ((begin (car range))
  14858. (end (cdr range)))
  14859. ;; Make sure that found property block is not located
  14860. ;; before current point, as it would generate an infloop.
  14861. ;; It can happen, for example, in the following
  14862. ;; situation:
  14863. ;;
  14864. ;; * Headline
  14865. ;; :PROPERTIES:
  14866. ;; ...
  14867. ;; :END:
  14868. ;; *************** Inlinetask
  14869. ;; #+BEGIN_EXAMPLE
  14870. ;; :PROPERTIES:
  14871. ;; #+END_EXAMPLE
  14872. ;;
  14873. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14874. (while (< (point) end)
  14875. (let ((p (progn (looking-at org-property-re)
  14876. (match-string-no-properties 2))))
  14877. ;; Only add true property name, not extension symbol.
  14878. (push (if (not (string-match-p "\\+\\'" p)) p
  14879. (substring p 0 -1))
  14880. props))
  14881. (forward-line))))
  14882. (outline-next-heading)))
  14883. (when columns
  14884. (goto-char (point-min))
  14885. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14886. (let ((element (org-element-at-point)))
  14887. (when (memq (org-element-type element) '(keyword node-property))
  14888. (let ((value (org-element-property :value element))
  14889. (start 0))
  14890. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14891. (setq start (match-end 0))
  14892. (let ((p (match-string-no-properties 1 value)))
  14893. (unless (member-ignore-case p org-special-properties)
  14894. (push p props))))))))))
  14895. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14896. (defun org-property-values (key)
  14897. "List all non-nil values of property KEY in current buffer."
  14898. (org-with-wide-buffer
  14899. (goto-char (point-min))
  14900. (let ((case-fold-search t)
  14901. (re (org-re-property key))
  14902. values)
  14903. (while (re-search-forward re nil t)
  14904. (push (org-entry-get (point) key) values))
  14905. (delete-dups values))))
  14906. (defun org-insert-property-drawer ()
  14907. "Insert a property drawer into the current entry."
  14908. (org-with-wide-buffer
  14909. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14910. (org-back-to-heading t)
  14911. (org-with-limited-levels (org-back-to-heading t)))
  14912. (forward-line)
  14913. (when (looking-at-p org-planning-line-re) (forward-line))
  14914. (unless (looking-at-p org-property-drawer-re)
  14915. ;; Make sure we start editing a line from current entry, not from
  14916. ;; next one. It prevents extending text properties or overlays
  14917. ;; belonging to the latter.
  14918. (when (bolp) (backward-char))
  14919. (let ((begin (1+ (point)))
  14920. (inhibit-read-only t))
  14921. (insert "\n:PROPERTIES:\n:END:")
  14922. (when (eobp) (insert "\n"))
  14923. (org-indent-region begin (point))))))
  14924. (defun org-insert-drawer (&optional arg drawer)
  14925. "Insert a drawer at point.
  14926. When optional argument ARG is non-nil, insert a property drawer.
  14927. Optional argument DRAWER, when non-nil, is a string representing
  14928. drawer's name. Otherwise, the user is prompted for a name.
  14929. If a region is active, insert the drawer around that region
  14930. instead.
  14931. Point is left between drawer's boundaries."
  14932. (interactive "P")
  14933. (let* ((drawer (if arg "PROPERTIES"
  14934. (or drawer (read-from-minibuffer "Drawer: ")))))
  14935. (cond
  14936. ;; With C-u, fall back on `org-insert-property-drawer'
  14937. (arg (org-insert-property-drawer))
  14938. ;; Check validity of suggested drawer's name.
  14939. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14940. (user-error "Invalid drawer name"))
  14941. ;; With an active region, insert a drawer at point.
  14942. ((not (org-region-active-p))
  14943. (progn
  14944. (unless (bolp) (insert "\n"))
  14945. (insert (format ":%s:\n\n:END:\n" drawer))
  14946. (forward-line -2)))
  14947. ;; Otherwise, insert the drawer at point
  14948. (t
  14949. (let ((rbeg (region-beginning))
  14950. (rend (copy-marker (region-end))))
  14951. (unwind-protect
  14952. (progn
  14953. (goto-char rbeg)
  14954. (beginning-of-line)
  14955. (when (save-excursion
  14956. (re-search-forward org-outline-regexp-bol rend t))
  14957. (user-error "Drawers cannot contain headlines"))
  14958. ;; Position point at the beginning of the first
  14959. ;; non-blank line in region. Insert drawer's opening
  14960. ;; there, then indent it.
  14961. (org-skip-whitespace)
  14962. (beginning-of-line)
  14963. (insert ":" drawer ":\n")
  14964. (forward-line -1)
  14965. (indent-for-tab-command)
  14966. ;; Move point to the beginning of the first blank line
  14967. ;; after the last non-blank line in region. Insert
  14968. ;; drawer's closing, then indent it.
  14969. (goto-char rend)
  14970. (skip-chars-backward " \r\t\n")
  14971. (insert "\n:END:")
  14972. (deactivate-mark t)
  14973. (indent-for-tab-command)
  14974. (unless (eolp) (insert "\n")))
  14975. ;; Clear marker, whatever the outcome of insertion is.
  14976. (set-marker rend nil)))))))
  14977. (defvar org-property-set-functions-alist nil
  14978. "Property set function alist.
  14979. Each entry should have the following format:
  14980. (PROPERTY . READ-FUNCTION)
  14981. The read function will be called with the same argument as
  14982. `org-completing-read'.")
  14983. (defun org-set-property-function (property)
  14984. "Get the function that should be used to set PROPERTY.
  14985. This is computed according to `org-property-set-functions-alist'."
  14986. (or (cdr (assoc property org-property-set-functions-alist))
  14987. 'org-completing-read))
  14988. (defun org-read-property-value (property)
  14989. "Read PROPERTY value from user."
  14990. (let* ((completion-ignore-case t)
  14991. (allowed (org-property-get-allowed-values nil property 'table))
  14992. (cur (org-entry-get nil property))
  14993. (prompt (concat property " value"
  14994. (if (and cur (string-match "\\S-" cur))
  14995. (concat " [" cur "]") "") ": "))
  14996. (set-function (org-set-property-function property))
  14997. (val (if allowed
  14998. (funcall set-function prompt allowed nil
  14999. (not (get-text-property 0 'org-unrestricted
  15000. (caar allowed))))
  15001. (funcall set-function prompt
  15002. (mapcar 'list (org-property-values property))
  15003. nil nil "" nil cur))))
  15004. (org-trim val)))
  15005. (defvar org-last-set-property nil)
  15006. (defvar org-last-set-property-value nil)
  15007. (defun org-read-property-name ()
  15008. "Read a property name."
  15009. (let ((completion-ignore-case t)
  15010. (default-prop (or (and (org-at-property-p)
  15011. (match-string-no-properties 2))
  15012. org-last-set-property)))
  15013. (org-completing-read
  15014. (concat "Property"
  15015. (if default-prop (concat " [" default-prop "]") "")
  15016. ": ")
  15017. (mapcar #'list (org-buffer-property-keys nil t t))
  15018. nil nil nil nil default-prop)))
  15019. (defun org-set-property-and-value (use-last)
  15020. "Allow to set [PROPERTY]: [value] direction from prompt.
  15021. When use-default, don't even ask, just use the last
  15022. \"[PROPERTY]: [value]\" string from the history."
  15023. (interactive "P")
  15024. (let* ((completion-ignore-case t)
  15025. (pv (or (and use-last org-last-set-property-value)
  15026. (org-completing-read
  15027. "Enter a \"[Property]: [value]\" pair: "
  15028. nil nil nil nil nil
  15029. org-last-set-property-value)))
  15030. prop val)
  15031. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  15032. (setq prop (match-string 1 pv)
  15033. val (match-string 2 pv))
  15034. (org-set-property prop val))))
  15035. (defun org-set-property (property value)
  15036. "In the current entry, set PROPERTY to VALUE.
  15037. When called interactively, this will prompt for a property name, offering
  15038. completion on existing and default properties. And then it will prompt
  15039. for a value, offering completion either on allowed values (via an inherited
  15040. xxx_ALL property) or on existing values in other instances of this property
  15041. in the current file.
  15042. Throw an error when trying to set a property with an invalid name."
  15043. (interactive (list nil nil))
  15044. (let ((property (or property (org-read-property-name))))
  15045. ;; `org-entry-put' also makes the following check, but this one
  15046. ;; avoids polluting `org-last-set-property' and
  15047. ;; `org-last-set-property-value' needlessly.
  15048. (unless (org--valid-property-p property)
  15049. (user-error "Invalid property name: \"%s\"" property))
  15050. (let ((value (or value (org-read-property-value property)))
  15051. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15052. (setq org-last-set-property property)
  15053. (setq org-last-set-property-value (concat property ": " value))
  15054. ;; Possibly postprocess the inserted value:
  15055. (when fn (setq value (funcall fn value)))
  15056. (unless (equal (org-entry-get nil property) value)
  15057. (org-entry-put nil property value)))))
  15058. (defun org-find-property (property &optional value)
  15059. "Find first entry in buffer that sets PROPERTY.
  15060. When optional argument VALUE is non-nil, only consider an entry
  15061. if it contains PROPERTY set to this value. If PROPERTY should be
  15062. explicitly set to nil, use string \"nil\" for VALUE.
  15063. Return position where the entry begins, or nil if there is no
  15064. such entry. If narrowing is in effect, only search the visible
  15065. part of the buffer."
  15066. (save-excursion
  15067. (goto-char (point-min))
  15068. (let ((case-fold-search t)
  15069. (re (org-re-property property nil (not value) value)))
  15070. (catch 'exit
  15071. (while (re-search-forward re nil t)
  15072. (when (if value (org-at-property-p)
  15073. (org-entry-get (point) property nil t))
  15074. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15075. (defun org-delete-property (property)
  15076. "In the current entry, delete PROPERTY."
  15077. (interactive
  15078. (let* ((completion-ignore-case t)
  15079. (cat (org-entry-get (point) "CATEGORY"))
  15080. (props0 (org-entry-properties nil 'standard))
  15081. (props (if cat props0
  15082. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15083. (prop (if (< 1 (length props))
  15084. (completing-read "Property: " props nil t)
  15085. (caar props))))
  15086. (list prop)))
  15087. (if (not property)
  15088. (message "No property to delete in this entry")
  15089. (org-entry-delete nil property)
  15090. (message "Property \"%s\" deleted" property)))
  15091. (defun org-delete-property-globally (property)
  15092. "Remove PROPERTY globally, from all entries.
  15093. This function ignores narrowing, if any."
  15094. (interactive
  15095. (let* ((completion-ignore-case t)
  15096. (prop (completing-read
  15097. "Globally remove property: "
  15098. (mapcar #'list (org-buffer-property-keys)))))
  15099. (list prop)))
  15100. (org-with-wide-buffer
  15101. (goto-char (point-min))
  15102. (let ((count 0)
  15103. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15104. (while (re-search-forward re nil t)
  15105. (when (org-entry-delete (point) property) (cl-incf count)))
  15106. (message "Property \"%s\" removed from %d entries" property count))))
  15107. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15108. (defun org-compute-property-at-point ()
  15109. "Compute the property at point.
  15110. This looks for an enclosing column format, extracts the operator and
  15111. then applies it to the property in the column format's scope."
  15112. (interactive)
  15113. (unless (org-at-property-p)
  15114. (user-error "Not at a property"))
  15115. (let ((prop (match-string-no-properties 2)))
  15116. (org-columns-get-format-and-top-level)
  15117. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15118. (user-error "No operator defined for property %s" prop))
  15119. (org-columns-compute prop)))
  15120. (defvar org-property-allowed-value-functions nil
  15121. "Hook for functions supplying allowed values for a specific property.
  15122. The functions must take a single argument, the name of the property, and
  15123. return a flat list of allowed values. If \":ETC\" is one of
  15124. the values, this means that these values are intended as defaults for
  15125. completion, but that other values should be allowed too.
  15126. The functions must return nil if they are not responsible for this
  15127. property.")
  15128. (defun org-property-get-allowed-values (pom property &optional table)
  15129. "Get allowed values for the property PROPERTY.
  15130. When TABLE is non-nil, return an alist that can directly be used for
  15131. completion."
  15132. (let (vals)
  15133. (cond
  15134. ((equal property "TODO")
  15135. (setq vals (org-with-point-at pom
  15136. (append org-todo-keywords-1 '("")))))
  15137. ((equal property "PRIORITY")
  15138. (let ((n org-lowest-priority))
  15139. (while (>= n org-highest-priority)
  15140. (push (char-to-string n) vals)
  15141. (setq n (1- n)))))
  15142. ((equal property "CATEGORY"))
  15143. ((member property org-special-properties))
  15144. ((setq vals (run-hook-with-args-until-success
  15145. 'org-property-allowed-value-functions property)))
  15146. (t
  15147. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15148. (when (and vals (string-match "\\S-" vals))
  15149. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15150. (setq vals (mapcar (lambda (x)
  15151. (cond ((stringp x) x)
  15152. ((numberp x) (number-to-string x))
  15153. ((symbolp x) (symbol-name x))
  15154. (t "???")))
  15155. vals)))))
  15156. (when (member ":ETC" vals)
  15157. (setq vals (remove ":ETC" vals))
  15158. (org-add-props (car vals) '(org-unrestricted t)))
  15159. (if table (mapcar 'list vals) vals)))
  15160. (defun org-property-previous-allowed-value (&optional _previous)
  15161. "Switch to the next allowed value for this property."
  15162. (interactive)
  15163. (org-property-next-allowed-value t))
  15164. (defun org-property-next-allowed-value (&optional previous)
  15165. "Switch to the next allowed value for this property."
  15166. (interactive)
  15167. (unless (org-at-property-p)
  15168. (user-error "Not at a property"))
  15169. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15170. (key (match-string 2))
  15171. (value (match-string 3))
  15172. (allowed (or (org-property-get-allowed-values (point) key)
  15173. (and (member value '("[ ]" "[-]" "[X]"))
  15174. '("[ ]" "[X]"))))
  15175. (heading (save-match-data (nth 4 (org-heading-components))))
  15176. nval)
  15177. (unless allowed
  15178. (user-error "Allowed values for this property have not been defined"))
  15179. (when previous (setq allowed (reverse allowed)))
  15180. (when (member value allowed)
  15181. (setq nval (car (cdr (member value allowed)))))
  15182. (setq nval (or nval (car allowed)))
  15183. (when (equal nval value)
  15184. (user-error "Only one allowed value for this property"))
  15185. (org-at-property-p)
  15186. (replace-match (concat " :" key ": " nval) t t)
  15187. (org-indent-line)
  15188. (beginning-of-line 1)
  15189. (skip-chars-forward " \t")
  15190. (when (equal prop org-effort-property)
  15191. (org-refresh-property
  15192. '((effort . identity)
  15193. (effort-minutes . org-duration-string-to-minutes))
  15194. nval)
  15195. (when (string= org-clock-current-task heading)
  15196. (setq org-clock-effort nval)
  15197. (org-clock-update-mode-line)))
  15198. (run-hook-with-args 'org-property-changed-functions key nval)))
  15199. (defun org-find-olp (path &optional this-buffer)
  15200. "Return a marker pointing to the entry at outline path OLP.
  15201. If anything goes wrong, throw an error.
  15202. You can wrap this call to catch the error like this:
  15203. (condition-case msg
  15204. (org-mobile-locate-entry (match-string 4))
  15205. (error (nth 1 msg)))
  15206. The return value will then be either a string with the error message,
  15207. or a marker if everything is OK.
  15208. If THIS-BUFFER is set, the outline path does not contain a file,
  15209. only headings."
  15210. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15211. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15212. (level 1)
  15213. (lmin 1)
  15214. (lmax 1)
  15215. end found flevel)
  15216. (unless buffer (error "File not found :%s" file))
  15217. (with-current-buffer buffer
  15218. (org-with-wide-buffer
  15219. (goto-char (point-min))
  15220. (dolist (heading path)
  15221. (let ((re (format org-complex-heading-regexp-format
  15222. (regexp-quote heading)))
  15223. (cnt 0))
  15224. (while (re-search-forward re end t)
  15225. (setq level (- (match-end 1) (match-beginning 1)))
  15226. (when (and (>= level lmin) (<= level lmax))
  15227. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15228. (when (= cnt 0)
  15229. (error "Heading not found on level %d: %s" lmax heading))
  15230. (when (> cnt 1)
  15231. (error "Heading not unique on level %d: %s" lmax heading))
  15232. (goto-char found)
  15233. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15234. (setq end (save-excursion (org-end-of-subtree t t)))))
  15235. (when (org-at-heading-p)
  15236. (point-marker))))))
  15237. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15238. "Find node HEADING in BUFFER.
  15239. Return a marker to the heading if it was found, or nil if not.
  15240. If POS-ONLY is set, return just the position instead of a marker.
  15241. The heading text must match exact, but it may have a TODO keyword,
  15242. a priority cookie and tags in the standard locations."
  15243. (with-current-buffer (or buffer (current-buffer))
  15244. (org-with-wide-buffer
  15245. (goto-char (point-min))
  15246. (let (case-fold-search)
  15247. (when (re-search-forward
  15248. (format org-complex-heading-regexp-format
  15249. (regexp-quote heading)) nil t)
  15250. (if pos-only
  15251. (match-beginning 0)
  15252. (move-marker (make-marker) (match-beginning 0))))))))
  15253. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15254. "Find Org node headline HEADING in all .org files in directory DIR.
  15255. When the target headline is found, return a marker to this location."
  15256. (let ((files (directory-files (or dir default-directory)
  15257. t "\\`[^.#].*\\.org\\'"))
  15258. visiting m buffer)
  15259. (catch 'found
  15260. (dolist (file files)
  15261. (message "trying %s" file)
  15262. (setq visiting (org-find-base-buffer-visiting file))
  15263. (setq buffer (or visiting (find-file-noselect file)))
  15264. (setq m (org-find-exact-headline-in-buffer
  15265. heading buffer))
  15266. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15267. (and m (throw 'found m))))))
  15268. (defun org-find-entry-with-id (ident)
  15269. "Locate the entry that contains the ID property with exact value IDENT.
  15270. IDENT can be a string, a symbol or a number, this function will search for
  15271. the string representation of it.
  15272. Return the position where this entry starts, or nil if there is no such entry."
  15273. (interactive "sID: ")
  15274. (let ((id (cond
  15275. ((stringp ident) ident)
  15276. ((symbolp ident) (symbol-name ident))
  15277. ((numberp ident) (number-to-string ident))
  15278. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15279. (org-with-wide-buffer (org-find-property "ID" id))))
  15280. ;;;; Timestamps
  15281. (defvar org-last-changed-timestamp nil)
  15282. (defvar org-last-inserted-timestamp nil
  15283. "The last time stamp inserted with `org-insert-time-stamp'.")
  15284. (defvar org-ts-what) ; dynamically scoped parameter
  15285. (defun org-time-stamp (arg &optional inactive)
  15286. "Prompt for a date/time and insert a time stamp.
  15287. If the user specifies a time like HH:MM or if this command is
  15288. called with at least one prefix argument, the time stamp contains
  15289. the date and the time. Otherwise, only the date is included.
  15290. All parts of a date not specified by the user are filled in from
  15291. the timestamp at point, if any, or the current date/time
  15292. otherwise.
  15293. If there is already a timestamp at the cursor, it is replaced.
  15294. With two universal prefix arguments, insert an active timestamp
  15295. with the current time without prompting the user.
  15296. When called from lisp, the timestamp is inactive if INACTIVE is
  15297. non-nil."
  15298. (interactive "P")
  15299. (let* ((ts (cond
  15300. ((org-at-date-range-p t)
  15301. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15302. ((org-at-timestamp-p t) (match-string 0))))
  15303. ;; Default time is either the timestamp at point or today.
  15304. ;; When entering a range, only the range start is considered.
  15305. (default-time (if (not ts) (current-time)
  15306. (apply #'encode-time (org-parse-time-string ts))))
  15307. (default-input (and ts (org-get-compact-tod ts)))
  15308. (repeater (and ts
  15309. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15310. (match-string 0 ts)))
  15311. org-time-was-given
  15312. org-end-time-was-given
  15313. (time
  15314. (and (if (equal arg '(16)) (current-time)
  15315. ;; Preserve `this-command' and `last-command'.
  15316. (let ((this-command this-command)
  15317. (last-command last-command))
  15318. (org-read-date
  15319. arg 'totime nil nil default-time default-input
  15320. inactive))))))
  15321. (cond
  15322. ((and ts
  15323. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15324. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15325. (insert "--")
  15326. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15327. (ts
  15328. ;; Make sure we're on a timestamp. When in the middle of a date
  15329. ;; range, move arbitrarily to range end.
  15330. (unless (org-at-timestamp-p t)
  15331. (skip-chars-forward "-")
  15332. (org-at-timestamp-p t))
  15333. (replace-match "")
  15334. (setq org-last-changed-timestamp
  15335. (org-insert-time-stamp
  15336. time (or org-time-was-given arg)
  15337. inactive nil nil (list org-end-time-was-given)))
  15338. (when repeater
  15339. (backward-char)
  15340. (insert " " repeater)
  15341. (setq org-last-changed-timestamp
  15342. (concat (substring org-last-inserted-timestamp 0 -1)
  15343. " " repeater ">")))
  15344. (message "Timestamp updated"))
  15345. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15346. (t (org-insert-time-stamp
  15347. time (or org-time-was-given arg) inactive nil nil
  15348. (list org-end-time-was-given))))))
  15349. ;; FIXME: can we use this for something else, like computing time differences?
  15350. (defun org-get-compact-tod (s)
  15351. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15352. (let* ((t1 (match-string 1 s))
  15353. (h1 (string-to-number (match-string 2 s)))
  15354. (m1 (string-to-number (match-string 3 s)))
  15355. (t2 (and (match-end 4) (match-string 5 s)))
  15356. (h2 (and t2 (string-to-number (match-string 6 s))))
  15357. (m2 (and t2 (string-to-number (match-string 7 s))))
  15358. dh dm)
  15359. (if (not t2)
  15360. t1
  15361. (setq dh (- h2 h1) dm (- m2 m1))
  15362. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15363. (concat t1 "+" (number-to-string dh)
  15364. (and (/= 0 dm) (format ":%02d" dm)))))))
  15365. (defun org-time-stamp-inactive (&optional arg)
  15366. "Insert an inactive time stamp.
  15367. An inactive time stamp is enclosed in square brackets instead of angle
  15368. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15369. does not link to the calendar and cannot be changed with the S-cursor keys.
  15370. So these are more for recording a certain time/date."
  15371. (interactive "P")
  15372. (org-time-stamp arg 'inactive))
  15373. (defvar org-date-ovl (make-overlay 1 1))
  15374. (overlay-put org-date-ovl 'face 'org-date-selected)
  15375. (delete-overlay org-date-ovl)
  15376. (defvar org-ans1) ; dynamically scoped parameter
  15377. (defvar org-ans2) ; dynamically scoped parameter
  15378. (defvar org-plain-time-of-day-regexp) ; defined below
  15379. (defvar org-overriding-default-time nil) ; dynamically scoped
  15380. (defvar org-read-date-overlay nil)
  15381. (defvar org-dcst nil) ; dynamically scoped
  15382. (defvar org-read-date-history nil)
  15383. (defvar org-read-date-final-answer nil)
  15384. (defvar org-read-date-analyze-futurep nil)
  15385. (defvar org-read-date-analyze-forced-year nil)
  15386. (defvar org-read-date-inactive)
  15387. (defvar org-read-date-minibuffer-local-map
  15388. (let* ((map (make-sparse-keymap)))
  15389. (set-keymap-parent map minibuffer-local-map)
  15390. (org-defkey map (kbd ".")
  15391. (lambda () (interactive)
  15392. ;; Are we at the beginning of the prompt?
  15393. (if (looking-back "^[^:]+: "
  15394. (let ((inhibit-field-text-motion t))
  15395. (line-beginning-position)))
  15396. (org-eval-in-calendar '(calendar-goto-today))
  15397. (insert "."))))
  15398. (org-defkey map (kbd "C-.")
  15399. (lambda () (interactive)
  15400. (org-eval-in-calendar '(calendar-goto-today))))
  15401. (org-defkey map [(meta shift left)]
  15402. (lambda () (interactive)
  15403. (org-eval-in-calendar '(calendar-backward-month 1))))
  15404. (org-defkey map [(meta shift right)]
  15405. (lambda () (interactive)
  15406. (org-eval-in-calendar '(calendar-forward-month 1))))
  15407. (org-defkey map [(meta shift up)]
  15408. (lambda () (interactive)
  15409. (org-eval-in-calendar '(calendar-backward-year 1))))
  15410. (org-defkey map [(meta shift down)]
  15411. (lambda () (interactive)
  15412. (org-eval-in-calendar '(calendar-forward-year 1))))
  15413. (org-defkey map [?\e (shift left)]
  15414. (lambda () (interactive)
  15415. (org-eval-in-calendar '(calendar-backward-month 1))))
  15416. (org-defkey map [?\e (shift right)]
  15417. (lambda () (interactive)
  15418. (org-eval-in-calendar '(calendar-forward-month 1))))
  15419. (org-defkey map [?\e (shift up)]
  15420. (lambda () (interactive)
  15421. (org-eval-in-calendar '(calendar-backward-year 1))))
  15422. (org-defkey map [?\e (shift down)]
  15423. (lambda () (interactive)
  15424. (org-eval-in-calendar '(calendar-forward-year 1))))
  15425. (org-defkey map [(shift up)]
  15426. (lambda () (interactive)
  15427. (org-eval-in-calendar '(calendar-backward-week 1))))
  15428. (org-defkey map [(shift down)]
  15429. (lambda () (interactive)
  15430. (org-eval-in-calendar '(calendar-forward-week 1))))
  15431. (org-defkey map [(shift left)]
  15432. (lambda () (interactive)
  15433. (org-eval-in-calendar '(calendar-backward-day 1))))
  15434. (org-defkey map [(shift right)]
  15435. (lambda () (interactive)
  15436. (org-eval-in-calendar '(calendar-forward-day 1))))
  15437. (org-defkey map "!"
  15438. (lambda () (interactive)
  15439. (org-eval-in-calendar '(diary-view-entries))
  15440. (message "")))
  15441. (org-defkey map ">"
  15442. (lambda () (interactive)
  15443. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15444. (org-defkey map "<"
  15445. (lambda () (interactive)
  15446. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15447. (org-defkey map "\C-v"
  15448. (lambda () (interactive)
  15449. (org-eval-in-calendar
  15450. '(calendar-scroll-left-three-months 1))))
  15451. (org-defkey map "\M-v"
  15452. (lambda () (interactive)
  15453. (org-eval-in-calendar
  15454. '(calendar-scroll-right-three-months 1))))
  15455. map)
  15456. "Keymap for minibuffer commands when using `org-read-date'.")
  15457. (defvar org-def)
  15458. (defvar org-defdecode)
  15459. (defvar org-with-time)
  15460. (defvar calendar-setup) ; Dynamically scoped.
  15461. (defun org-read-date (&optional with-time to-time from-string prompt
  15462. default-time default-input inactive)
  15463. "Read a date, possibly a time, and make things smooth for the user.
  15464. The prompt will suggest to enter an ISO date, but you can also enter anything
  15465. which will at least partially be understood by `parse-time-string'.
  15466. Unrecognized parts of the date will default to the current day, month, year,
  15467. hour and minute. If this command is called to replace a timestamp at point,
  15468. or to enter the second timestamp of a range, the default time is taken
  15469. from the existing stamp. Furthermore, the command prefers the future,
  15470. so if you are giving a date where the year is not given, and the day-month
  15471. combination is already past in the current year, it will assume you
  15472. mean next year. For details, see the manual. A few examples:
  15473. 3-2-5 --> 2003-02-05
  15474. feb 15 --> currentyear-02-15
  15475. 2/15 --> currentyear-02-15
  15476. sep 12 9 --> 2009-09-12
  15477. 12:45 --> today 12:45
  15478. 22 sept 0:34 --> currentyear-09-22 0:34
  15479. 12 --> currentyear-currentmonth-12
  15480. Fri --> nearest Friday after today
  15481. -Tue --> last Tuesday
  15482. etc.
  15483. Furthermore you can specify a relative date by giving, as the *first* thing
  15484. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15485. change in days weeks, months, years.
  15486. With a single plus or minus, the date is relative to today. With a double
  15487. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15488. +4d --> four days from today
  15489. +4 --> same as above
  15490. +2w --> two weeks from today
  15491. ++5 --> five days from default date
  15492. The function understands only English month and weekday abbreviations.
  15493. While prompting, a calendar is popped up - you can also select the
  15494. date with the mouse (button 1). The calendar shows a period of three
  15495. months. To scroll it to other months, use the keys `>' and `<'.
  15496. If you don't like the calendar, turn it off with
  15497. (setq org-read-date-popup-calendar nil)
  15498. With optional argument TO-TIME, the date will immediately be converted
  15499. to an internal time.
  15500. With an optional argument WITH-TIME, the prompt will suggest to
  15501. also insert a time. Note that when WITH-TIME is not set, you can
  15502. still enter a time, and this function will inform the calling routine
  15503. about this change. The calling routine may then choose to change the
  15504. format used to insert the time stamp into the buffer to include the time.
  15505. With optional argument FROM-STRING, read from this string instead from
  15506. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15507. the time/date that is used for everything that is not specified by the
  15508. user."
  15509. (require 'parse-time)
  15510. (let* ((org-with-time with-time)
  15511. (org-time-stamp-rounding-minutes
  15512. (if (equal org-with-time '(16))
  15513. '(0 0)
  15514. org-time-stamp-rounding-minutes))
  15515. (org-dcst org-display-custom-times)
  15516. (ct (org-current-time))
  15517. (org-def (or org-overriding-default-time default-time ct))
  15518. (org-defdecode (decode-time org-def))
  15519. (cur-frame (selected-frame))
  15520. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15521. (calendar-setup
  15522. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15523. (calendar-move-hook nil)
  15524. (calendar-view-diary-initially-flag nil)
  15525. (calendar-view-holidays-initially-flag nil)
  15526. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15527. ;; Rationalize `org-def' and `org-defdecode', if required.
  15528. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15529. (setf (nth 2 org-defdecode) -1)
  15530. (setf (nth 1 org-defdecode) 59)
  15531. (setq org-def (apply #'encode-time org-defdecode))
  15532. (setq org-defdecode (decode-time org-def)))
  15533. (let* ((timestr (format-time-string
  15534. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15535. org-def))
  15536. (prompt (concat (if prompt (concat prompt " ") "")
  15537. (format "Date+time [%s]: " timestr))))
  15538. (cond
  15539. (from-string (setq ans from-string))
  15540. (org-read-date-popup-calendar
  15541. (save-excursion
  15542. (save-window-excursion
  15543. (calendar)
  15544. (when (eq calendar-setup 'calendar-only)
  15545. (setq cal-frame
  15546. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15547. (select-frame cal-frame))
  15548. (org-eval-in-calendar '(setq cursor-type nil) t)
  15549. (unwind-protect
  15550. (progn
  15551. (calendar-forward-day (- (time-to-days org-def)
  15552. (calendar-absolute-from-gregorian
  15553. (calendar-current-date))))
  15554. (org-eval-in-calendar nil t)
  15555. (let* ((old-map (current-local-map))
  15556. (map (copy-keymap calendar-mode-map))
  15557. (minibuffer-local-map
  15558. (copy-keymap org-read-date-minibuffer-local-map)))
  15559. (org-defkey map (kbd "RET") 'org-calendar-select)
  15560. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15561. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15562. (unwind-protect
  15563. (progn
  15564. (use-local-map map)
  15565. (setq org-read-date-inactive inactive)
  15566. (add-hook 'post-command-hook 'org-read-date-display)
  15567. (setq org-ans0
  15568. (read-string prompt
  15569. default-input
  15570. 'org-read-date-history
  15571. nil))
  15572. ;; org-ans0: from prompt
  15573. ;; org-ans1: from mouse click
  15574. ;; org-ans2: from calendar motion
  15575. (setq ans
  15576. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15577. (remove-hook 'post-command-hook 'org-read-date-display)
  15578. (use-local-map old-map)
  15579. (when org-read-date-overlay
  15580. (delete-overlay org-read-date-overlay)
  15581. (setq org-read-date-overlay nil)))))
  15582. (bury-buffer "*Calendar*")
  15583. (when cal-frame
  15584. (delete-frame cal-frame)
  15585. (select-frame-set-input-focus cur-frame))))))
  15586. (t ; Naked prompt only
  15587. (unwind-protect
  15588. (setq ans (read-string prompt default-input
  15589. 'org-read-date-history timestr))
  15590. (when org-read-date-overlay
  15591. (delete-overlay org-read-date-overlay)
  15592. (setq org-read-date-overlay nil))))))
  15593. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15594. (when org-read-date-analyze-forced-year
  15595. (message "Year was forced into %s"
  15596. (if org-read-date-force-compatible-dates
  15597. "compatible range (1970-2037)"
  15598. "range representable on this machine"))
  15599. (ding))
  15600. ;; One round trip to get rid of 34th of August and stuff like that....
  15601. (setq final (decode-time (apply 'encode-time final)))
  15602. (setq org-read-date-final-answer ans)
  15603. (if to-time
  15604. (apply 'encode-time final)
  15605. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15606. (format "%04d-%02d-%02d %02d:%02d"
  15607. (nth 5 final) (nth 4 final) (nth 3 final)
  15608. (nth 2 final) (nth 1 final))
  15609. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15610. (defun org-read-date-display ()
  15611. "Display the current date prompt interpretation in the minibuffer."
  15612. (when org-read-date-display-live
  15613. (when org-read-date-overlay
  15614. (delete-overlay org-read-date-overlay))
  15615. (when (minibufferp (current-buffer))
  15616. (save-excursion
  15617. (end-of-line 1)
  15618. (while (not (equal (buffer-substring
  15619. (max (point-min) (- (point) 4)) (point))
  15620. " "))
  15621. (insert " ")))
  15622. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15623. " " (or org-ans1 org-ans2)))
  15624. (org-end-time-was-given nil)
  15625. (f (org-read-date-analyze ans org-def org-defdecode))
  15626. (fmts (if org-dcst
  15627. org-time-stamp-custom-formats
  15628. org-time-stamp-formats))
  15629. (fmt (if (or org-with-time
  15630. (and (boundp 'org-time-was-given) org-time-was-given))
  15631. (cdr fmts)
  15632. (car fmts)))
  15633. (txt (format-time-string fmt (apply 'encode-time f)))
  15634. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15635. (txt (concat "=> " txt)))
  15636. (when (and org-end-time-was-given
  15637. (string-match org-plain-time-of-day-regexp txt))
  15638. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15639. org-end-time-was-given
  15640. (substring txt (match-end 0)))))
  15641. (when org-read-date-analyze-futurep
  15642. (setq txt (concat txt " (=>F)")))
  15643. (setq org-read-date-overlay
  15644. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15645. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15646. (defun org-read-date-analyze (ans def defdecode)
  15647. "Analyze the combined answer of the date prompt."
  15648. ;; FIXME: cleanup and comment
  15649. ;; Pass `current-time' result to `decode-time' (instead of calling
  15650. ;; without arguments) so that only `current-time' has to be
  15651. ;; overriden in tests.
  15652. (let ((org-def def)
  15653. (org-defdecode defdecode)
  15654. (nowdecode (decode-time (current-time)))
  15655. delta deltan deltaw deltadef year month day
  15656. hour minute second wday pm h2 m2 tl wday1
  15657. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15658. (setq org-read-date-analyze-futurep nil
  15659. org-read-date-analyze-forced-year nil)
  15660. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15661. (setq ans "+0"))
  15662. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15663. (setq ans (replace-match "" t t ans)
  15664. deltan (car delta)
  15665. deltaw (nth 1 delta)
  15666. deltadef (nth 2 delta)))
  15667. ;; Check if there is an iso week date in there. If yes, store the
  15668. ;; info and postpone interpreting it until the rest of the parsing
  15669. ;; is done.
  15670. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15671. (setq iso-year (when (match-end 1)
  15672. (org-small-year-to-year
  15673. (string-to-number (match-string 1 ans))))
  15674. iso-weekday (when (match-end 3)
  15675. (string-to-number (match-string 3 ans)))
  15676. iso-week (string-to-number (match-string 2 ans)))
  15677. (setq ans (replace-match "" t t ans)))
  15678. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15679. (when (string-match
  15680. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15681. (setq year (if (match-end 2)
  15682. (string-to-number (match-string 2 ans))
  15683. (progn (setq kill-year t)
  15684. (string-to-number (format-time-string "%Y"))))
  15685. month (string-to-number (match-string 3 ans))
  15686. day (string-to-number (match-string 4 ans)))
  15687. (setq year (org-small-year-to-year year))
  15688. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15689. t nil ans)))
  15690. ;; Help matching dotted european dates
  15691. (when (string-match
  15692. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15693. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15694. (setq kill-year t)
  15695. (string-to-number (format-time-string "%Y")))
  15696. day (string-to-number (match-string 1 ans))
  15697. month (string-to-number (match-string 2 ans))
  15698. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15699. t nil ans)))
  15700. ;; Help matching american dates, like 5/30 or 5/30/7
  15701. (when (string-match
  15702. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15703. (setq year (if (match-end 4)
  15704. (string-to-number (match-string 4 ans))
  15705. (progn (setq kill-year t)
  15706. (string-to-number (format-time-string "%Y"))))
  15707. month (string-to-number (match-string 1 ans))
  15708. day (string-to-number (match-string 2 ans)))
  15709. (setq year (org-small-year-to-year year))
  15710. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15711. t nil ans)))
  15712. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15713. ;; If there is a time with am/pm, and *no* time without it, we convert
  15714. ;; so that matching will be successful.
  15715. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15716. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15717. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15718. (setq hour (string-to-number (match-string 1 ans))
  15719. minute (if (match-end 3)
  15720. (string-to-number (match-string 3 ans))
  15721. 0)
  15722. pm (equal ?p
  15723. (string-to-char (downcase (match-string 4 ans)))))
  15724. (if (and (= hour 12) (not pm))
  15725. (setq hour 0)
  15726. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15727. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15728. t t ans))))
  15729. ;; Check if a time range is given as a duration
  15730. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15731. (setq hour (string-to-number (match-string 1 ans))
  15732. h2 (+ hour (string-to-number (match-string 3 ans)))
  15733. minute (string-to-number (match-string 2 ans))
  15734. m2 (+ minute (if (match-end 5) (string-to-number
  15735. (match-string 5 ans))0)))
  15736. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15737. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15738. t t ans)))
  15739. ;; Check if there is a time range
  15740. (when (boundp 'org-end-time-was-given)
  15741. (setq org-time-was-given nil)
  15742. (when (and (string-match org-plain-time-of-day-regexp ans)
  15743. (match-end 8))
  15744. (setq org-end-time-was-given (match-string 8 ans))
  15745. (setq ans (concat (substring ans 0 (match-beginning 7))
  15746. (substring ans (match-end 7))))))
  15747. (setq tl (parse-time-string ans)
  15748. day (or (nth 3 tl) (nth 3 org-defdecode))
  15749. month
  15750. (cond ((nth 4 tl))
  15751. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15752. ;; Day was specified. Make sure DAY+MONTH
  15753. ;; combination happens in the future.
  15754. ((nth 3 tl)
  15755. (setq futurep t)
  15756. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15757. (nth 4 nowdecode)))
  15758. (t (nth 4 org-defdecode)))
  15759. year
  15760. (cond ((and (not kill-year) (nth 5 tl)))
  15761. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15762. ;; Month was guessed in the future and is at least
  15763. ;; equal to NOWDECODE's. Fix year accordingly.
  15764. (futurep
  15765. (if (or (> month (nth 4 nowdecode))
  15766. (>= day (nth 3 nowdecode)))
  15767. (nth 5 nowdecode)
  15768. (1+ (nth 5 nowdecode))))
  15769. ;; Month was specified. Make sure MONTH+YEAR
  15770. ;; combination happens in the future.
  15771. ((nth 4 tl)
  15772. (setq futurep t)
  15773. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15774. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15775. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15776. (t (nth 5 nowdecode))))
  15777. (t (nth 5 org-defdecode)))
  15778. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15779. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15780. second (or (nth 0 tl) 0)
  15781. wday (nth 6 tl))
  15782. (when (and (eq org-read-date-prefer-future 'time)
  15783. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15784. (equal day (nth 3 nowdecode))
  15785. (equal month (nth 4 nowdecode))
  15786. (equal year (nth 5 nowdecode))
  15787. (nth 2 tl)
  15788. (or (< (nth 2 tl) (nth 2 nowdecode))
  15789. (and (= (nth 2 tl) (nth 2 nowdecode))
  15790. (nth 1 tl)
  15791. (< (nth 1 tl) (nth 1 nowdecode)))))
  15792. (setq day (1+ day)
  15793. futurep t))
  15794. ;; Special date definitions below
  15795. (cond
  15796. (iso-week
  15797. ;; There was an iso week
  15798. (require 'cal-iso)
  15799. (setq futurep nil)
  15800. (setq year (or iso-year year)
  15801. day (or iso-weekday wday 1)
  15802. wday nil ; to make sure that the trigger below does not match
  15803. iso-date (calendar-gregorian-from-absolute
  15804. (calendar-iso-to-absolute
  15805. (list iso-week day year))))
  15806. ; FIXME: Should we also push ISO weeks into the future?
  15807. ; (when (and org-read-date-prefer-future
  15808. ; (not iso-year)
  15809. ; (< (calendar-absolute-from-gregorian iso-date)
  15810. ; (time-to-days (current-time))))
  15811. ; (setq year (1+ year)
  15812. ; iso-date (calendar-gregorian-from-absolute
  15813. ; (calendar-iso-to-absolute
  15814. ; (list iso-week day year)))))
  15815. (setq month (car iso-date)
  15816. year (nth 2 iso-date)
  15817. day (nth 1 iso-date)))
  15818. (deltan
  15819. (setq futurep nil)
  15820. (unless deltadef
  15821. ;; Pass `current-time' result to `decode-time' (instead of
  15822. ;; calling without arguments) so that only `current-time' has
  15823. ;; to be overriden in tests.
  15824. (let ((now (decode-time (current-time))))
  15825. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15826. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15827. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15828. ((equal deltaw "m") (setq month (+ month deltan)))
  15829. ((equal deltaw "y") (setq year (+ year deltan)))))
  15830. ((and wday (not (nth 3 tl)))
  15831. ;; Weekday was given, but no day, so pick that day in the week
  15832. ;; on or after the derived date.
  15833. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15834. (unless (equal wday wday1)
  15835. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15836. (when (and (boundp 'org-time-was-given)
  15837. (nth 2 tl))
  15838. (setq org-time-was-given t))
  15839. (when (< year 100) (setq year (+ 2000 year)))
  15840. ;; Check of the date is representable
  15841. (if org-read-date-force-compatible-dates
  15842. (progn
  15843. (when (< year 1970)
  15844. (setq year 1970 org-read-date-analyze-forced-year t))
  15845. (when (> year 2037)
  15846. (setq year 2037 org-read-date-analyze-forced-year t)))
  15847. (condition-case nil
  15848. (ignore (encode-time second minute hour day month year))
  15849. (error
  15850. (setq year (nth 5 org-defdecode))
  15851. (setq org-read-date-analyze-forced-year t))))
  15852. (setq org-read-date-analyze-futurep futurep)
  15853. (list second minute hour day month year)))
  15854. (defvar parse-time-weekdays)
  15855. (defun org-read-date-get-relative (s today default)
  15856. "Check string S for special relative date string.
  15857. TODAY and DEFAULT are internal times, for today and for a default.
  15858. Return shift list (N what def-flag)
  15859. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15860. N is the number of WHATs to shift.
  15861. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15862. the DEFAULT date rather than TODAY."
  15863. (require 'parse-time)
  15864. (when (and
  15865. (string-match
  15866. (concat
  15867. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15868. "\\([0-9]+\\)?"
  15869. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15870. "\\([ \t]\\|$\\)") s)
  15871. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15872. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15873. (string-to-char (substring (match-string 1 s) -1))
  15874. ?+))
  15875. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15876. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15877. (what (if (match-end 3) (match-string 3 s) "d"))
  15878. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15879. (date (if rel default today))
  15880. (wday (nth 6 (decode-time date)))
  15881. delta)
  15882. (if wday1
  15883. (progn
  15884. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15885. (when (= delta 0) (setq delta 7))
  15886. (when (= dir ?-)
  15887. (setq delta (- delta 7))
  15888. (when (= delta 0) (setq delta -7)))
  15889. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15890. (list delta "d" rel))
  15891. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15892. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15893. "Turn a user-specified date into the internal representation.
  15894. The internal representation needed by the calendar is (month day year).
  15895. This is a wrapper to handle the brain-dead convention in calendar that
  15896. user function argument order change dependent on argument order."
  15897. (pcase calendar-date-style
  15898. (`american (list arg1 arg2 arg3))
  15899. (`european (list arg2 arg1 arg3))
  15900. (`iso (list arg2 arg3 arg1))))
  15901. (defun org-eval-in-calendar (form &optional keepdate)
  15902. "Eval FORM in the calendar window and return to current window.
  15903. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15904. (let ((sf (selected-frame))
  15905. (sw (selected-window)))
  15906. (select-window (get-buffer-window "*Calendar*" t))
  15907. (eval form)
  15908. (when (and (not keepdate) (calendar-cursor-to-date))
  15909. (let* ((date (calendar-cursor-to-date))
  15910. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15911. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15912. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15913. (select-window sw)
  15914. (select-frame-set-input-focus sf)))
  15915. (defun org-calendar-select ()
  15916. "Return to `org-read-date' with the date currently selected.
  15917. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15918. (interactive)
  15919. (when (calendar-cursor-to-date)
  15920. (let* ((date (calendar-cursor-to-date))
  15921. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15922. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15923. (when (active-minibuffer-window) (exit-minibuffer))))
  15924. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15925. "Insert a date stamp for the date given by the internal TIME.
  15926. See `format-time-string' for the format of TIME.
  15927. WITH-HM means use the stamp format that includes the time of the day.
  15928. INACTIVE means use square brackets instead of angular ones, so that the
  15929. stamp will not contribute to the agenda.
  15930. PRE and POST are optional strings to be inserted before and after the
  15931. stamp.
  15932. The command returns the inserted time stamp."
  15933. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15934. stamp)
  15935. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15936. (insert-before-markers (or pre ""))
  15937. (when (listp extra)
  15938. (setq extra (car extra))
  15939. (if (and (stringp extra)
  15940. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15941. (setq extra (format "-%02d:%02d"
  15942. (string-to-number (match-string 1 extra))
  15943. (string-to-number (match-string 2 extra))))
  15944. (setq extra nil)))
  15945. (when extra
  15946. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15947. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15948. (insert-before-markers (or post ""))
  15949. (setq org-last-inserted-timestamp stamp)))
  15950. (defun org-toggle-time-stamp-overlays ()
  15951. "Toggle the use of custom time stamp formats."
  15952. (interactive)
  15953. (setq org-display-custom-times (not org-display-custom-times))
  15954. (unless org-display-custom-times
  15955. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15956. (while (setq p (next-single-property-change p 'display))
  15957. (when (and (get-text-property p 'display)
  15958. (eq (get-text-property p 'face) 'org-date))
  15959. (remove-text-properties
  15960. p (setq p (next-single-property-change p 'display))
  15961. '(display t))))
  15962. (set-buffer-modified-p bmp)))
  15963. (org-restart-font-lock)
  15964. (setq org-table-may-need-update t)
  15965. (if org-display-custom-times
  15966. (message "Time stamps are overlaid with custom format")
  15967. (message "Time stamp overlays removed")))
  15968. (defun org-display-custom-time (beg end)
  15969. "Overlay modified time stamp format over timestamp between BEG and END."
  15970. (let* ((ts (buffer-substring beg end))
  15971. t1 w1 with-hm tf time str w2 (off 0))
  15972. (save-match-data
  15973. (setq t1 (org-parse-time-string ts t))
  15974. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15975. (setq off (- (match-end 0) (match-beginning 0)))))
  15976. (setq end (- end off))
  15977. (setq w1 (- end beg)
  15978. with-hm (and (nth 1 t1) (nth 2 t1))
  15979. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15980. time (org-fix-decoded-time t1)
  15981. str (org-add-props
  15982. (format-time-string
  15983. (substring tf 1 -1) (apply 'encode-time time))
  15984. nil 'mouse-face 'highlight)
  15985. w2 (length str))
  15986. (unless (= w2 w1)
  15987. (add-text-properties (1+ beg) (+ 2 beg)
  15988. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15989. (put-text-property beg end 'display str)))
  15990. (defun org-fix-decoded-time (time)
  15991. "Set 0 instead of nil for the first 6 elements of time.
  15992. Don't touch the rest."
  15993. (let ((n 0))
  15994. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15995. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15996. "Difference between TIMESTAMP-STRING and now in days.
  15997. If SECONDS is non-nil, return the difference in seconds."
  15998. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15999. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  16000. (funcall fdiff (current-time)))))
  16001. (defun org-deadline-close-p (timestamp-string &optional ndays)
  16002. "Is the time in TIMESTAMP-STRING close to the current date?"
  16003. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  16004. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  16005. (not (org-entry-is-done-p))))
  16006. (defun org-get-wdays (ts &optional delay zero-delay)
  16007. "Get the deadline lead time appropriate for timestring TS.
  16008. When DELAY is non-nil, get the delay time for scheduled items
  16009. instead of the deadline lead time. When ZERO-DELAY is non-nil
  16010. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  16011. don't try to find the delay cookie in the scheduled timestamp."
  16012. (let ((tv (if delay org-scheduled-delay-days
  16013. org-deadline-warning-days)))
  16014. (cond
  16015. ((or (and delay (< tv 0))
  16016. (and delay zero-delay (<= tv 0))
  16017. (and (not delay) (<= tv 0)))
  16018. ;; Enforce this value no matter what
  16019. (- tv))
  16020. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  16021. ;; lead time is specified.
  16022. (floor (* (string-to-number (match-string 1 ts))
  16023. (cdr (assoc (match-string 2 ts)
  16024. '(("d" . 1) ("w" . 7)
  16025. ("m" . 30.4) ("y" . 365.25)
  16026. ("h" . 0.041667)))))))
  16027. ;; go for the default.
  16028. (t tv))))
  16029. (defun org-calendar-select-mouse (ev)
  16030. "Return to `org-read-date' with the date currently selected.
  16031. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  16032. (interactive "e")
  16033. (mouse-set-point ev)
  16034. (when (calendar-cursor-to-date)
  16035. (let* ((date (calendar-cursor-to-date))
  16036. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  16037. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  16038. (when (active-minibuffer-window) (exit-minibuffer))))
  16039. (defun org-check-deadlines (ndays)
  16040. "Check if there are any deadlines due or past due.
  16041. A deadline is considered due if it happens within `org-deadline-warning-days'
  16042. days from today's date. If the deadline appears in an entry marked DONE,
  16043. it is not shown. A numeric prefix argument NDAYS can be used to test that
  16044. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  16045. are shown."
  16046. (interactive "P")
  16047. (let* ((org-warn-days
  16048. (cond
  16049. ((equal ndays '(4)) 100000)
  16050. (ndays (prefix-numeric-value ndays))
  16051. (t (abs org-deadline-warning-days))))
  16052. (case-fold-search nil)
  16053. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16054. (callback
  16055. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16056. (message "%d deadlines past-due or due within %d days"
  16057. (org-occur regexp nil callback)
  16058. org-warn-days)))
  16059. (defsubst org-re-timestamp (type)
  16060. "Return a regexp for timestamp TYPE.
  16061. Allowed values for TYPE are:
  16062. all: all timestamps
  16063. active: only active timestamps (<...>)
  16064. inactive: only inactive timestamps ([...])
  16065. scheduled: only scheduled timestamps
  16066. deadline: only deadline timestamps
  16067. closed: only closed time-stamps
  16068. When TYPE is nil, fall back on returning a regexp that matches
  16069. both scheduled and deadline timestamps."
  16070. (cl-case type
  16071. (all org-ts-regexp-both)
  16072. (active org-ts-regexp)
  16073. (inactive org-ts-regexp-inactive)
  16074. (scheduled org-scheduled-time-regexp)
  16075. (deadline org-deadline-time-regexp)
  16076. (closed org-closed-time-regexp)
  16077. (otherwise
  16078. (concat "\\<"
  16079. (regexp-opt (list org-deadline-string org-scheduled-string))
  16080. " *<\\([^>]+\\)>"))))
  16081. (defun org-check-before-date (d)
  16082. "Check if there are deadlines or scheduled entries before date D."
  16083. (interactive (list (org-read-date)))
  16084. (let* ((case-fold-search nil)
  16085. (regexp (org-re-timestamp org-ts-type))
  16086. (ts-type org-ts-type)
  16087. (callback
  16088. (lambda ()
  16089. (let ((match (match-string 1)))
  16090. (and (if (memq ts-type '(active inactive all))
  16091. (eq (org-element-type (save-excursion
  16092. (backward-char)
  16093. (org-element-context)))
  16094. 'timestamp)
  16095. (org-at-planning-p))
  16096. (time-less-p
  16097. (org-time-string-to-time match)
  16098. (org-time-string-to-time d)))))))
  16099. (message "%d entries before %s"
  16100. (org-occur regexp nil callback)
  16101. d)))
  16102. (defun org-check-after-date (d)
  16103. "Check if there are deadlines or scheduled entries after date D."
  16104. (interactive (list (org-read-date)))
  16105. (let* ((case-fold-search nil)
  16106. (regexp (org-re-timestamp org-ts-type))
  16107. (ts-type org-ts-type)
  16108. (callback
  16109. (lambda ()
  16110. (let ((match (match-string 1)))
  16111. (and (if (memq ts-type '(active inactive all))
  16112. (eq (org-element-type (save-excursion
  16113. (backward-char)
  16114. (org-element-context)))
  16115. 'timestamp)
  16116. (org-at-planning-p))
  16117. (not (time-less-p
  16118. (org-time-string-to-time match)
  16119. (org-time-string-to-time d))))))))
  16120. (message "%d entries after %s"
  16121. (org-occur regexp nil callback)
  16122. d)))
  16123. (defun org-check-dates-range (start-date end-date)
  16124. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16125. (interactive (list (org-read-date nil nil nil "Range starts")
  16126. (org-read-date nil nil nil "Range end")))
  16127. (let ((case-fold-search nil)
  16128. (regexp (org-re-timestamp org-ts-type))
  16129. (callback
  16130. (let ((type org-ts-type))
  16131. (lambda ()
  16132. (let ((match (match-string 1)))
  16133. (and
  16134. (if (memq type '(active inactive all))
  16135. (eq (org-element-type (save-excursion
  16136. (backward-char)
  16137. (org-element-context)))
  16138. 'timestamp)
  16139. (org-at-planning-p))
  16140. (not (time-less-p
  16141. (org-time-string-to-time match)
  16142. (org-time-string-to-time start-date)))
  16143. (time-less-p
  16144. (org-time-string-to-time match)
  16145. (org-time-string-to-time end-date))))))))
  16146. (message "%d entries between %s and %s"
  16147. (org-occur regexp nil callback) start-date end-date)))
  16148. (defun org-evaluate-time-range (&optional to-buffer)
  16149. "Evaluate a time range by computing the difference between start and end.
  16150. Normally the result is just printed in the echo area, but with prefix arg
  16151. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16152. If the time range is actually in a table, the result is inserted into the
  16153. next column.
  16154. For time difference computation, a year is assumed to be exactly 365
  16155. days in order to avoid rounding problems."
  16156. (interactive "P")
  16157. (or
  16158. (org-clock-update-time-maybe)
  16159. (save-excursion
  16160. (unless (org-at-date-range-p t)
  16161. (goto-char (point-at-bol))
  16162. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16163. (unless (org-at-date-range-p t)
  16164. (user-error "Not at a time-stamp range, and none found in current line")))
  16165. (let* ((ts1 (match-string 1))
  16166. (ts2 (match-string 2))
  16167. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16168. (match-end (match-end 0))
  16169. (time1 (org-time-string-to-time ts1))
  16170. (time2 (org-time-string-to-time ts2))
  16171. (t1 (float-time time1))
  16172. (t2 (float-time time2))
  16173. (diff (abs (- t2 t1)))
  16174. (negative (< (- t2 t1) 0))
  16175. ;; (ys (floor (* 365 24 60 60)))
  16176. (ds (* 24 60 60))
  16177. (hs (* 60 60))
  16178. (fy "%dy %dd %02d:%02d")
  16179. (fy1 "%dy %dd")
  16180. (fd "%dd %02d:%02d")
  16181. (fd1 "%dd")
  16182. (fh "%02d:%02d")
  16183. y d h m align)
  16184. (if havetime
  16185. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16186. y 0
  16187. d (floor (/ diff ds)) diff (mod diff ds)
  16188. h (floor (/ diff hs)) diff (mod diff hs)
  16189. m (floor (/ diff 60)))
  16190. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16191. y 0
  16192. d (floor (+ (/ diff ds) 0.5))
  16193. h 0 m 0))
  16194. (if (not to-buffer)
  16195. (message "%s" (org-make-tdiff-string y d h m))
  16196. (if (org-at-table-p)
  16197. (progn
  16198. (goto-char match-end)
  16199. (setq align t)
  16200. (and (looking-at " *|") (goto-char (match-end 0))))
  16201. (goto-char match-end))
  16202. (when (looking-at
  16203. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16204. (replace-match ""))
  16205. (when negative (insert " -"))
  16206. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16207. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16208. (insert " " (format fh h m))))
  16209. (when align (org-table-align))
  16210. (message "Time difference inserted")))))
  16211. (defun org-make-tdiff-string (y d h m)
  16212. (let ((fmt "")
  16213. (l nil))
  16214. (when (> y 0)
  16215. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16216. (push y l))
  16217. (when (> d 0)
  16218. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16219. (push d l))
  16220. (when (> h 0)
  16221. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16222. (push h l))
  16223. (when (> m 0)
  16224. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16225. (push m l))
  16226. (apply 'format fmt (nreverse l))))
  16227. (defun org-time-string-to-time (s &optional buffer pos)
  16228. "Convert a timestamp string into internal time."
  16229. (condition-case errdata
  16230. (apply 'encode-time (org-parse-time-string s))
  16231. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16232. s (if (not (and buffer pos))
  16233. ""
  16234. (format-message " at %d in buffer `%s'" pos buffer))
  16235. (cdr errdata)))))
  16236. (defun org-time-string-to-seconds (s)
  16237. "Convert a timestamp string to a number of seconds."
  16238. (float-time (org-time-string-to-time s)))
  16239. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16240. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16241. "Convert time stamp S to an absolute day number.
  16242. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16243. stamp, get the closest date to DAYNR. If PREFER is
  16244. `past' (respectively `future') return a date past (respectively
  16245. after) or equal to DAYNR.
  16246. POS is the location of time stamp S, as a buffer position in
  16247. BUFFER.
  16248. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16249. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16250. signalled."
  16251. (cond
  16252. ((string-match "\\`%%\\((.*)\\)" s)
  16253. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16254. ;; only able to match individual dates. If it fails, raise an
  16255. ;; error.
  16256. (if (and daynr
  16257. (org-diary-sexp-entry
  16258. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16259. daynr
  16260. (signal 'org-diary-sexp-no-match (list s))))
  16261. (daynr (org-closest-date s daynr prefer))
  16262. (t (time-to-days
  16263. (condition-case errdata
  16264. (apply #'encode-time (org-parse-time-string s))
  16265. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16266. s
  16267. (if (not (and buffer pos)) ""
  16268. (format-message " at %d in buffer `%s'" pos buffer))
  16269. (cdr errdata))))))))
  16270. (defun org-days-to-iso-week (days)
  16271. "Return the iso week number."
  16272. (require 'cal-iso)
  16273. (car (calendar-iso-from-absolute days)))
  16274. (defun org-small-year-to-year (year)
  16275. "Convert 2-digit years into 4-digit years.
  16276. YEAR is expanded into one of the 30 next years, if possible, or
  16277. into a past one. Any year larger than 99 is returned unchanged."
  16278. (if (>= year 100) year
  16279. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16280. (century (/ current 100))
  16281. (offset (- year (% current 100))))
  16282. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16283. ((> offset -70) (+ (* century 100) year))
  16284. (t (+ (* (1+ century) 100) year))))))
  16285. (defun org-time-from-absolute (d)
  16286. "Return the time corresponding to date D.
  16287. D may be an absolute day number, or a calendar-type list (month day year)."
  16288. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16289. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16290. (defvar org-agenda-current-date)
  16291. (defun org-calendar-holiday ()
  16292. "List of holidays, for Diary display in Org mode."
  16293. (require 'holidays)
  16294. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16295. (and hl (mapconcat #'identity hl "; "))))
  16296. (defun org-diary-sexp-entry (sexp entry d)
  16297. "Process a SEXP diary ENTRY for date D."
  16298. (require 'diary-lib)
  16299. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16300. ;; dynamically.
  16301. (let* ((sexp `(let ((entry ,entry)
  16302. (date ',d))
  16303. ,(car (read-from-string sexp))))
  16304. (result (if calendar-debug-sexp (eval sexp)
  16305. (condition-case nil
  16306. (eval sexp)
  16307. (error
  16308. (beep)
  16309. (message "Bad sexp at line %d in %s: %s"
  16310. (org-current-line)
  16311. (buffer-file-name) sexp)
  16312. (sleep-for 2))))))
  16313. (cond ((stringp result) (split-string result "; "))
  16314. ((and (consp result)
  16315. (not (consp (cdr result)))
  16316. (stringp (cdr result))) (cdr result))
  16317. ((and (consp result)
  16318. (stringp (car result))) result)
  16319. (result entry))))
  16320. (defun org-diary-to-ical-string (frombuf)
  16321. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16322. This uses the icalendar.el library."
  16323. (let* ((tmpdir temporary-file-directory)
  16324. (tmpfile (make-temp-name
  16325. (expand-file-name "orgics" tmpdir)))
  16326. buf rtn b e)
  16327. (with-current-buffer frombuf
  16328. (icalendar-export-region (point-min) (point-max) tmpfile)
  16329. (setq buf (find-buffer-visiting tmpfile))
  16330. (set-buffer buf)
  16331. (goto-char (point-min))
  16332. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16333. (setq b (match-beginning 0)))
  16334. (goto-char (point-max))
  16335. (when (re-search-backward "^END:VEVENT" nil t)
  16336. (setq e (match-end 0)))
  16337. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16338. (kill-buffer buf)
  16339. (delete-file tmpfile)
  16340. rtn))
  16341. (defun org-closest-date (start current prefer)
  16342. "Return closest date to CURRENT starting from START.
  16343. CURRENT and START are both time stamps.
  16344. When PREFER is `past', return a date that is either CURRENT or
  16345. past. When PREFER is `future', return a date that is either
  16346. CURRENT or future.
  16347. Only time stamps with a repeater are modified. Any other time
  16348. stamp stay unchanged. In any case, return value is an absolute
  16349. day number."
  16350. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16351. ;; No repeater. Do not shift time stamp.
  16352. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16353. (let ((value (string-to-number (match-string 1 start)))
  16354. (type (match-string 2 start)))
  16355. (if (= 0 value)
  16356. ;; Repeater with a 0-value is considered as void.
  16357. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16358. (let* ((base (org-date-to-gregorian start))
  16359. (target (org-date-to-gregorian current))
  16360. (sday (calendar-absolute-from-gregorian base))
  16361. (cday (calendar-absolute-from-gregorian target))
  16362. n1 n2)
  16363. ;; If START is already past CURRENT, just return START.
  16364. (if (<= cday sday) sday
  16365. ;; Compute closest date before (N1) and closest date past
  16366. ;; (N2) CURRENT.
  16367. (pcase type
  16368. ("h"
  16369. (let ((missing-hours
  16370. (mod (+ (- (* 24 (- cday sday))
  16371. (nth 2 (org-parse-time-string start)))
  16372. org-extend-today-until)
  16373. value)))
  16374. (setf n1 (if (= missing-hours 0) cday
  16375. (- cday (1+ (/ missing-hours 24)))))
  16376. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16377. ((or "d" "w")
  16378. (let ((value (if (equal type "w") (* 7 value) value)))
  16379. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16380. (setf n2 (+ n1 value))))
  16381. ("m"
  16382. (let* ((add-months
  16383. (lambda (d n)
  16384. ;; Add N months to gregorian date D, i.e.,
  16385. ;; a list (MONTH DAY YEAR). Return a valid
  16386. ;; gregorian date.
  16387. (let ((m (+ (nth 0 d) n)))
  16388. (list (mod m 12)
  16389. (nth 1 d)
  16390. (+ (/ m 12) (nth 2 d))))))
  16391. (months ; Complete months to TARGET.
  16392. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16393. (- (nth 0 target) (nth 0 base))
  16394. ;; If START's day is greater than
  16395. ;; TARGET's, remove incomplete month.
  16396. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16397. value)
  16398. value))
  16399. (before (funcall add-months base months)))
  16400. (setf n1 (calendar-absolute-from-gregorian before))
  16401. (setf n2
  16402. (calendar-absolute-from-gregorian
  16403. (funcall add-months before value)))))
  16404. (_
  16405. (let* ((d (nth 1 base))
  16406. (m (nth 0 base))
  16407. (y (nth 2 base))
  16408. (years ; Complete years to TARGET.
  16409. (* (/ (- (nth 2 target)
  16410. y
  16411. ;; If START's month and day are
  16412. ;; greater than TARGET's, remove
  16413. ;; incomplete year.
  16414. (if (or (> (nth 0 target) m)
  16415. (and (= (nth 0 target) m)
  16416. (> (nth 1 target) d)))
  16417. 0
  16418. 1))
  16419. value)
  16420. value))
  16421. (before (list m d (+ y years))))
  16422. (setf n1 (calendar-absolute-from-gregorian before))
  16423. (setf n2 (calendar-absolute-from-gregorian
  16424. (list m d (+ (nth 2 before) value)))))))
  16425. ;; Handle PREFER parameter, if any.
  16426. (cond
  16427. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16428. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16429. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16430. (defun org-date-to-gregorian (d)
  16431. "Turn any specification of date D into a Gregorian date for the calendar."
  16432. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16433. ((and (listp d) (= (length d) 3)) d)
  16434. ((stringp d)
  16435. (let ((d (org-parse-time-string d)))
  16436. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16437. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16438. (defun org-parse-time-string (s &optional nodefault)
  16439. "Parse the standard Org time string.
  16440. This should be a lot faster than the normal `parse-time-string'.
  16441. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16442. hour and minute fields will be nil if not given."
  16443. (cond ((string-match org-ts-regexp0 s)
  16444. (list 0
  16445. (when (or (match-beginning 8) (not nodefault))
  16446. (string-to-number (or (match-string 8 s) "0")))
  16447. (when (or (match-beginning 7) (not nodefault))
  16448. (string-to-number (or (match-string 7 s) "0")))
  16449. (string-to-number (match-string 4 s))
  16450. (string-to-number (match-string 3 s))
  16451. (string-to-number (match-string 2 s))
  16452. nil nil nil))
  16453. ((string-match "^<[^>]+>$" s)
  16454. (decode-time (seconds-to-time (org-matcher-time s))))
  16455. (t (error "Not a standard Org time string: %s" s))))
  16456. (defun org-timestamp-up (&optional arg)
  16457. "Increase the date item at the cursor by one.
  16458. If the cursor is on the year, change the year. If it is on the month,
  16459. the day or the time, change that.
  16460. With prefix ARG, change by that many units."
  16461. (interactive "p")
  16462. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16463. (defun org-timestamp-down (&optional arg)
  16464. "Decrease the date item at the cursor by one.
  16465. If the cursor is on the year, change the year. If it is on the month,
  16466. the day or the time, change that.
  16467. With prefix ARG, change by that many units."
  16468. (interactive "p")
  16469. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16470. (defun org-timestamp-up-day (&optional arg)
  16471. "Increase the date in the time stamp by one day.
  16472. With prefix ARG, change that many days."
  16473. (interactive "p")
  16474. (if (and (not (org-at-timestamp-p t))
  16475. (org-at-heading-p))
  16476. (org-todo 'up)
  16477. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16478. (defun org-timestamp-down-day (&optional arg)
  16479. "Decrease the date in the time stamp by one day.
  16480. With prefix ARG, change that many days."
  16481. (interactive "p")
  16482. (if (and (not (org-at-timestamp-p t))
  16483. (org-at-heading-p))
  16484. (org-todo 'down)
  16485. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16486. (defun org-at-timestamp-p (&optional inactive-ok)
  16487. "Non-nil if point is inside a timestamp.
  16488. When optional argument INACTIVE-OK is non-nil, also consider
  16489. inactive timestamps.
  16490. When this function returns a non-nil value, match data is set
  16491. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16492. INACTIVE-OK."
  16493. (interactive)
  16494. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16495. (pos (point))
  16496. (ans (or (looking-at tsr)
  16497. (save-excursion
  16498. (skip-chars-backward "^[<\n\r\t")
  16499. (when (> (point) (point-min)) (backward-char 1))
  16500. (and (looking-at tsr)
  16501. (> (- (match-end 0) pos) -1))))))
  16502. (and ans
  16503. (boundp 'org-ts-what)
  16504. (setq org-ts-what
  16505. (cond
  16506. ((= pos (match-beginning 0)) 'bracket)
  16507. ;; Point is considered to be "on the bracket" whether
  16508. ;; it's really on it or right after it.
  16509. ((= pos (1- (match-end 0))) 'bracket)
  16510. ((= pos (match-end 0)) 'after)
  16511. ((org-pos-in-match-range pos 2) 'year)
  16512. ((org-pos-in-match-range pos 3) 'month)
  16513. ((org-pos-in-match-range pos 7) 'hour)
  16514. ((org-pos-in-match-range pos 8) 'minute)
  16515. ((or (org-pos-in-match-range pos 4)
  16516. (org-pos-in-match-range pos 5)) 'day)
  16517. ((and (> pos (or (match-end 8) (match-end 5)))
  16518. (< pos (match-end 0)))
  16519. (- pos (or (match-end 8) (match-end 5))))
  16520. (t 'day))))
  16521. ans))
  16522. (defun org-toggle-timestamp-type ()
  16523. "Toggle the type (<active> or [inactive]) of a time stamp."
  16524. (interactive)
  16525. (when (org-at-timestamp-p t)
  16526. (let ((beg (match-beginning 0)) (end (match-end 0))
  16527. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16528. (save-excursion
  16529. (goto-char beg)
  16530. (while (re-search-forward "[][<>]" end t)
  16531. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16532. t t)))
  16533. (message "Timestamp is now %sactive"
  16534. (if (equal (char-after beg) ?<) "" "in")))))
  16535. (defun org-at-clock-log-p nil
  16536. "Is the cursor on the clock log line?"
  16537. (save-excursion
  16538. (move-beginning-of-line 1)
  16539. (looking-at org-clock-line-re)))
  16540. (defvar org-clock-history) ; defined in org-clock.el
  16541. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16542. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16543. "Change the date in the time stamp at point.
  16544. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16545. `year', `minute', `second'. If WHAT is not given, the cursor position
  16546. in the timestamp determines what will be changed.
  16547. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16548. (let ((origin (point)) origin-cat
  16549. with-hm inactive
  16550. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16551. org-ts-what
  16552. extra rem
  16553. ts time time0 fixnext clrgx)
  16554. (unless (org-at-timestamp-p t)
  16555. (user-error "Not at a timestamp"))
  16556. (if (and (not what) (eq org-ts-what 'bracket))
  16557. (org-toggle-timestamp-type)
  16558. ;; Point isn't on brackets. Remember the part of the time-stamp
  16559. ;; the point was in. Indeed, size of time-stamps may change,
  16560. ;; but point must be kept in the same category nonetheless.
  16561. (setq origin-cat org-ts-what)
  16562. (when (and (not what) (not (eq org-ts-what 'day))
  16563. org-display-custom-times
  16564. (get-text-property (point) 'display)
  16565. (not (get-text-property (1- (point)) 'display)))
  16566. (setq org-ts-what 'day))
  16567. (setq org-ts-what (or what org-ts-what)
  16568. inactive (= (char-after (match-beginning 0)) ?\[)
  16569. ts (match-string 0))
  16570. (replace-match "")
  16571. (when (string-match
  16572. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16573. ts)
  16574. (setq extra (match-string 1 ts))
  16575. (when suppress-tmp-delay
  16576. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16577. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16578. (setq with-hm t))
  16579. (setq time0 (org-parse-time-string ts))
  16580. (when (and updown
  16581. (eq org-ts-what 'minute)
  16582. (not current-prefix-arg))
  16583. ;; This looks like s-up and s-down. Change by one rounding step.
  16584. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16585. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16586. (setcar (cdr time0) (+ (nth 1 time0)
  16587. (if (> n 0) (- rem) (- dm rem))))))
  16588. (setq time
  16589. (apply #'encode-time
  16590. (or (car time0) 0)
  16591. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16592. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16593. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16594. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16595. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16596. (nthcdr 6 time0)))
  16597. (when (and (member org-ts-what '(hour minute))
  16598. extra
  16599. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16600. (setq extra (org-modify-ts-extra
  16601. extra
  16602. (if (eq org-ts-what 'hour) 2 5)
  16603. n dm)))
  16604. (when (integerp org-ts-what)
  16605. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16606. (when (eq what 'calendar)
  16607. (let ((cal-date (org-get-date-from-calendar)))
  16608. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16609. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16610. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16611. (setcar time0 (or (car time0) 0))
  16612. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16613. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16614. (setq time (apply 'encode-time time0))))
  16615. ;; Insert the new time-stamp, and ensure point stays in the same
  16616. ;; category as before (i.e. not after the last position in that
  16617. ;; category).
  16618. (let ((pos (point)))
  16619. ;; Stay before inserted string. `save-excursion' is of no use.
  16620. (setq org-last-changed-timestamp
  16621. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16622. (goto-char pos))
  16623. (save-match-data
  16624. (looking-at org-ts-regexp3)
  16625. (goto-char
  16626. (pcase origin-cat
  16627. ;; `day' category ends before `hour' if any, or at the end
  16628. ;; of the day name.
  16629. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16630. (`hour (min (match-end 7) origin))
  16631. (`minute (min (1- (match-end 8)) origin))
  16632. ((pred integerp) (min (1- (match-end 0)) origin))
  16633. ;; Point was right after the time-stamp. However, the
  16634. ;; time-stamp length might have changed, so refer to
  16635. ;; (match-end 0) instead.
  16636. (`after (match-end 0))
  16637. ;; `year' and `month' have both fixed size: point couldn't
  16638. ;; have moved into another part.
  16639. (_ origin))))
  16640. ;; Update clock if on a CLOCK line.
  16641. (org-clock-update-time-maybe)
  16642. ;; Maybe adjust the closest clock in `org-clock-history'
  16643. (when org-clock-adjust-closest
  16644. (if (not (and (org-at-clock-log-p)
  16645. (< 1 (length (delq nil (mapcar 'marker-position
  16646. org-clock-history))))))
  16647. (message "No clock to adjust")
  16648. (cond ((save-excursion ; fix previous clock?
  16649. (re-search-backward org-ts-regexp0 nil t)
  16650. (looking-back (concat org-clock-string " \\[")
  16651. (line-beginning-position)))
  16652. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16653. ((save-excursion ; fix next clock?
  16654. (re-search-backward org-ts-regexp0 nil t)
  16655. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16656. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16657. (save-window-excursion
  16658. ;; Find closest clock to point, adjust the previous/next one in history
  16659. (let* ((p (save-excursion (org-back-to-heading t)))
  16660. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16661. (clfixnth
  16662. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16663. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16664. (if (not clfixpos)
  16665. (message "No clock to adjust")
  16666. (save-excursion
  16667. (org-goto-marker-or-bmk clfixpos)
  16668. (org-show-subtree)
  16669. (when (re-search-forward clrgx nil t)
  16670. (goto-char (match-beginning 1))
  16671. (let (org-clock-adjust-closest)
  16672. (org-timestamp-change n org-ts-what updown))
  16673. (message "Clock adjusted in %s for heading: %s"
  16674. (file-name-nondirectory (buffer-file-name))
  16675. (org-get-heading t t)))))))))
  16676. ;; Try to recenter the calendar window, if any.
  16677. (when (and org-calendar-follow-timestamp-change
  16678. (get-buffer-window "*Calendar*" t)
  16679. (memq org-ts-what '(day month year)))
  16680. (org-recenter-calendar (time-to-days time))))))
  16681. (defun org-modify-ts-extra (s pos n dm)
  16682. "Change the different parts of the lead-time and repeat fields in timestamp."
  16683. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16684. ng h m new rem)
  16685. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16686. (cond
  16687. ((or (org-pos-in-match-range pos 2)
  16688. (org-pos-in-match-range pos 3))
  16689. (setq m (string-to-number (match-string 3 s))
  16690. h (string-to-number (match-string 2 s)))
  16691. (if (org-pos-in-match-range pos 2)
  16692. (setq h (+ h n))
  16693. (setq n (* dm (with-no-warnings (signum n))))
  16694. (unless (= 0 (setq rem (% m dm)))
  16695. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16696. (setq m (+ m n)))
  16697. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16698. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16699. (setq h (mod h 24))
  16700. (setq ng 1 new (format "-%02d:%02d" h m)))
  16701. ((org-pos-in-match-range pos 6)
  16702. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16703. ((org-pos-in-match-range pos 5)
  16704. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16705. ((org-pos-in-match-range pos 9)
  16706. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16707. ((org-pos-in-match-range pos 8)
  16708. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16709. (when ng
  16710. (setq s (concat
  16711. (substring s 0 (match-beginning ng))
  16712. new
  16713. (substring s (match-end ng))))))
  16714. s))
  16715. (defun org-recenter-calendar (d)
  16716. "If the calendar is visible, recenter it to date D."
  16717. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16718. (when cwin
  16719. (let ((calendar-move-hook nil))
  16720. (with-selected-window cwin
  16721. (calendar-goto-date
  16722. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16723. (defun org-goto-calendar (&optional arg)
  16724. "Go to the Emacs calendar at the current date.
  16725. If there is a time stamp in the current line, go to that date.
  16726. A prefix ARG can be used to force the current date."
  16727. (interactive "P")
  16728. (let ((tsr org-ts-regexp) diff
  16729. (calendar-move-hook nil)
  16730. (calendar-view-holidays-initially-flag nil)
  16731. (calendar-view-diary-initially-flag nil))
  16732. (when (or (org-at-timestamp-p)
  16733. (save-excursion
  16734. (beginning-of-line 1)
  16735. (looking-at (concat ".*" tsr))))
  16736. (let ((d1 (time-to-days (current-time)))
  16737. (d2 (time-to-days
  16738. (org-time-string-to-time (match-string 1)))))
  16739. (setq diff (- d2 d1))))
  16740. (calendar)
  16741. (calendar-goto-today)
  16742. (when (and diff (not arg)) (calendar-forward-day diff))))
  16743. (defun org-get-date-from-calendar ()
  16744. "Return a list (month day year) of date at point in calendar."
  16745. (with-current-buffer "*Calendar*"
  16746. (save-match-data
  16747. (calendar-cursor-to-date))))
  16748. (defun org-date-from-calendar ()
  16749. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16750. If there is already a time stamp at the cursor position, update it."
  16751. (interactive)
  16752. (if (org-at-timestamp-p t)
  16753. (org-timestamp-change 0 'calendar)
  16754. (let ((cal-date (org-get-date-from-calendar)))
  16755. (org-insert-time-stamp
  16756. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16757. (defcustom org-effort-durations
  16758. `(("min" . 1)
  16759. ("h" . 60)
  16760. ("d" . ,(* 60 8))
  16761. ("w" . ,(* 60 8 5))
  16762. ("m" . ,(* 60 8 5 4))
  16763. ("y" . ,(* 60 8 5 40)))
  16764. "Conversion factor to minutes for an effort modifier.
  16765. Each entry has the form (MODIFIER . MINUTES).
  16766. In an effort string, a number followed by MODIFIER is multiplied
  16767. by the specified number of MINUTES to obtain an effort in
  16768. minutes.
  16769. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16770. effort string \"2hours\" is equivalent to 120 minutes."
  16771. :group 'org-agenda
  16772. :version "25.2"
  16773. :package-version '(Org . "8.3")
  16774. :type '(alist :key-type (string :tag "Modifier")
  16775. :value-type (number :tag "Minutes")))
  16776. (defun org-minutes-to-clocksum-string (m)
  16777. "Format number of minutes as a clocksum string.
  16778. The format is determined by `org-time-clocksum-format',
  16779. `org-time-clocksum-use-fractional' and
  16780. `org-time-clocksum-fractional-format' and
  16781. `org-time-clocksum-use-effort-durations'."
  16782. (let ((clocksum "")
  16783. (m (round m)) ; Don't allow fractions of minutes
  16784. h d w mo y fmt n)
  16785. (setq h (if org-time-clocksum-use-effort-durations
  16786. (cdr (assoc "h" org-effort-durations)) 60)
  16787. d (if org-time-clocksum-use-effort-durations
  16788. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16789. w (if org-time-clocksum-use-effort-durations
  16790. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16791. mo (if org-time-clocksum-use-effort-durations
  16792. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16793. y (if org-time-clocksum-use-effort-durations
  16794. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16795. ;; fractional format
  16796. (if org-time-clocksum-use-fractional
  16797. (cond
  16798. ;; single format string
  16799. ((stringp org-time-clocksum-fractional-format)
  16800. (format org-time-clocksum-fractional-format (/ m (float h))))
  16801. ;; choice of fractional formats for different time units
  16802. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16803. (> (/ (truncate m) (* y d h)) 0))
  16804. (format fmt (/ m (* y d (float h)))))
  16805. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16806. (> (/ (truncate m) (* mo d h)) 0))
  16807. (format fmt (/ m (* mo d (float h)))))
  16808. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16809. (> (/ (truncate m) (* w d h)) 0))
  16810. (format fmt (/ m (* w d (float h)))))
  16811. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16812. (> (/ (truncate m) (* d h)) 0))
  16813. (format fmt (/ m (* d (float h)))))
  16814. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16815. (> (/ (truncate m) h) 0))
  16816. (format fmt (/ m (float h))))
  16817. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16818. (format fmt m))
  16819. ;; fall back to smallest time unit with a format
  16820. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16821. (format fmt (/ m (float h))))
  16822. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16823. (format fmt (/ m (* d (float h)))))
  16824. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16825. (format fmt (/ m (* w d (float h)))))
  16826. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16827. (format fmt (/ m (* mo d (float h)))))
  16828. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16829. (format fmt (/ m (* y d (float h))))))
  16830. ;; standard (non-fractional) format, with single format string
  16831. (if (stringp org-time-clocksum-format)
  16832. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16833. ;; separate formats components
  16834. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16835. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16836. (plist-get org-time-clocksum-format :require-years))
  16837. (setq clocksum (concat clocksum (format fmt n))
  16838. m (- m (* n y d h))))
  16839. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16840. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16841. (plist-get org-time-clocksum-format :require-months))
  16842. (setq clocksum (concat clocksum (format fmt n))
  16843. m (- m (* n mo d h))))
  16844. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16845. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16846. (plist-get org-time-clocksum-format :require-weeks))
  16847. (setq clocksum (concat clocksum (format fmt n))
  16848. m (- m (* n w d h))))
  16849. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16850. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16851. (plist-get org-time-clocksum-format :require-days))
  16852. (setq clocksum (concat clocksum (format fmt n))
  16853. m (- m (* n d h))))
  16854. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16855. (or (> (setq n (/ (truncate m) h)) 0)
  16856. (plist-get org-time-clocksum-format :require-hours))
  16857. (setq clocksum (concat clocksum (format fmt n))
  16858. m (- m (* n h))))
  16859. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16860. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16861. (setq clocksum (concat clocksum (format fmt m))))
  16862. ;; return formatted time duration
  16863. clocksum))))
  16864. (defun org-hours-to-clocksum-string (n)
  16865. (org-minutes-to-clocksum-string (* n 60)))
  16866. (defun org-hh:mm-string-to-minutes (s)
  16867. "Convert a string H:MM to a number of minutes.
  16868. If the string is just a number, interpret it as minutes.
  16869. In fact, the first hh:mm or number in the string will be taken,
  16870. there can be extra stuff in the string.
  16871. If no number is found, the return value is 0."
  16872. (cond
  16873. ((integerp s) s)
  16874. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16875. (+ (* (string-to-number (match-string 1 s)) 60)
  16876. (string-to-number (match-string 2 s))))
  16877. ((string-match "\\([0-9]+\\)" s)
  16878. (string-to-number (match-string 1 s)))
  16879. (t 0)))
  16880. (defcustom org-image-actual-width t
  16881. "Should we use the actual width of images when inlining them?
  16882. When set to t, always use the image width.
  16883. When set to a number, use imagemagick (when available) to set
  16884. the image's width to this value.
  16885. When set to a number in a list, try to get the width from any
  16886. #+ATTR.* keyword if it matches a width specification like
  16887. #+ATTR_HTML: :width 300px
  16888. and fall back on that number if none is found.
  16889. When set to nil, try to get the width from an #+ATTR.* keyword
  16890. and fall back on the original width if none is found.
  16891. This requires Emacs >= 24.1, build with imagemagick support."
  16892. :group 'org-appearance
  16893. :version "24.4"
  16894. :package-version '(Org . "8.0")
  16895. :type '(choice
  16896. (const :tag "Use the image width" t)
  16897. (integer :tag "Use a number of pixels")
  16898. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16899. (const :tag "Use #+ATTR* or don't resize" nil)))
  16900. (defcustom org-agenda-inhibit-startup nil
  16901. "Inhibit startup when preparing agenda buffers.
  16902. When this variable is t, the initialization of the Org agenda
  16903. buffers is inhibited: e.g. the visibility state is not set, the
  16904. tables are not re-aligned, etc."
  16905. :type 'boolean
  16906. :version "24.3"
  16907. :group 'org-agenda)
  16908. (defcustom org-agenda-ignore-properties nil
  16909. "Avoid updating text properties when building the agenda.
  16910. Properties are used to prepare buffers for effort estimates,
  16911. appointments, statistics and subtree-local categories.
  16912. If you don't use these in the agenda, you can add them to this
  16913. list and agenda building will be a bit faster.
  16914. The value is a list, with zero or more of the symbols `effort', `appt',
  16915. `stats' or `category'."
  16916. :type '(set :greedy t
  16917. (const effort)
  16918. (const appt)
  16919. (const stats)
  16920. (const category))
  16921. :version "25.2"
  16922. :package-version '(Org . "8.3")
  16923. :group 'org-agenda)
  16924. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16925. "Convert a duration string S to minutes.
  16926. A bare number is interpreted as minutes, modifiers can be set by
  16927. customizing `org-effort-durations' (which see).
  16928. Entries containing a colon are interpreted as H:MM by
  16929. `org-hh:mm-string-to-minutes'."
  16930. (let ((result 0)
  16931. (re (concat "\\([0-9.]+\\) *\\("
  16932. (regexp-opt (mapcar 'car org-effort-durations))
  16933. "\\)")))
  16934. (while (string-match re s)
  16935. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16936. (string-to-number (match-string 1 s))))
  16937. (setq s (replace-match "" nil t s)))
  16938. (setq result (floor result))
  16939. (cl-incf result (org-hh:mm-string-to-minutes s))
  16940. (if output-to-string (number-to-string result) result)))
  16941. ;;;; Files
  16942. (defun org-save-all-org-buffers ()
  16943. "Save all Org buffers without user confirmation."
  16944. (interactive)
  16945. (message "Saving all Org buffers...")
  16946. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16947. (when (featurep 'org-id) (org-id-locations-save))
  16948. (message "Saving all Org buffers... done"))
  16949. (defun org-revert-all-org-buffers ()
  16950. "Revert all Org buffers.
  16951. Prompt for confirmation when there are unsaved changes.
  16952. Be sure you know what you are doing before letting this function
  16953. overwrite your changes.
  16954. This function is useful in a setup where one tracks org files
  16955. with a version control system, to revert on one machine after pulling
  16956. changes from another. I believe the procedure must be like this:
  16957. 1. M-x org-save-all-org-buffers
  16958. 2. Pull changes from the other machine, resolve conflicts
  16959. 3. M-x org-revert-all-org-buffers"
  16960. (interactive)
  16961. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16962. (user-error "Abort"))
  16963. (save-excursion
  16964. (save-window-excursion
  16965. (dolist (b (buffer-list))
  16966. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16967. (with-current-buffer b buffer-file-name))
  16968. (pop-to-buffer-same-window b)
  16969. (revert-buffer t 'no-confirm)))
  16970. (when (and (featurep 'org-id) org-id-track-globally)
  16971. (org-id-locations-load)))))
  16972. ;;;; Agenda files
  16973. ;;;###autoload
  16974. (defun org-switchb (&optional arg)
  16975. "Switch between Org buffers.
  16976. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16977. With `\\[universal-argument] \\[universal-argument]' \
  16978. prefix, restrict available buffers to agenda files."
  16979. (interactive "P")
  16980. (let ((blist (org-buffer-list
  16981. (cond ((equal arg '(4)) 'files)
  16982. ((equal arg '(16)) 'agenda)))))
  16983. (pop-to-buffer-same-window
  16984. (completing-read "Org buffer: "
  16985. (mapcar #'list (mapcar #'buffer-name blist))
  16986. nil t))))
  16987. (defun org-buffer-list (&optional predicate exclude-tmp)
  16988. "Return a list of Org buffers.
  16989. PREDICATE can be `export', `files' or `agenda'.
  16990. export restrict the list to Export buffers.
  16991. files restrict the list to buffers visiting Org files.
  16992. agenda restrict the list to buffers visiting agenda files.
  16993. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16994. (let* ((bfn nil)
  16995. (agenda-files (and (eq predicate 'agenda)
  16996. (mapcar 'file-truename (org-agenda-files t))))
  16997. (filter
  16998. (cond
  16999. ((eq predicate 'files)
  17000. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  17001. ((eq predicate 'export)
  17002. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  17003. ((eq predicate 'agenda)
  17004. (lambda (b)
  17005. (with-current-buffer b
  17006. (and (derived-mode-p 'org-mode)
  17007. (setq bfn (buffer-file-name b))
  17008. (member (file-truename bfn) agenda-files)))))
  17009. (t (lambda (b) (with-current-buffer b
  17010. (or (derived-mode-p 'org-mode)
  17011. (string-match "\\*Org .*Export"
  17012. (buffer-name b)))))))))
  17013. (delq nil
  17014. (mapcar
  17015. (lambda(b)
  17016. (if (and (funcall filter b)
  17017. (or (not exclude-tmp)
  17018. (not (string-match "tmp" (buffer-name b)))))
  17019. b
  17020. nil))
  17021. (buffer-list)))))
  17022. (defun org-agenda-files (&optional unrestricted archives)
  17023. "Get the list of agenda files.
  17024. Optional UNRESTRICTED means return the full list even if a restriction
  17025. is currently in place.
  17026. When ARCHIVES is t, include all archive files that are really being
  17027. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  17028. `org-agenda-archives-mode' is t."
  17029. (let ((files
  17030. (cond
  17031. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  17032. ((stringp org-agenda-files) (org-read-agenda-file-list))
  17033. ((listp org-agenda-files) org-agenda-files)
  17034. (t (error "Invalid value of `org-agenda-files'")))))
  17035. (setq files (apply 'append
  17036. (mapcar (lambda (f)
  17037. (if (file-directory-p f)
  17038. (directory-files
  17039. f t org-agenda-file-regexp)
  17040. (list f)))
  17041. files)))
  17042. (when org-agenda-skip-unavailable-files
  17043. (setq files (delq nil
  17044. (mapcar (function
  17045. (lambda (file)
  17046. (and (file-readable-p file) file)))
  17047. files))))
  17048. (when (or (eq archives t)
  17049. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17050. (setq files (org-add-archive-files files)))
  17051. files))
  17052. (defun org-agenda-file-p (&optional file)
  17053. "Return non-nil, if FILE is an agenda file.
  17054. If FILE is omitted, use the file associated with the current
  17055. buffer."
  17056. (let ((fname (or file (buffer-file-name))))
  17057. (and fname
  17058. (member (file-truename fname)
  17059. (mapcar #'file-truename (org-agenda-files t))))))
  17060. (defun org-edit-agenda-file-list ()
  17061. "Edit the list of agenda files.
  17062. Depending on setup, this either uses customize to edit the variable
  17063. `org-agenda-files', or it visits the file that is holding the list. In the
  17064. latter case, the buffer is set up in a way that saving it automatically kills
  17065. the buffer and restores the previous window configuration."
  17066. (interactive)
  17067. (if (stringp org-agenda-files)
  17068. (let ((cw (current-window-configuration)))
  17069. (find-file org-agenda-files)
  17070. (setq-local org-window-configuration cw)
  17071. (add-hook 'after-save-hook
  17072. (lambda ()
  17073. (set-window-configuration
  17074. (prog1 org-window-configuration
  17075. (kill-buffer (current-buffer))))
  17076. (org-install-agenda-files-menu)
  17077. (message "New agenda file list installed"))
  17078. nil 'local)
  17079. (message "%s" (substitute-command-keys
  17080. "Edit list and finish with \\[save-buffer]")))
  17081. (customize-variable 'org-agenda-files)))
  17082. (defun org-store-new-agenda-file-list (list)
  17083. "Set new value for the agenda file list and save it correctly."
  17084. (if (stringp org-agenda-files)
  17085. (let ((fe (org-read-agenda-file-list t)) b u)
  17086. (while (setq b (find-buffer-visiting org-agenda-files))
  17087. (kill-buffer b))
  17088. (with-temp-file org-agenda-files
  17089. (insert
  17090. (mapconcat
  17091. (lambda (f) ;; Keep un-expanded entries.
  17092. (if (setq u (assoc f fe))
  17093. (cdr u)
  17094. f))
  17095. list "\n")
  17096. "\n")))
  17097. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17098. (org-insert-mode-line-in-empty-file nil))
  17099. (setq org-agenda-files list)
  17100. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17101. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17102. "Read the list of agenda files from a file.
  17103. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17104. filenames, used by `org-store-new-agenda-file-list' to write back
  17105. un-expanded file names."
  17106. (when (file-directory-p org-agenda-files)
  17107. (error "`org-agenda-files' cannot be a single directory"))
  17108. (when (stringp org-agenda-files)
  17109. (with-temp-buffer
  17110. (insert-file-contents org-agenda-files)
  17111. (mapcar
  17112. (lambda (f)
  17113. (let ((e (expand-file-name (substitute-in-file-name f)
  17114. org-directory)))
  17115. (if pair-with-expansion
  17116. (cons e f)
  17117. e)))
  17118. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17119. ;;;###autoload
  17120. (defun org-cycle-agenda-files ()
  17121. "Cycle through the files in `org-agenda-files'.
  17122. If the current buffer visits an agenda file, find the next one in the list.
  17123. If the current buffer does not, find the first agenda file."
  17124. (interactive)
  17125. (let* ((fs (or (org-agenda-files t)
  17126. (user-error "No agenda files")))
  17127. (files (copy-sequence fs))
  17128. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17129. file)
  17130. (when tcf
  17131. (while (and (setq file (pop files))
  17132. (not (equal (file-truename file) tcf)))))
  17133. (find-file (car (or files fs)))
  17134. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17135. (defun org-agenda-file-to-front (&optional to-end)
  17136. "Move/add the current file to the top of the agenda file list.
  17137. If the file is not present in the list, it is added to the front. If it is
  17138. present, it is moved there. With optional argument TO-END, add/move to the
  17139. end of the list."
  17140. (interactive "P")
  17141. (let ((org-agenda-skip-unavailable-files nil)
  17142. (file-alist (mapcar (lambda (x)
  17143. (cons (file-truename x) x))
  17144. (org-agenda-files t)))
  17145. (ctf (file-truename
  17146. (or buffer-file-name
  17147. (user-error "Please save the current buffer to a file"))))
  17148. x had)
  17149. (setq x (assoc ctf file-alist) had x)
  17150. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17151. (if to-end
  17152. (setq file-alist (append (delq x file-alist) (list x)))
  17153. (setq file-alist (cons x (delq x file-alist))))
  17154. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17155. (org-install-agenda-files-menu)
  17156. (message "File %s to %s of agenda file list"
  17157. (if had "moved" "added") (if to-end "end" "front"))))
  17158. (defun org-remove-file (&optional file)
  17159. "Remove current file from the list of files in variable `org-agenda-files'.
  17160. These are the files which are being checked for agenda entries.
  17161. Optional argument FILE means use this file instead of the current."
  17162. (interactive)
  17163. (let* ((org-agenda-skip-unavailable-files nil)
  17164. (file (or file buffer-file-name
  17165. (user-error "Current buffer does not visit a file")))
  17166. (true-file (file-truename file))
  17167. (afile (abbreviate-file-name file))
  17168. (files (delq nil (mapcar
  17169. (lambda (x)
  17170. (unless (equal true-file
  17171. (file-truename x))
  17172. x))
  17173. (org-agenda-files t)))))
  17174. (if (not (= (length files) (length (org-agenda-files t))))
  17175. (progn
  17176. (org-store-new-agenda-file-list files)
  17177. (org-install-agenda-files-menu)
  17178. (message "Removed from Org Agenda list: %s" afile))
  17179. (message "File was not in list: %s (not removed)" afile))))
  17180. (defun org-file-menu-entry (file)
  17181. (vector file (list 'find-file file) t))
  17182. (defun org-check-agenda-file (file)
  17183. "Make sure FILE exists. If not, ask user what to do."
  17184. (unless (file-exists-p file)
  17185. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17186. (abbreviate-file-name file))
  17187. (let ((r (downcase (read-char-exclusive))))
  17188. (cond
  17189. ((equal r ?r)
  17190. (org-remove-file file)
  17191. (throw 'nextfile t))
  17192. (t (user-error "Abort"))))))
  17193. (defun org-get-agenda-file-buffer (file)
  17194. "Get an agenda buffer visiting FILE.
  17195. If the buffer needs to be created, add it to the list of buffers
  17196. which might be released later."
  17197. (let ((buf (org-find-base-buffer-visiting file)))
  17198. (if buf
  17199. buf ; just return it
  17200. ;; Make a new buffer and remember it
  17201. (setq buf (find-file-noselect file))
  17202. (when buf (push buf org-agenda-new-buffers))
  17203. buf)))
  17204. (defun org-release-buffers (blist)
  17205. "Release all buffers in list, asking the user for confirmation when needed.
  17206. When a buffer is unmodified, it is just killed. When modified, it is saved
  17207. \(if the user agrees) and then killed."
  17208. (let (file)
  17209. (dolist (buf blist)
  17210. (setq file (buffer-file-name buf))
  17211. (when (and (buffer-modified-p buf)
  17212. file
  17213. (y-or-n-p (format "Save file %s? " file)))
  17214. (with-current-buffer buf (save-buffer)))
  17215. (kill-buffer buf))))
  17216. (defun org-agenda-prepare-buffers (files)
  17217. "Create buffers for all agenda files, protect archived trees and comments."
  17218. (interactive)
  17219. (let ((pa '(:org-archived t))
  17220. (pc '(:org-comment t))
  17221. (pall '(:org-archived t :org-comment t))
  17222. (inhibit-read-only t)
  17223. (org-inhibit-startup org-agenda-inhibit-startup)
  17224. (rea (concat ":" org-archive-tag ":"))
  17225. re pos)
  17226. (setq org-tag-alist-for-agenda nil
  17227. org-tag-groups-alist-for-agenda nil)
  17228. (save-excursion
  17229. (save-restriction
  17230. (dolist (file files)
  17231. (catch 'nextfile
  17232. (if (bufferp file)
  17233. (set-buffer file)
  17234. (org-check-agenda-file file)
  17235. (set-buffer (org-get-agenda-file-buffer file)))
  17236. (widen)
  17237. (org-set-regexps-and-options 'tags-only)
  17238. (setq pos (point))
  17239. (or (memq 'category org-agenda-ignore-properties)
  17240. (org-refresh-category-properties))
  17241. (or (memq 'stats org-agenda-ignore-properties)
  17242. (org-refresh-stats-properties))
  17243. (or (memq 'effort org-agenda-ignore-properties)
  17244. (org-refresh-effort-properties))
  17245. (or (memq 'appt org-agenda-ignore-properties)
  17246. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17247. (setq org-todo-keywords-for-agenda
  17248. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17249. (setq org-done-keywords-for-agenda
  17250. (append org-done-keywords-for-agenda org-done-keywords))
  17251. (setq org-todo-keyword-alist-for-agenda
  17252. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17253. (setq org-tag-alist-for-agenda
  17254. (org-uniquify
  17255. (append org-tag-alist-for-agenda
  17256. org-current-tag-alist)))
  17257. ;; Merge current file's tag groups into global
  17258. ;; `org-tag-groups-alist-for-agenda'.
  17259. (when org-group-tags
  17260. (dolist (alist org-tag-groups-alist)
  17261. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17262. (if old
  17263. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17264. (push alist org-tag-groups-alist-for-agenda)))))
  17265. (org-with-silent-modifications
  17266. (save-excursion
  17267. (remove-text-properties (point-min) (point-max) pall)
  17268. (when org-agenda-skip-archived-trees
  17269. (goto-char (point-min))
  17270. (while (re-search-forward rea nil t)
  17271. (when (org-at-heading-p t)
  17272. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17273. (goto-char (point-min))
  17274. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17275. (while (re-search-forward re nil t)
  17276. (when (save-match-data (org-in-commented-heading-p t))
  17277. (add-text-properties
  17278. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17279. (goto-char pos)))))
  17280. (setq org-todo-keywords-for-agenda
  17281. (org-uniquify org-todo-keywords-for-agenda))
  17282. (setq org-todo-keyword-alist-for-agenda
  17283. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17284. ;;;; CDLaTeX minor mode
  17285. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17286. "Keymap for the minor `org-cdlatex-mode'.")
  17287. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17288. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17289. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17290. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17291. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17292. (defvar org-cdlatex-texmathp-advice-is-done nil
  17293. "Flag remembering if we have applied the advice to texmathp already.")
  17294. (define-minor-mode org-cdlatex-mode
  17295. "Toggle the minor `org-cdlatex-mode'.
  17296. This mode supports entering LaTeX environment and math in LaTeX fragments
  17297. in Org mode.
  17298. \\{org-cdlatex-mode-map}"
  17299. nil " OCDL" nil
  17300. (when org-cdlatex-mode
  17301. (require 'cdlatex)
  17302. (run-hooks 'cdlatex-mode-hook)
  17303. (cdlatex-compute-tables))
  17304. (unless org-cdlatex-texmathp-advice-is-done
  17305. (setq org-cdlatex-texmathp-advice-is-done t)
  17306. (defadvice texmathp (around org-math-always-on activate)
  17307. "Always return t in Org buffers.
  17308. This is because we want to insert math symbols without dollars even outside
  17309. the LaTeX math segments. If Org mode thinks that point is actually inside
  17310. an embedded LaTeX fragment, let `texmathp' do its job.
  17311. `\\[org-cdlatex-mode-map]'"
  17312. (interactive)
  17313. (let (p)
  17314. (cond
  17315. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17316. ((eq this-command 'cdlatex-math-symbol)
  17317. (setq ad-return-value t
  17318. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17319. (t
  17320. (let ((p (org-inside-LaTeX-fragment-p)))
  17321. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17322. (setq ad-return-value t
  17323. texmathp-why '("Org mode embedded math" . 0))
  17324. (when p ad-do-it)))))))))
  17325. (defun turn-on-org-cdlatex ()
  17326. "Unconditionally turn on `org-cdlatex-mode'."
  17327. (org-cdlatex-mode 1))
  17328. (defun org-try-cdlatex-tab ()
  17329. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17330. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17331. - inside a LaTeX fragment, or
  17332. - after the first word in a line, where an abbreviation expansion could
  17333. insert a LaTeX environment."
  17334. (when org-cdlatex-mode
  17335. (cond
  17336. ;; Before any word on the line: No expansion possible.
  17337. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17338. ;; Just after first word on the line: Expand it. Make sure it
  17339. ;; cannot happen on headlines, though.
  17340. ((save-excursion
  17341. (skip-chars-backward "a-zA-Z0-9*")
  17342. (skip-chars-backward " \t")
  17343. (and (bolp) (not (org-at-heading-p))))
  17344. (cdlatex-tab) t)
  17345. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17346. (defun org-cdlatex-underscore-caret (&optional _arg)
  17347. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17348. Revert to the normal definition outside of these fragments."
  17349. (interactive "P")
  17350. (if (org-inside-LaTeX-fragment-p)
  17351. (call-interactively 'cdlatex-sub-superscript)
  17352. (let (org-cdlatex-mode)
  17353. (call-interactively (key-binding (vector last-input-event))))))
  17354. (defun org-cdlatex-math-modify (&optional _arg)
  17355. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17356. Revert to the normal definition outside of these fragments."
  17357. (interactive "P")
  17358. (if (org-inside-LaTeX-fragment-p)
  17359. (call-interactively 'cdlatex-math-modify)
  17360. (let (org-cdlatex-mode)
  17361. (call-interactively (key-binding (vector last-input-event))))))
  17362. (defun org-cdlatex-environment-indent (&optional environment item)
  17363. "Execute `cdlatex-environment' and indent the inserted environment.
  17364. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17365. The inserted environment is indented to current indentation
  17366. unless point is at the beginning of the line, in which the
  17367. environment remains unintended."
  17368. (interactive)
  17369. ;; cdlatex-environment always return nil. Therefore, capture output
  17370. ;; first and determine if an environment was selected.
  17371. (let* ((beg (point-marker))
  17372. (end (copy-marker (point) t))
  17373. (inserted (progn
  17374. (ignore-errors (cdlatex-environment environment item))
  17375. (< beg end)))
  17376. ;; Figure out how many lines to move forward after the
  17377. ;; environment has been inserted.
  17378. (lines (when inserted
  17379. (save-excursion
  17380. (- (cl-loop while (< beg (point))
  17381. with x = 0
  17382. do (forward-line -1)
  17383. (cl-incf x)
  17384. finally return x)
  17385. (if (progn (goto-char beg)
  17386. (and (progn (skip-chars-forward " \t") (eolp))
  17387. (progn (skip-chars-backward " \t") (bolp))))
  17388. 1 0)))))
  17389. (env (org-trim (delete-and-extract-region beg end))))
  17390. (when inserted
  17391. ;; Get indentation of next line unless at column 0.
  17392. (let ((ind (if (bolp) 0
  17393. (save-excursion
  17394. (org-return-indent)
  17395. (prog1 (org-get-indentation)
  17396. (when (progn (skip-chars-forward " \t") (eolp))
  17397. (delete-region beg (point)))))))
  17398. (bol (progn (skip-chars-backward " \t") (bolp))))
  17399. ;; Insert a newline before environment unless at column zero
  17400. ;; to "escape" the current line. Insert a newline if
  17401. ;; something is one the same line as \end{ENVIRONMENT}.
  17402. (insert
  17403. (concat (unless bol "\n") env
  17404. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17405. (unless (zerop ind)
  17406. (save-excursion
  17407. (goto-char beg)
  17408. (while (< (point) end)
  17409. (unless (eolp) (indent-line-to ind))
  17410. (forward-line))))
  17411. (goto-char beg)
  17412. (forward-line lines)
  17413. (indent-line-to ind)))
  17414. (set-marker beg nil)
  17415. (set-marker end nil)))
  17416. ;;;; LaTeX fragments
  17417. (defun org-inside-LaTeX-fragment-p ()
  17418. "Test if point is inside a LaTeX fragment.
  17419. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17420. sequence appearing also before point.
  17421. Even though the matchers for math are configurable, this function assumes
  17422. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17423. delimiters are skipped when they have been removed by customization.
  17424. The return value is nil, or a cons cell with the delimiter and the
  17425. position of this delimiter.
  17426. This function does a reasonably good job, but can locally be fooled by
  17427. for example currency specifications. For example it will assume being in
  17428. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17429. fragments that are properly closed, but during editing, we have to live
  17430. with the uncertainty caused by missing closing delimiters. This function
  17431. looks only before point, not after."
  17432. (catch 'exit
  17433. (let ((pos (point))
  17434. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17435. (lim (progn
  17436. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17437. (point)))
  17438. dd-on str (start 0) m re)
  17439. (goto-char pos)
  17440. (when dodollar
  17441. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17442. re (nth 1 (assoc "$" org-latex-regexps)))
  17443. (while (string-match re str start)
  17444. (cond
  17445. ((= (match-end 0) (length str))
  17446. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17447. ((= (match-end 0) (- (length str) 5))
  17448. (throw 'exit nil))
  17449. (t (setq start (match-end 0))))))
  17450. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17451. (goto-char pos)
  17452. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17453. (and (match-beginning 2) (throw 'exit nil))
  17454. ;; count $$
  17455. (while (re-search-backward "\\$\\$" lim t)
  17456. (setq dd-on (not dd-on)))
  17457. (goto-char pos)
  17458. (when dd-on (cons "$$" m))))))
  17459. (defun org-inside-latex-macro-p ()
  17460. "Is point inside a LaTeX macro or its arguments?"
  17461. (save-match-data
  17462. (org-in-regexp
  17463. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17464. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17465. "Build an overlay between BEG and END using IMAGE file.
  17466. Argument IMAGETYPE is the extension of the displayed image,
  17467. as a string. It defaults to \"png\"."
  17468. (let ((ov (make-overlay beg end))
  17469. (imagetype (or (intern imagetype) 'png)))
  17470. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17471. (overlay-put ov 'evaporate t)
  17472. (overlay-put ov
  17473. 'modification-hooks
  17474. (list (lambda (o _flag _beg _end &optional _l)
  17475. (delete-overlay o))))
  17476. (overlay-put ov
  17477. 'display
  17478. (list 'image :type imagetype :file image :ascent 'center))))
  17479. (defun org--list-latex-overlays (&optional beg end)
  17480. "List all Org LaTeX overlays in current buffer.
  17481. Limit to overlays between BEG and END when those are provided."
  17482. (cl-remove-if-not
  17483. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17484. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17485. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17486. "Remove all overlays with LaTeX fragment images in current buffer.
  17487. When optional arguments BEG and END are non-nil, remove all
  17488. overlays between them instead. Return a non-nil value when some
  17489. overlays were removed, nil otherwise."
  17490. (let ((overlays (org--list-latex-overlays beg end)))
  17491. (mapc #'delete-overlay overlays)
  17492. overlays))
  17493. (defun org-toggle-latex-fragment (&optional arg)
  17494. "Preview the LaTeX fragment at point, or all locally or globally.
  17495. If the cursor is on a LaTeX fragment, create the image and overlay
  17496. it over the source code, if there is none. Remove it otherwise.
  17497. If there is no fragment at point, display all fragments in the
  17498. current section.
  17499. With prefix ARG, preview or clear image for all fragments in the
  17500. current subtree or in the whole buffer when used before the first
  17501. headline. With a prefix ARG `\\[universal-argument] \
  17502. \\[universal-argument]' preview or clear images
  17503. for all fragments in the buffer."
  17504. (interactive "P")
  17505. (when (display-graphic-p)
  17506. (catch 'exit
  17507. (save-excursion
  17508. (let (beg end msg)
  17509. (cond
  17510. ((or (equal arg '(16))
  17511. (and (equal arg '(4))
  17512. (org-with-limited-levels (org-before-first-heading-p))))
  17513. (if (org-remove-latex-fragment-image-overlays)
  17514. (progn (message "LaTeX fragments images removed from buffer")
  17515. (throw 'exit nil))
  17516. (setq msg "Creating images for buffer...")))
  17517. ((equal arg '(4))
  17518. (org-with-limited-levels (org-back-to-heading t))
  17519. (setq beg (point))
  17520. (setq end (progn (org-end-of-subtree t) (point)))
  17521. (if (org-remove-latex-fragment-image-overlays beg end)
  17522. (progn
  17523. (message "LaTeX fragment images removed from subtree")
  17524. (throw 'exit nil))
  17525. (setq msg "Creating images for subtree...")))
  17526. ((let ((datum (org-element-context)))
  17527. (when (memq (org-element-type datum)
  17528. '(latex-environment latex-fragment))
  17529. (setq beg (org-element-property :begin datum))
  17530. (setq end (org-element-property :end datum))
  17531. (if (org-remove-latex-fragment-image-overlays beg end)
  17532. (progn (message "LaTeX fragment image removed")
  17533. (throw 'exit nil))
  17534. (setq msg "Creating image...")))))
  17535. (t
  17536. (org-with-limited-levels
  17537. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17538. (outline-previous-heading)
  17539. (point)))
  17540. (setq end (progn (outline-next-heading) (point)))
  17541. (if (org-remove-latex-fragment-image-overlays beg end)
  17542. (progn
  17543. (message "LaTeX fragment images removed from section")
  17544. (throw 'exit nil))
  17545. (setq msg "Creating images for section...")))))
  17546. (let ((file (buffer-file-name (buffer-base-buffer))))
  17547. (org-format-latex
  17548. (concat org-preview-latex-image-directory "org-ltximg")
  17549. beg end
  17550. ;; Emacs cannot overlay images from remote hosts. Create
  17551. ;; it in `temporary-file-directory' instead.
  17552. (if (or (not file) (file-remote-p file))
  17553. temporary-file-directory
  17554. default-directory)
  17555. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17556. (message (concat msg "done")))))))
  17557. (defun org-format-latex
  17558. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17559. "Replace LaTeX fragments with links to an image.
  17560. The function takes care of creating the replacement image.
  17561. Only consider fragments between BEG and END when those are
  17562. provided.
  17563. When optional argument OVERLAYS is non-nil, display the image on
  17564. top of the fragment instead of replacing it.
  17565. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17566. Some of the options can be changed using the variable
  17567. `org-format-latex-options', which see."
  17568. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17569. (unless (eq processing-type 'verbatim)
  17570. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17571. (cnt 0)
  17572. checkdir-flag)
  17573. (goto-char (or beg (point-min)))
  17574. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17575. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17576. (overlay-recenter (or end (point-max))))
  17577. (while (re-search-forward math-regexp end t)
  17578. (unless (and overlays
  17579. (eq (get-char-property (point) 'org-overlay-type)
  17580. 'org-latex-overlay))
  17581. (let* ((context (org-element-context))
  17582. (type (org-element-type context)))
  17583. (when (memq type '(latex-environment latex-fragment))
  17584. (let ((block-type (eq type 'latex-environment))
  17585. (value (org-element-property :value context))
  17586. (beg (org-element-property :begin context))
  17587. (end (save-excursion
  17588. (goto-char (org-element-property :end context))
  17589. (skip-chars-backward " \r\t\n")
  17590. (point))))
  17591. (cond
  17592. ((eq processing-type 'mathjax)
  17593. ;; Prepare for MathJax processing.
  17594. (if (not (string-match "\\`\\$\\$?" value))
  17595. (goto-char end)
  17596. (delete-region beg end)
  17597. (if (string= (match-string 0 value) "$$")
  17598. (insert "\\[" (substring value 2 -2) "\\]")
  17599. (insert "\\(" (substring value 1 -1) "\\)"))))
  17600. ((assq processing-type org-preview-latex-process-alist)
  17601. ;; Process to an image.
  17602. (cl-incf cnt)
  17603. (goto-char beg)
  17604. (let* ((processing-info
  17605. (cdr (assq processing-type org-preview-latex-process-alist)))
  17606. (face (face-at-point))
  17607. ;; Get the colors from the face at point.
  17608. (fg
  17609. (let ((color (plist-get org-format-latex-options
  17610. :foreground)))
  17611. (if (and forbuffer (eq color 'auto))
  17612. (face-attribute face :foreground nil 'default)
  17613. color)))
  17614. (bg
  17615. (let ((color (plist-get org-format-latex-options
  17616. :background)))
  17617. (if (and forbuffer (eq color 'auto))
  17618. (face-attribute face :background nil 'default)
  17619. color)))
  17620. (hash (sha1 (prin1-to-string
  17621. (list org-format-latex-header
  17622. org-latex-default-packages-alist
  17623. org-latex-packages-alist
  17624. org-format-latex-options
  17625. forbuffer value fg bg))))
  17626. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17627. (absprefix (expand-file-name prefix dir))
  17628. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17629. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17630. (sep (and block-type "\n\n"))
  17631. (link (concat sep "[[file:" linkfile "]]" sep))
  17632. (options
  17633. (org-combine-plists
  17634. org-format-latex-options
  17635. `(:foreground ,fg :background ,bg))))
  17636. (when msg (message msg cnt))
  17637. (unless checkdir-flag ; Ensure the directory exists.
  17638. (setq checkdir-flag t)
  17639. (let ((todir (file-name-directory absprefix)))
  17640. (unless (file-directory-p todir)
  17641. (make-directory todir t))))
  17642. (unless (file-exists-p movefile)
  17643. (org-create-formula-image
  17644. value movefile options forbuffer processing-type))
  17645. (if overlays
  17646. (progn
  17647. (dolist (o (overlays-in beg end))
  17648. (when (eq (overlay-get o 'org-overlay-type)
  17649. 'org-latex-overlay)
  17650. (delete-overlay o)))
  17651. (org--format-latex-make-overlay beg end movefile imagetype)
  17652. (goto-char end))
  17653. (delete-region beg end)
  17654. (insert
  17655. (org-add-props link
  17656. (list 'org-latex-src
  17657. (replace-regexp-in-string "\"" "" value)
  17658. 'org-latex-src-embed-type
  17659. (if block-type 'paragraph 'character)))))))
  17660. ((eq processing-type 'mathml)
  17661. ;; Process to MathML.
  17662. (unless (org-format-latex-mathml-available-p)
  17663. (user-error "LaTeX to MathML converter not configured"))
  17664. (cl-incf cnt)
  17665. (when msg (message msg cnt))
  17666. (goto-char beg)
  17667. (delete-region beg end)
  17668. (insert (org-format-latex-as-mathml
  17669. value block-type prefix dir)))
  17670. (t
  17671. (error "Unknown conversion process %s for LaTeX fragments"
  17672. processing-type)))))))))))
  17673. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17674. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17675. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17676. sucessful, return the portion between \"<math...> </math>\"
  17677. elements otherwise return nil. When MATHML-FILE is specified,
  17678. write the results in to that file. When invoked as an
  17679. interactive command, prompt for LATEX-FRAG, with initial value
  17680. set to the current active region and echo the results for user
  17681. inspection."
  17682. (interactive (list (let ((frag (when (org-region-active-p)
  17683. (buffer-substring-no-properties
  17684. (region-beginning) (region-end)))))
  17685. (read-string "LaTeX Fragment: " frag nil frag))))
  17686. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17687. (let* ((tmp-in-file
  17688. (let ((file (file-relative-name
  17689. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17690. (write-region latex-frag nil file)
  17691. file))
  17692. (tmp-out-file (file-relative-name
  17693. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17694. (cmd (format-spec
  17695. org-latex-to-mathml-convert-command
  17696. `((?j . ,(and org-latex-to-mathml-jar-file
  17697. (shell-quote-argument
  17698. (expand-file-name
  17699. org-latex-to-mathml-jar-file))))
  17700. (?I . ,(shell-quote-argument tmp-in-file))
  17701. (?i . ,latex-frag)
  17702. (?o . ,(shell-quote-argument tmp-out-file)))))
  17703. mathml shell-command-output)
  17704. (when (called-interactively-p 'any)
  17705. (unless (org-format-latex-mathml-available-p)
  17706. (user-error "LaTeX to MathML converter not configured")))
  17707. (message "Running %s" cmd)
  17708. (setq shell-command-output (shell-command-to-string cmd))
  17709. (setq mathml
  17710. (when (file-readable-p tmp-out-file)
  17711. (with-current-buffer (find-file-noselect tmp-out-file t)
  17712. (goto-char (point-min))
  17713. (when (re-search-forward
  17714. (concat
  17715. (regexp-quote
  17716. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17717. "[^>]*?>"
  17718. "\\(.\\|\n\\)*"
  17719. "</math>")
  17720. nil t)
  17721. (prog1 (match-string 0) (kill-buffer))))))
  17722. (cond
  17723. (mathml
  17724. (setq mathml
  17725. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17726. (when mathml-file
  17727. (write-region mathml nil mathml-file))
  17728. (when (called-interactively-p 'any)
  17729. (message mathml)))
  17730. ((message "LaTeX to MathML conversion failed")
  17731. (message shell-command-output)))
  17732. (delete-file tmp-in-file)
  17733. (when (file-exists-p tmp-out-file)
  17734. (delete-file tmp-out-file))
  17735. mathml))
  17736. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17737. prefix &optional dir)
  17738. "Use `org-create-math-formula' but check local cache first."
  17739. (let* ((absprefix (expand-file-name prefix dir))
  17740. (print-length nil) (print-level nil)
  17741. (formula-id (concat
  17742. "formula-"
  17743. (sha1
  17744. (prin1-to-string
  17745. (list latex-frag
  17746. org-latex-to-mathml-convert-command)))))
  17747. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17748. (formula-cache-dir (file-name-directory formula-cache)))
  17749. (unless (file-directory-p formula-cache-dir)
  17750. (make-directory formula-cache-dir t))
  17751. (unless (file-exists-p formula-cache)
  17752. (org-create-math-formula latex-frag formula-cache))
  17753. (if (file-exists-p formula-cache)
  17754. ;; Successful conversion. Return the link to MathML file.
  17755. (org-add-props
  17756. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17757. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17758. 'org-latex-src-embed-type (if latex-frag-type
  17759. 'paragraph 'character)))
  17760. ;; Failed conversion. Return the LaTeX fragment verbatim
  17761. latex-frag)))
  17762. (declare-function org-export-get-backend "ox" (name))
  17763. (declare-function org-export--get-global-options "ox" (&optional backend))
  17764. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17765. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17766. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17767. (defun org-create-formula--latex-header ()
  17768. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17769. (let ((info (org-combine-plists (org-export--get-global-options
  17770. (org-export-get-backend 'latex))
  17771. (org-export--get-inbuffer-options
  17772. (org-export-get-backend 'latex)))))
  17773. (org-latex-guess-babel-language
  17774. (org-latex-guess-inputenc
  17775. (org-splice-latex-header
  17776. org-format-latex-header
  17777. org-latex-default-packages-alist
  17778. org-latex-packages-alist t
  17779. (plist-get info :latex-header)))
  17780. info)))
  17781. (defun org--get-display-dpi ()
  17782. "Get the DPI of the display.
  17783. Assumes that the display has the same pixel width in the
  17784. horizontal and vertical directions."
  17785. (if (display-graphic-p)
  17786. (round (/ (display-pixel-height)
  17787. (/ (display-mm-height) 25.4)))
  17788. (error "Attempt to calculate the dpi of a non-graphic display")))
  17789. (defun org-create-formula-image
  17790. (string tofile options buffer &optional processing-type)
  17791. "Create an image from LaTeX source using external processes.
  17792. The LaTeX STRING is saved to a temporary LaTeX file, then
  17793. converted to an image file by process PROCESSING-TYPE defined in
  17794. `org-preview-latex-process-alist'. A nil value defaults to
  17795. `org-preview-latex-default-process'.
  17796. The generated image file is eventually moved to TOFILE.
  17797. The OPTIONS argument controls the size, foreground color and
  17798. background color of the generated image.
  17799. When BUFFER non-nil, this function is used for LaTeX previewing.
  17800. Otherwise, it is used to deal with LaTeX snippets showed in
  17801. a HTML file."
  17802. (let* ((processing-type (or processing-type
  17803. org-preview-latex-default-process))
  17804. (processing-info
  17805. (cdr (assq processing-type org-preview-latex-process-alist)))
  17806. (programs (plist-get processing-info :programs))
  17807. (error-message (or (plist-get processing-info :message) ""))
  17808. (use-xcolor (plist-get processing-info :use-xcolor))
  17809. (image-input-type (plist-get processing-info :image-input-type))
  17810. (image-output-type (plist-get processing-info :image-output-type))
  17811. (post-clean (or (plist-get processing-info :post-clean)
  17812. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17813. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17814. (latex-header (or (plist-get processing-info :latex-header)
  17815. (org-create-formula--latex-header)))
  17816. (latex-compiler (plist-get processing-info :latex-compiler))
  17817. (image-converter (plist-get processing-info :image-converter))
  17818. (tmpdir temporary-file-directory)
  17819. (texfilebase (make-temp-name
  17820. (expand-file-name "orgtex" tmpdir)))
  17821. (texfile (concat texfilebase ".tex"))
  17822. (font-height (face-attribute 'default :height nil))
  17823. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17824. '(1.0 . 1.0)))
  17825. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17826. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17827. (dpi (* scale (floor (if buffer font-height 140.0))))
  17828. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17829. "Black"))
  17830. (bg (or (plist-get options (if buffer :background :html-background))
  17831. "Transparent"))
  17832. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17833. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17834. (dolist (program programs)
  17835. (org-check-external-command program error-message))
  17836. (if use-xcolor
  17837. (progn (if (eq fg 'default)
  17838. (setq fg (org-latex-color :foreground))
  17839. (setq fg (org-latex-color-format fg)))
  17840. (if (eq bg 'default)
  17841. (setq bg (org-latex-color :background))
  17842. (setq bg (org-latex-color-format
  17843. (if (string= bg "Transparent") "white" bg))))
  17844. (with-temp-file texfile
  17845. (insert latex-header)
  17846. (insert "\n\\begin{document}\n"
  17847. "\\definecolor{fg}{rgb}{" fg "}\n"
  17848. "\\definecolor{bg}{rgb}{" bg "}\n"
  17849. "\n\\pagecolor{bg}\n"
  17850. "\n{\\color{fg}\n"
  17851. string
  17852. "\n}\n"
  17853. "\n\\end{document}\n")))
  17854. (if (eq fg 'default)
  17855. (setq fg (org-dvipng-color :foreground))
  17856. (unless (string= fg "Transparent")
  17857. (setq fg (org-dvipng-color-format fg))))
  17858. (if (eq bg 'default)
  17859. (setq bg (org-dvipng-color :background))
  17860. (unless (string= bg "Transparent")
  17861. (setq bg (org-dvipng-color-format bg))))
  17862. (with-temp-file texfile
  17863. (insert latex-header)
  17864. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17865. (let* ((err-msg (format "Please adjust '%s' part of \
  17866. `org-preview-latex-process-alist'."
  17867. processing-type))
  17868. (image-input-file
  17869. (org-compile-file
  17870. texfile latex-compiler image-input-type err-msg log-buf))
  17871. (image-output-file
  17872. (org-compile-file
  17873. image-input-file image-converter image-output-type err-msg log-buf
  17874. `((?F . ,(shell-quote-argument fg))
  17875. (?B . ,(shell-quote-argument bg))
  17876. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17877. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17878. (copy-file image-output-file tofile 'replace)
  17879. (dolist (e post-clean)
  17880. (when (file-exists-p (concat texfilebase e))
  17881. (delete-file (concat texfilebase e))))
  17882. image-output-file)))
  17883. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17884. "Fill a LaTeX header template TPL.
  17885. In the template, the following place holders will be recognized:
  17886. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17887. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17888. [PACKAGES] \\usepackage statements for PKG
  17889. [NO-PACKAGES] do not include PKG
  17890. [EXTRA] the string EXTRA
  17891. [NO-EXTRA] do not include EXTRA
  17892. For backward compatibility, if both the positive and the negative place
  17893. holder is missing, the positive one (without the \"NO-\") will be
  17894. assumed to be present at the end of the template.
  17895. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17896. EXTRA is a string.
  17897. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17898. (let (rpl (end ""))
  17899. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17900. (setq rpl (if (or (match-end 1) (not def-pkg))
  17901. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17902. tpl (replace-match rpl t t tpl))
  17903. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17904. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17905. (setq rpl (if (or (match-end 1) (not pkg))
  17906. "" (org-latex-packages-to-string pkg snippets-p t))
  17907. tpl (replace-match rpl t t tpl))
  17908. (when pkg (setq end
  17909. (concat end "\n"
  17910. (org-latex-packages-to-string pkg snippets-p)))))
  17911. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17912. (setq rpl (if (or (match-end 1) (not extra))
  17913. "" (concat extra "\n"))
  17914. tpl (replace-match rpl t t tpl))
  17915. (when (and extra (string-match "\\S-" extra))
  17916. (setq end (concat end "\n" extra))))
  17917. (if (string-match "\\S-" end)
  17918. (concat tpl "\n" end)
  17919. tpl)))
  17920. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17921. "Turn an alist of packages into a string with the \\usepackage macros."
  17922. (setq pkg (mapconcat (lambda(p)
  17923. (cond
  17924. ((stringp p) p)
  17925. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17926. (format "%% Package %s omitted" (cadr p)))
  17927. ((equal "" (car p))
  17928. (format "\\usepackage{%s}" (cadr p)))
  17929. (t
  17930. (format "\\usepackage[%s]{%s}"
  17931. (car p) (cadr p)))))
  17932. pkg
  17933. "\n"))
  17934. (if newline (concat pkg "\n") pkg))
  17935. (defun org-dvipng-color (attr)
  17936. "Return a RGB color specification for dvipng."
  17937. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17938. (defun org-dvipng-color-format (color-name)
  17939. "Convert COLOR-NAME to a RGB color value for dvipng."
  17940. (apply #'format "rgb %s %s %s"
  17941. (mapcar 'org-normalize-color
  17942. (color-values color-name))))
  17943. (defun org-latex-color (attr)
  17944. "Return a RGB color for the LaTeX color package."
  17945. (org-latex-color-format (face-attribute 'default attr nil)))
  17946. (defun org-latex-color-format (color-name)
  17947. "Convert COLOR-NAME to a RGB color value."
  17948. (apply #'format "%s,%s,%s"
  17949. (mapcar 'org-normalize-color
  17950. (color-values color-name))))
  17951. (defun org-normalize-color (value)
  17952. "Return string to be used as color value for an RGB component."
  17953. (format "%g" (/ value 65535.0)))
  17954. ;; Image display
  17955. (defvar-local org-inline-image-overlays nil)
  17956. (defun org-toggle-inline-images (&optional include-linked)
  17957. "Toggle the display of inline images.
  17958. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17959. (interactive "P")
  17960. (if org-inline-image-overlays
  17961. (progn
  17962. (org-remove-inline-images)
  17963. (when (called-interactively-p 'interactive)
  17964. (message "Inline image display turned off")))
  17965. (org-display-inline-images include-linked)
  17966. (when (called-interactively-p 'interactive)
  17967. (message (if org-inline-image-overlays
  17968. (format "%d images displayed inline"
  17969. (length org-inline-image-overlays))
  17970. "No images to display inline")))))
  17971. (defun org-redisplay-inline-images ()
  17972. "Refresh the display of inline images."
  17973. (interactive)
  17974. (if (not org-inline-image-overlays)
  17975. (org-toggle-inline-images)
  17976. (org-toggle-inline-images)
  17977. (org-toggle-inline-images)))
  17978. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17979. "Display inline images.
  17980. An inline image is a link which follows either of these
  17981. conventions:
  17982. 1. Its path is a file with an extension matching return value
  17983. from `image-file-name-regexp' and it has no contents.
  17984. 2. Its description consists in a single link of the previous
  17985. type.
  17986. When optional argument INCLUDE-LINKED is non-nil, also links with
  17987. a text description part will be inlined. This can be nice for
  17988. a quick look at those images, but it does not reflect what
  17989. exported files will look like.
  17990. When optional argument REFRESH is non-nil, refresh existing
  17991. images between BEG and END. This will create new image displays
  17992. only if necessary. BEG and END default to the buffer
  17993. boundaries."
  17994. (interactive "P")
  17995. (when (display-graphic-p)
  17996. (unless refresh
  17997. (org-remove-inline-images)
  17998. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17999. (org-with-wide-buffer
  18000. (goto-char (or beg (point-min)))
  18001. (let ((case-fold-search t)
  18002. (file-extension-re (image-file-name-regexp)))
  18003. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  18004. (let ((link (save-match-data (org-element-context))))
  18005. ;; Check if we're at an inline image.
  18006. (when (and (equal (org-element-property :type link) "file")
  18007. (or include-linked
  18008. (not (org-element-property :contents-begin link)))
  18009. (let ((parent (org-element-property :parent link)))
  18010. (or (not (eq (org-element-type parent) 'link))
  18011. (not (cdr (org-element-contents parent)))))
  18012. (string-match-p file-extension-re
  18013. (org-element-property :path link)))
  18014. (let ((file (expand-file-name
  18015. (org-link-unescape
  18016. (org-element-property :path link)))))
  18017. (when (file-exists-p file)
  18018. (let ((width
  18019. ;; Apply `org-image-actual-width' specifications.
  18020. (cond
  18021. ((not (image-type-available-p 'imagemagick)) nil)
  18022. ((eq org-image-actual-width t) nil)
  18023. ((listp org-image-actual-width)
  18024. (or
  18025. ;; First try to find a width among
  18026. ;; attributes associated to the paragraph
  18027. ;; containing link.
  18028. (let ((paragraph
  18029. (let ((e link))
  18030. (while (and (setq e (org-element-property
  18031. :parent e))
  18032. (not (eq (org-element-type e)
  18033. 'paragraph))))
  18034. e)))
  18035. (when paragraph
  18036. (save-excursion
  18037. (goto-char (org-element-property :begin paragraph))
  18038. (when
  18039. (re-search-forward
  18040. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18041. (org-element-property
  18042. :post-affiliated paragraph)
  18043. t)
  18044. (string-to-number (match-string 1))))))
  18045. ;; Otherwise, fall-back to provided number.
  18046. (car org-image-actual-width)))
  18047. ((numberp org-image-actual-width)
  18048. org-image-actual-width)))
  18049. (old (get-char-property-and-overlay
  18050. (org-element-property :begin link)
  18051. 'org-image-overlay)))
  18052. (if (and (car-safe old) refresh)
  18053. (image-refresh (overlay-get (cdr old) 'display))
  18054. (let ((image (create-image file
  18055. (and width 'imagemagick)
  18056. nil
  18057. :width width)))
  18058. (when image
  18059. (let* ((link
  18060. ;; If inline image is the description
  18061. ;; of another link, be sure to
  18062. ;; consider the latter as the one to
  18063. ;; apply the overlay on.
  18064. (let ((parent
  18065. (org-element-property :parent link)))
  18066. (if (eq (org-element-type parent) 'link)
  18067. parent
  18068. link)))
  18069. (ov (make-overlay
  18070. (org-element-property :begin link)
  18071. (progn
  18072. (goto-char
  18073. (org-element-property :end link))
  18074. (skip-chars-backward " \t")
  18075. (point)))))
  18076. (overlay-put ov 'display image)
  18077. (overlay-put ov 'face 'default)
  18078. (overlay-put ov 'org-image-overlay t)
  18079. (overlay-put
  18080. ov 'modification-hooks
  18081. (list 'org-display-inline-remove-overlay))
  18082. (push ov org-inline-image-overlays)))))))))))))))
  18083. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18084. "Remove inline-display overlay if a corresponding region is modified."
  18085. (let ((inhibit-modification-hooks t))
  18086. (when (and ov after)
  18087. (delete ov org-inline-image-overlays)
  18088. (delete-overlay ov))))
  18089. (defun org-remove-inline-images ()
  18090. "Remove inline display of images."
  18091. (interactive)
  18092. (mapc #'delete-overlay org-inline-image-overlays)
  18093. (setq org-inline-image-overlays nil))
  18094. ;;;; Key bindings
  18095. ;; Outline functions from `outline-mode-prefix-map'
  18096. ;; that can be remapped in Org:
  18097. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18098. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18099. (define-key org-mode-map [remap outline-forward-same-level]
  18100. 'org-forward-heading-same-level)
  18101. (define-key org-mode-map [remap outline-backward-same-level]
  18102. 'org-backward-heading-same-level)
  18103. (define-key org-mode-map [remap outline-show-branches]
  18104. 'org-kill-note-or-show-branches)
  18105. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18106. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18107. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18108. (define-key org-mode-map [remap outline-next-visible-heading]
  18109. 'org-next-visible-heading)
  18110. (define-key org-mode-map [remap outline-previous-visible-heading]
  18111. 'org-previous-visible-heading)
  18112. (define-key org-mode-map [remap show-children] 'org-show-children)
  18113. ;; Outline functions from `outline-mode-prefix-map' that can not
  18114. ;; be remapped in Org:
  18115. ;; - the column "key binding" shows whether the Outline function is still
  18116. ;; available in Org mode on the same key that it has been bound to in
  18117. ;; Outline mode:
  18118. ;; - "overridden": key used for a different functionality in Org mode
  18119. ;; - else: key still bound to the same Outline function in Org mode
  18120. ;; | Outline function | key binding | Org replacement |
  18121. ;; |------------------------------------+-------------+--------------------------|
  18122. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18123. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18124. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18125. ;; | `show-entry' | overridden | no replacement |
  18126. ;; | `show-branches' | `C-c C-k' | still same function |
  18127. ;; | `show-subtree' | overridden | visibility cycling |
  18128. ;; | `show-all' | overridden | no replacement |
  18129. ;; | `hide-subtree' | overridden | visibility cycling |
  18130. ;; | `hide-body' | overridden | no replacement |
  18131. ;; | `hide-entry' | overridden | visibility cycling |
  18132. ;; | `hide-leaves' | overridden | no replacement |
  18133. ;; | `hide-sublevels' | overridden | no replacement |
  18134. ;; | `hide-other' | overridden | no replacement |
  18135. ;; Make `C-c C-x' a prefix key
  18136. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18137. ;; TAB key with modifiers
  18138. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18139. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18140. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18141. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18142. ;; The following line is necessary under Suse GNU/Linux
  18143. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18144. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18145. (define-key org-mode-map [backtab] 'org-shifttab)
  18146. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18147. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18148. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18149. ;; Cursor keys with modifiers
  18150. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18151. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18152. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18153. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18154. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18155. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18156. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18157. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18158. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18159. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18160. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18161. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18162. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18163. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18164. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18165. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18166. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18167. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18168. ;; Babel keys
  18169. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18170. (dolist (pair org-babel-key-bindings)
  18171. (define-key org-babel-map (car pair) (cdr pair)))
  18172. ;;; Extra keys for tty access.
  18173. ;; We only set them when really needed because otherwise the
  18174. ;; menus don't show the simple keys
  18175. (when (or org-use-extra-keys (not window-system))
  18176. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18177. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18178. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18179. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18180. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18181. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18182. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18183. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18184. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18185. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18186. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18187. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18188. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18189. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18190. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18191. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18192. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18193. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18194. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18195. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18196. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18197. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18198. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18199. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18200. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18201. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18202. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18203. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18204. ;; All the other keys
  18205. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18206. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18207. (if (boundp 'narrow-map)
  18208. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18209. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18210. (if (boundp 'narrow-map)
  18211. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18212. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18213. (if (boundp 'narrow-map)
  18214. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18215. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18216. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18217. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18218. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18219. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18220. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18221. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18222. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18223. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18224. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18225. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18226. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18227. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18228. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18229. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18230. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18231. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18232. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18233. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18234. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18235. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18236. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18237. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18238. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18239. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18240. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18241. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18242. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18243. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18244. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18245. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18246. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18247. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18248. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18249. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18250. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18251. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18252. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18253. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18254. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18255. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18256. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18257. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18258. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18259. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18260. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18261. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18262. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18263. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18264. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18265. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18266. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18267. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18268. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18269. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18270. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18271. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18272. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18273. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18274. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18275. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18276. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18277. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18278. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18279. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18280. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18281. (org-defkey org-mode-map "\C-m" 'org-return)
  18282. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18283. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18284. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18285. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18286. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18287. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18288. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18289. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18290. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18291. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18292. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18293. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18294. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18295. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18296. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18297. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18298. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18299. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18300. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18301. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18302. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18303. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18304. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18305. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18306. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18307. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18308. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18309. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18310. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18311. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18312. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18313. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18314. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18315. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18316. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18317. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18318. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18319. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18320. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18321. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18322. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18323. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18324. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18325. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18326. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18327. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18328. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18329. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18330. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18331. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18332. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18333. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18334. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18335. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18336. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18337. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18338. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18339. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18340. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18341. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18342. (defconst org-speed-commands-default
  18343. '(
  18344. ("Outline Navigation")
  18345. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18346. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18347. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18348. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18349. ("F" . org-next-block)
  18350. ("B" . org-previous-block)
  18351. ("u" . (org-speed-move-safe 'outline-up-heading))
  18352. ("j" . org-goto)
  18353. ("g" . (org-refile t))
  18354. ("Outline Visibility")
  18355. ("c" . org-cycle)
  18356. ("C" . org-shifttab)
  18357. (" " . org-display-outline-path)
  18358. ("s" . org-narrow-to-subtree)
  18359. ("=" . org-columns)
  18360. ("Outline Structure Editing")
  18361. ("U" . org-metaup)
  18362. ("D" . org-metadown)
  18363. ("r" . org-metaright)
  18364. ("l" . org-metaleft)
  18365. ("R" . org-shiftmetaright)
  18366. ("L" . org-shiftmetaleft)
  18367. ("i" . (progn (forward-char 1) (call-interactively
  18368. 'org-insert-heading-respect-content)))
  18369. ("^" . org-sort)
  18370. ("w" . org-refile)
  18371. ("a" . org-archive-subtree-default-with-confirmation)
  18372. ("@" . org-mark-subtree)
  18373. ("#" . org-toggle-comment)
  18374. ("Clock Commands")
  18375. ("I" . org-clock-in)
  18376. ("O" . org-clock-out)
  18377. ("Meta Data Editing")
  18378. ("t" . org-todo)
  18379. ("," . (org-priority))
  18380. ("0" . (org-priority ?\ ))
  18381. ("1" . (org-priority ?A))
  18382. ("2" . (org-priority ?B))
  18383. ("3" . (org-priority ?C))
  18384. (":" . org-set-tags-command)
  18385. ("e" . org-set-effort)
  18386. ("E" . org-inc-effort)
  18387. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18388. (org-entry-put (point) "APPT_WARNTIME" m)))
  18389. ("Agenda Views etc")
  18390. ("v" . org-agenda)
  18391. ("/" . org-sparse-tree)
  18392. ("Misc")
  18393. ("o" . org-open-at-point)
  18394. ("?" . org-speed-command-help)
  18395. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18396. (">" . (org-agenda-remove-restriction-lock))
  18397. )
  18398. "The default speed commands.")
  18399. (defun org-print-speed-command (e)
  18400. (if (> (length (car e)) 1)
  18401. (progn
  18402. (princ "\n")
  18403. (princ (car e))
  18404. (princ "\n")
  18405. (princ (make-string (length (car e)) ?-))
  18406. (princ "\n"))
  18407. (princ (car e))
  18408. (princ " ")
  18409. (if (symbolp (cdr e))
  18410. (princ (symbol-name (cdr e)))
  18411. (prin1 (cdr e)))
  18412. (princ "\n")))
  18413. (defun org-speed-command-help ()
  18414. "Show the available speed commands."
  18415. (interactive)
  18416. (if (not org-use-speed-commands)
  18417. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18418. (with-output-to-temp-buffer "*Help*"
  18419. (princ "User-defined Speed commands\n===========================\n")
  18420. (mapc #'org-print-speed-command org-speed-commands-user)
  18421. (princ "\n")
  18422. (princ "Built-in Speed commands\n=======================\n")
  18423. (mapc #'org-print-speed-command org-speed-commands-default))
  18424. (with-current-buffer "*Help*"
  18425. (setq truncate-lines t))))
  18426. (defun org-speed-move-safe (cmd)
  18427. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18428. If not, return to the original position and throw an error."
  18429. (interactive)
  18430. (let ((pos (point)))
  18431. (call-interactively cmd)
  18432. (unless (and (bolp) (org-at-heading-p))
  18433. (goto-char pos)
  18434. (error "Boundary reached while executing %s" cmd))))
  18435. (defvar org-self-insert-command-undo-counter 0)
  18436. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18437. (defvar org-speed-command nil)
  18438. (defun org-speed-command-activate (keys)
  18439. "Hook for activating single-letter speed commands.
  18440. `org-speed-commands-default' specifies a minimal command set.
  18441. Use `org-speed-commands-user' for further customization."
  18442. (when (or (and (bolp) (looking-at org-outline-regexp))
  18443. (and (functionp org-use-speed-commands)
  18444. (funcall org-use-speed-commands)))
  18445. (cdr (assoc keys (append org-speed-commands-user
  18446. org-speed-commands-default)))))
  18447. (defun org-babel-speed-command-activate (keys)
  18448. "Hook for activating single-letter code block commands."
  18449. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18450. (cdr (assoc keys org-babel-key-bindings))))
  18451. (defcustom org-speed-command-hook
  18452. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18453. "Hook for activating speed commands at strategic locations.
  18454. Hook functions are called in sequence until a valid handler is
  18455. found.
  18456. Each hook takes a single argument, a user-pressed command key
  18457. which is also a `self-insert-command' from the global map.
  18458. Within the hook, examine the cursor position and the command key
  18459. and return nil or a valid handler as appropriate. Handler could
  18460. be one of an interactive command, a function, or a form.
  18461. Set `org-use-speed-commands' to non-nil value to enable this
  18462. hook. The default setting is `org-speed-command-activate'."
  18463. :group 'org-structure
  18464. :version "24.1"
  18465. :type 'hook)
  18466. (defun org-self-insert-command (N)
  18467. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18468. If the cursor is in a table looking at whitespace, the whitespace is
  18469. overwritten, and the table is not marked as requiring realignment."
  18470. (interactive "p")
  18471. (org-check-before-invisible-edit 'insert)
  18472. (cond
  18473. ((and org-use-speed-commands
  18474. (let ((kv (this-command-keys-vector)))
  18475. (setq org-speed-command
  18476. (run-hook-with-args-until-success
  18477. 'org-speed-command-hook
  18478. (make-string 1 (aref kv (1- (length kv))))))))
  18479. (cond
  18480. ((commandp org-speed-command)
  18481. (setq this-command org-speed-command)
  18482. (call-interactively org-speed-command))
  18483. ((functionp org-speed-command)
  18484. (funcall org-speed-command))
  18485. ((and org-speed-command (listp org-speed-command))
  18486. (eval org-speed-command))
  18487. (t (let (org-use-speed-commands)
  18488. (call-interactively 'org-self-insert-command)))))
  18489. ((and
  18490. (org-at-table-p)
  18491. (progn
  18492. ;; Check if we blank the field, and if that triggers align.
  18493. (and (featurep 'org-table) org-table-auto-blank-field
  18494. (memq last-command
  18495. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18496. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18497. ;; Got extra space, this field does not determine
  18498. ;; column width.
  18499. (let (org-table-may-need-update) (org-table-blank-field))
  18500. ;; No extra space, this field may determine column
  18501. ;; width.
  18502. (org-table-blank-field)))
  18503. t)
  18504. (eq N 1)
  18505. (looking-at "[^|\n]* \\( \\)|"))
  18506. ;; There is room for insertion without re-aligning the table.
  18507. (delete-region (match-beginning 1) (match-end 1))
  18508. (self-insert-command N))
  18509. (t
  18510. (setq org-table-may-need-update t)
  18511. (self-insert-command N)
  18512. (org-fix-tags-on-the-fly)
  18513. (when org-self-insert-cluster-for-undo
  18514. (if (not (eq last-command 'org-self-insert-command))
  18515. (setq org-self-insert-command-undo-counter 1)
  18516. (if (>= org-self-insert-command-undo-counter 20)
  18517. (setq org-self-insert-command-undo-counter 1)
  18518. (and (> org-self-insert-command-undo-counter 0)
  18519. buffer-undo-list (listp buffer-undo-list)
  18520. (not (cadr buffer-undo-list)) ; remove nil entry
  18521. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18522. (setq org-self-insert-command-undo-counter
  18523. (1+ org-self-insert-command-undo-counter))))))))
  18524. (defun org-check-before-invisible-edit (kind)
  18525. "Check is editing if kind KIND would be dangerous with invisible text around.
  18526. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18527. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18528. (when (and org-catch-invisible-edits
  18529. (or (not (boundp 'visible-mode)) (not visible-mode))
  18530. (or (get-char-property (point) 'invisible)
  18531. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18532. ;; OK, we need to take a closer look
  18533. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18534. (invisible-before-point (unless (bobp) (get-char-property
  18535. (1- (point)) 'invisible)))
  18536. (border-and-ok-direction
  18537. (or
  18538. ;; Check if we are acting predictably before invisible text
  18539. (and invisible-at-point (not invisible-before-point)
  18540. (memq kind '(insert delete-backward)))
  18541. ;; Check if we are acting predictably after invisible text
  18542. ;; This works not well, and I have turned it off. It seems
  18543. ;; better to always show and stop after invisible text.
  18544. ;; (and (not invisible-at-point) invisible-before-point
  18545. ;; (memq kind '(insert delete)))
  18546. )))
  18547. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18548. (memq invisible-before-point '(outline org-hide-block t)))
  18549. (when (eq org-catch-invisible-edits 'error)
  18550. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18551. (if (and org-custom-properties-overlays
  18552. (y-or-n-p "Display invisible properties in this buffer? "))
  18553. (org-toggle-custom-properties-visibility)
  18554. ;; Make the area visible
  18555. (save-excursion
  18556. (when invisible-before-point
  18557. (goto-char (previous-single-char-property-change
  18558. (point) 'invisible)))
  18559. (outline-show-subtree))
  18560. (cond
  18561. ((eq org-catch-invisible-edits 'show)
  18562. ;; That's it, we do the edit after showing
  18563. (message
  18564. "Unfolding invisible region around point before editing")
  18565. (sit-for 1))
  18566. ((and (eq org-catch-invisible-edits 'smart)
  18567. border-and-ok-direction)
  18568. (message "Unfolding invisible region around point before editing"))
  18569. (t
  18570. ;; Don't do the edit, make the user repeat it in full visibility
  18571. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18572. (defun org-fix-tags-on-the-fly ()
  18573. "Align tags in headline at point.
  18574. Unlike to `org-set-tags', it ignores region and sorting."
  18575. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18576. (org-at-heading-p))
  18577. (let ((org-ignore-region t)
  18578. (org-tags-sort-function nil))
  18579. (org-set-tags nil t))))
  18580. (defun org-delete-backward-char (N)
  18581. "Like `delete-backward-char', insert whitespace at field end in tables.
  18582. When deleting backwards, in tables this function will insert whitespace in
  18583. front of the next \"|\" separator, to keep the table aligned. The table will
  18584. still be marked for re-alignment if the field did fill the entire column,
  18585. because, in this case the deletion might narrow the column."
  18586. (interactive "p")
  18587. (save-match-data
  18588. (org-check-before-invisible-edit 'delete-backward)
  18589. (if (and (org-at-table-p)
  18590. (eq N 1)
  18591. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18592. (looking-at ".*?|"))
  18593. (let ((pos (point))
  18594. (noalign (looking-at "[^|\n\r]* |"))
  18595. (c org-table-may-need-update))
  18596. (backward-delete-char N)
  18597. (unless overwrite-mode
  18598. (skip-chars-forward "^|")
  18599. (insert " ")
  18600. (goto-char (1- pos)))
  18601. ;; noalign: if there were two spaces at the end, this field
  18602. ;; does not determine the width of the column.
  18603. (when noalign (setq org-table-may-need-update c)))
  18604. (backward-delete-char N)
  18605. (org-fix-tags-on-the-fly))))
  18606. (defun org-delete-char (N)
  18607. "Like `delete-char', but insert whitespace at field end in tables.
  18608. When deleting characters, in tables this function will insert whitespace in
  18609. front of the next \"|\" separator, to keep the table aligned. The table will
  18610. still be marked for re-alignment if the field did fill the entire column,
  18611. because, in this case the deletion might narrow the column."
  18612. (interactive "p")
  18613. (save-match-data
  18614. (org-check-before-invisible-edit 'delete)
  18615. (if (and (org-at-table-p)
  18616. (not (bolp))
  18617. (not (= (char-after) ?|))
  18618. (eq N 1))
  18619. (if (looking-at ".*?|")
  18620. (let ((pos (point))
  18621. (noalign (looking-at "[^|\n\r]* |"))
  18622. (c org-table-may-need-update))
  18623. (replace-match
  18624. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18625. (goto-char pos)
  18626. ;; noalign: if there were two spaces at the end, this field
  18627. ;; does not determine the width of the column.
  18628. (when noalign (setq org-table-may-need-update c)))
  18629. (delete-char N))
  18630. (delete-char N)
  18631. (org-fix-tags-on-the-fly))))
  18632. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18633. (put 'org-self-insert-command 'delete-selection
  18634. (lambda ()
  18635. (not (run-hook-with-args-until-success
  18636. 'self-insert-uses-region-functions))))
  18637. (put 'orgtbl-self-insert-command 'delete-selection
  18638. (lambda ()
  18639. (not (run-hook-with-args-until-success
  18640. 'self-insert-uses-region-functions))))
  18641. (put 'org-delete-char 'delete-selection 'supersede)
  18642. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18643. (put 'org-yank 'delete-selection 'yank)
  18644. ;; Make `flyspell-mode' delay after some commands
  18645. (put 'org-self-insert-command 'flyspell-delayed t)
  18646. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18647. (put 'org-delete-char 'flyspell-delayed t)
  18648. (put 'org-delete-backward-char 'flyspell-delayed t)
  18649. ;; Make pabbrev-mode expand after Org mode commands
  18650. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18651. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18652. (defun org-remap (map &rest commands)
  18653. "In MAP, remap the functions given in COMMANDS.
  18654. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18655. (let (new old)
  18656. (while commands
  18657. (setq old (pop commands) new (pop commands))
  18658. (org-defkey map (vector 'remap old) new))))
  18659. (defun org-transpose-words ()
  18660. "Transpose words for Org.
  18661. This uses the `org-mode-transpose-word-syntax-table' syntax
  18662. table, which interprets characters in `org-emphasis-alist' as
  18663. word constituents."
  18664. (interactive)
  18665. (with-syntax-table org-mode-transpose-word-syntax-table
  18666. (call-interactively 'transpose-words)))
  18667. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18668. (when (eq org-enable-table-editor 'optimized)
  18669. ;; If the user wants maximum table support, we need to hijack
  18670. ;; some standard editing functions
  18671. (org-remap org-mode-map
  18672. 'self-insert-command 'org-self-insert-command
  18673. 'delete-char 'org-delete-char
  18674. 'delete-backward-char 'org-delete-backward-char)
  18675. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18676. (defvar org-ctrl-c-ctrl-c-hook nil
  18677. "Hook for functions attaching themselves to `C-c C-c'.
  18678. This can be used to add additional functionality to the C-c C-c
  18679. key which executes context-dependent commands. This hook is run
  18680. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18681. run after the last test.
  18682. Each function will be called with no arguments. The function
  18683. must check if the context is appropriate for it to act. If yes,
  18684. it should do its thing and then return a non-nil value. If the
  18685. context is wrong, just do nothing and return nil.")
  18686. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18687. "Hook for functions attaching themselves to `C-c C-c'.
  18688. This can be used to add additional functionality to the C-c C-c
  18689. key which executes context-dependent commands. This hook is run
  18690. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18691. before the first test.
  18692. Each function will be called with no arguments. The function
  18693. must check if the context is appropriate for it to act. If yes,
  18694. it should do its thing and then return a non-nil value. If the
  18695. context is wrong, just do nothing and return nil.")
  18696. (defvar org-tab-first-hook nil
  18697. "Hook for functions to attach themselves to TAB.
  18698. See `org-ctrl-c-ctrl-c-hook' for more information.
  18699. This hook runs as the first action when TAB is pressed, even before
  18700. `org-cycle' messes around with the `outline-regexp' to cater for
  18701. inline tasks and plain list item folding.
  18702. If any function in this hook returns t, any other actions that
  18703. would have been caused by TAB (such as table field motion or visibility
  18704. cycling) will not occur.")
  18705. (defvar org-tab-after-check-for-table-hook nil
  18706. "Hook for functions to attach themselves to TAB.
  18707. See `org-ctrl-c-ctrl-c-hook' for more information.
  18708. This hook runs after it has been established that the cursor is not in a
  18709. table, but before checking if the cursor is in a headline or if global cycling
  18710. should be done.
  18711. If any function in this hook returns t, not other actions like visibility
  18712. cycling will be done.")
  18713. (defvar org-tab-after-check-for-cycling-hook nil
  18714. "Hook for functions to attach themselves to TAB.
  18715. See `org-ctrl-c-ctrl-c-hook' for more information.
  18716. This hook runs after it has been established that not table field motion and
  18717. not visibility should be done because of current context. This is probably
  18718. the place where a package like yasnippets can hook in.")
  18719. (defvar org-tab-before-tab-emulation-hook nil
  18720. "Hook for functions to attach themselves to TAB.
  18721. See `org-ctrl-c-ctrl-c-hook' for more information.
  18722. This hook runs after every other options for TAB have been exhausted, but
  18723. before indentation and \t insertion takes place.")
  18724. (defvar org-metaleft-hook nil
  18725. "Hook for functions attaching themselves to `M-left'.
  18726. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18727. (defvar org-metaright-hook nil
  18728. "Hook for functions attaching themselves to `M-right'.
  18729. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18730. (defvar org-metaup-hook nil
  18731. "Hook for functions attaching themselves to `M-up'.
  18732. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18733. (defvar org-metadown-hook nil
  18734. "Hook for functions attaching themselves to `M-down'.
  18735. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18736. (defvar org-shiftmetaleft-hook nil
  18737. "Hook for functions attaching themselves to `M-S-left'.
  18738. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18739. (defvar org-shiftmetaright-hook nil
  18740. "Hook for functions attaching themselves to `M-S-right'.
  18741. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18742. (defvar org-shiftmetaup-hook nil
  18743. "Hook for functions attaching themselves to `M-S-up'.
  18744. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18745. (defvar org-shiftmetadown-hook nil
  18746. "Hook for functions attaching themselves to `M-S-down'.
  18747. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18748. (defvar org-metareturn-hook nil
  18749. "Hook for functions attaching themselves to `M-RET'.
  18750. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18751. (defvar org-shiftup-hook nil
  18752. "Hook for functions attaching themselves to `S-up'.
  18753. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18754. (defvar org-shiftup-final-hook nil
  18755. "Hook for functions attaching themselves to `S-up'.
  18756. This one runs after all other options except shift-select have been excluded.
  18757. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18758. (defvar org-shiftdown-hook nil
  18759. "Hook for functions attaching themselves to `S-down'.
  18760. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18761. (defvar org-shiftdown-final-hook nil
  18762. "Hook for functions attaching themselves to `S-down'.
  18763. This one runs after all other options except shift-select have been excluded.
  18764. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18765. (defvar org-shiftleft-hook nil
  18766. "Hook for functions attaching themselves to `S-left'.
  18767. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18768. (defvar org-shiftleft-final-hook nil
  18769. "Hook for functions attaching themselves to `S-left'.
  18770. This one runs after all other options except shift-select have been excluded.
  18771. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18772. (defvar org-shiftright-hook nil
  18773. "Hook for functions attaching themselves to `S-right'.
  18774. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18775. (defvar org-shiftright-final-hook nil
  18776. "Hook for functions attaching themselves to `S-right'.
  18777. This one runs after all other options except shift-select have been excluded.
  18778. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18779. (defun org-modifier-cursor-error ()
  18780. "Throw an error, a modified cursor command was applied in wrong context."
  18781. (user-error "This command is active in special context like tables, headlines or items"))
  18782. (defun org-shiftselect-error ()
  18783. "Throw an error because Shift-Cursor command was applied in wrong context."
  18784. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18785. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18786. (user-error "This command works only in special context like headlines or timestamps")))
  18787. (defun org-call-for-shift-select (cmd)
  18788. (let ((this-command-keys-shift-translated t))
  18789. (call-interactively cmd)))
  18790. (defun org-shifttab (&optional arg)
  18791. "Global visibility cycling or move to previous table field.
  18792. Call `org-table-previous-field' within a table.
  18793. When ARG is nil, cycle globally through visibility states.
  18794. When ARG is a numeric prefix, show contents of this level."
  18795. (interactive "P")
  18796. (cond
  18797. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18798. ((integerp arg)
  18799. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18800. (message "Content view to level: %d" arg)
  18801. (org-content (prefix-numeric-value arg2))
  18802. (org-cycle-show-empty-lines t)
  18803. (setq org-cycle-global-status 'overview)))
  18804. (t (call-interactively 'org-global-cycle))))
  18805. (defun org-shiftmetaleft ()
  18806. "Promote subtree or delete table column.
  18807. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18808. `org-table-delete-column', depending on context. See the
  18809. individual commands for more information."
  18810. (interactive)
  18811. (cond
  18812. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18813. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18814. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18815. ((if (not (org-region-active-p)) (org-at-item-p)
  18816. (save-excursion (goto-char (region-beginning))
  18817. (org-at-item-p)))
  18818. (call-interactively 'org-outdent-item-tree))
  18819. (t (org-modifier-cursor-error))))
  18820. (defun org-shiftmetaright ()
  18821. "Demote subtree or insert table column.
  18822. Calls `org-demote-subtree', `org-indent-item-tree', or
  18823. `org-table-insert-column', depending on context. See the
  18824. individual commands for more information."
  18825. (interactive)
  18826. (cond
  18827. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18828. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18829. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18830. ((if (not (org-region-active-p)) (org-at-item-p)
  18831. (save-excursion (goto-char (region-beginning))
  18832. (org-at-item-p)))
  18833. (call-interactively 'org-indent-item-tree))
  18834. (t (org-modifier-cursor-error))))
  18835. (defun org-shiftmetaup (&optional _arg)
  18836. "Drag the line at point up.
  18837. In a table, kill the current row.
  18838. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18839. but also adjust the previous clocked item in the clock history.
  18840. Everywhere else, drag the line at point up."
  18841. (interactive "P")
  18842. (cond
  18843. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18844. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18845. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18846. (call-interactively 'org-timestamp-up)))
  18847. (t (call-interactively 'org-drag-line-backward))))
  18848. (defun org-shiftmetadown (&optional _arg)
  18849. "Drag the line at point down.
  18850. In a table, insert an empty row at the current line.
  18851. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18852. but also adjust the previous clocked item in the clock history.
  18853. Everywhere else, drag the line at point down."
  18854. (interactive "P")
  18855. (cond
  18856. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18857. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18858. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18859. (call-interactively 'org-timestamp-down)))
  18860. (t (call-interactively 'org-drag-line-forward))))
  18861. (defsubst org-hidden-tree-error ()
  18862. (user-error
  18863. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18864. (defun org-metaleft (&optional _arg)
  18865. "Promote heading, list item at point or move table column left.
  18866. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18867. depending on context. With no specific context, calls the Emacs
  18868. default `backward-word'. See the individual commands for more
  18869. information.
  18870. This function runs the hook `org-metaleft-hook' as a first step,
  18871. and returns at first non-nil value."
  18872. (interactive "P")
  18873. (cond
  18874. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18875. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18876. ((org-with-limited-levels
  18877. (or (org-at-heading-p)
  18878. (and (org-region-active-p)
  18879. (save-excursion
  18880. (goto-char (region-beginning))
  18881. (org-at-heading-p)))))
  18882. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18883. (call-interactively 'org-do-promote))
  18884. ;; At an inline task.
  18885. ((org-at-heading-p)
  18886. (call-interactively 'org-inlinetask-promote))
  18887. ((or (org-at-item-p)
  18888. (and (org-region-active-p)
  18889. (save-excursion
  18890. (goto-char (region-beginning))
  18891. (org-at-item-p))))
  18892. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18893. (call-interactively 'org-outdent-item))
  18894. (t (call-interactively 'backward-word))))
  18895. (defun org-metaright (&optional _arg)
  18896. "Demote heading, list item at point or move table column right.
  18897. In front of a drawer or a block keyword, indent it correctly.
  18898. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18899. `org-indent-drawer' or `org-indent-block' depending on context.
  18900. With no specific context, calls the Emacs default `forward-word'.
  18901. See the individual commands for more information.
  18902. This function runs the hook `org-metaright-hook' as a first step,
  18903. and returns at first non-nil value."
  18904. (interactive "P")
  18905. (cond
  18906. ((run-hook-with-args-until-success 'org-metaright-hook))
  18907. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18908. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18909. ((org-at-block-p) (call-interactively 'org-indent-block))
  18910. ((org-with-limited-levels
  18911. (or (org-at-heading-p)
  18912. (and (org-region-active-p)
  18913. (save-excursion
  18914. (goto-char (region-beginning))
  18915. (org-at-heading-p)))))
  18916. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18917. (call-interactively 'org-do-demote))
  18918. ;; At an inline task.
  18919. ((org-at-heading-p)
  18920. (call-interactively 'org-inlinetask-demote))
  18921. ((or (org-at-item-p)
  18922. (and (org-region-active-p)
  18923. (save-excursion
  18924. (goto-char (region-beginning))
  18925. (org-at-item-p))))
  18926. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18927. (call-interactively 'org-indent-item))
  18928. (t (call-interactively 'forward-word))))
  18929. (defun org-check-for-hidden (what)
  18930. "Check if there are hidden headlines/items in the current visual line.
  18931. WHAT can be either `headlines' or `items'. If the current line is
  18932. an outline or item heading and it has a folded subtree below it,
  18933. this function returns t, nil otherwise."
  18934. (let ((re (cond
  18935. ((eq what 'headlines) org-outline-regexp-bol)
  18936. ((eq what 'items) (org-item-beginning-re))
  18937. (t (error "This should not happen"))))
  18938. beg end)
  18939. (save-excursion
  18940. (catch 'exit
  18941. (unless (org-region-active-p)
  18942. (setq beg (point-at-bol))
  18943. (beginning-of-line 2)
  18944. (while (and (not (eobp)) ;; this is like `next-line'
  18945. (get-char-property (1- (point)) 'invisible))
  18946. (beginning-of-line 2))
  18947. (setq end (point))
  18948. (goto-char beg)
  18949. (goto-char (point-at-eol))
  18950. (setq end (max end (point)))
  18951. (while (re-search-forward re end t)
  18952. (when (get-char-property (match-beginning 0) 'invisible)
  18953. (throw 'exit t))))
  18954. nil))))
  18955. (defun org-metaup (&optional _arg)
  18956. "Move subtree up or move table row up.
  18957. Calls `org-move-subtree-up' or `org-table-move-row' or
  18958. `org-move-item-up', depending on context. See the individual commands
  18959. for more information."
  18960. (interactive "P")
  18961. (cond
  18962. ((run-hook-with-args-until-success 'org-metaup-hook))
  18963. ((org-region-active-p)
  18964. (let* ((a (min (region-beginning) (region-end)))
  18965. (b (1- (max (region-beginning) (region-end))))
  18966. (c (save-excursion (goto-char a)
  18967. (move-beginning-of-line 0)))
  18968. (d (save-excursion (goto-char a)
  18969. (move-end-of-line 0) (point))))
  18970. (transpose-regions a b c d)
  18971. (goto-char c)))
  18972. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18973. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18974. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18975. (t (org-drag-element-backward))))
  18976. (defun org-metadown (&optional _arg)
  18977. "Move subtree down or move table row down.
  18978. Calls `org-move-subtree-down' or `org-table-move-row' or
  18979. `org-move-item-down', depending on context. See the individual
  18980. commands for more information."
  18981. (interactive "P")
  18982. (cond
  18983. ((run-hook-with-args-until-success 'org-metadown-hook))
  18984. ((org-region-active-p)
  18985. (let* ((a (min (region-beginning) (region-end)))
  18986. (b (max (region-beginning) (region-end)))
  18987. (c (save-excursion (goto-char b)
  18988. (move-beginning-of-line 1)))
  18989. (d (save-excursion (goto-char b)
  18990. (move-end-of-line 1) (1+ (point)))))
  18991. (transpose-regions a b c d)
  18992. (goto-char d)))
  18993. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18994. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18995. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18996. (t (org-drag-element-forward))))
  18997. (defun org-shiftup (&optional arg)
  18998. "Increase item in timestamp or increase priority of current headline.
  18999. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  19000. depending on context. See the individual commands for more information."
  19001. (interactive "P")
  19002. (cond
  19003. ((run-hook-with-args-until-success 'org-shiftup-hook))
  19004. ((and org-support-shift-select (org-region-active-p))
  19005. (org-call-for-shift-select 'previous-line))
  19006. ((org-at-timestamp-p t)
  19007. (call-interactively (if org-edit-timestamp-down-means-later
  19008. 'org-timestamp-down 'org-timestamp-up)))
  19009. ((and (not (eq org-support-shift-select 'always))
  19010. org-enable-priority-commands
  19011. (org-at-heading-p))
  19012. (call-interactively 'org-priority-up))
  19013. ((and (not org-support-shift-select) (org-at-item-p))
  19014. (call-interactively 'org-previous-item))
  19015. ((org-clocktable-try-shift 'up arg))
  19016. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  19017. (org-support-shift-select
  19018. (org-call-for-shift-select 'previous-line))
  19019. (t (org-shiftselect-error))))
  19020. (defun org-shiftdown (&optional arg)
  19021. "Decrease item in timestamp or decrease priority of current headline.
  19022. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  19023. depending on context. See the individual commands for more information."
  19024. (interactive "P")
  19025. (cond
  19026. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  19027. ((and org-support-shift-select (org-region-active-p))
  19028. (org-call-for-shift-select 'next-line))
  19029. ((org-at-timestamp-p t)
  19030. (call-interactively (if org-edit-timestamp-down-means-later
  19031. 'org-timestamp-up 'org-timestamp-down)))
  19032. ((and (not (eq org-support-shift-select 'always))
  19033. org-enable-priority-commands
  19034. (org-at-heading-p))
  19035. (call-interactively 'org-priority-down))
  19036. ((and (not org-support-shift-select) (org-at-item-p))
  19037. (call-interactively 'org-next-item))
  19038. ((org-clocktable-try-shift 'down arg))
  19039. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19040. (org-support-shift-select
  19041. (org-call-for-shift-select 'next-line))
  19042. (t (org-shiftselect-error))))
  19043. (defun org-shiftright (&optional arg)
  19044. "Cycle the thing at point or in the current line, depending on context.
  19045. Depending on context, this does one of the following:
  19046. - switch a timestamp at point one day into the future
  19047. - on a headline, switch to the next TODO keyword.
  19048. - on an item, switch entire list to the next bullet type
  19049. - on a property line, switch to the next allowed value
  19050. - on a clocktable definition line, move time block into the future"
  19051. (interactive "P")
  19052. (cond
  19053. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19054. ((and org-support-shift-select (org-region-active-p))
  19055. (org-call-for-shift-select 'forward-char))
  19056. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19057. ((and (not (eq org-support-shift-select 'always))
  19058. (org-at-heading-p))
  19059. (let ((org-inhibit-logging
  19060. (not org-treat-S-cursor-todo-selection-as-state-change))
  19061. (org-inhibit-blocking
  19062. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19063. (org-call-with-arg 'org-todo 'right)))
  19064. ((or (and org-support-shift-select
  19065. (not (eq org-support-shift-select 'always))
  19066. (org-at-item-bullet-p))
  19067. (and (not org-support-shift-select) (org-at-item-p)))
  19068. (org-call-with-arg 'org-cycle-list-bullet nil))
  19069. ((and (not (eq org-support-shift-select 'always))
  19070. (org-at-property-p))
  19071. (call-interactively 'org-property-next-allowed-value))
  19072. ((org-clocktable-try-shift 'right arg))
  19073. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19074. (org-support-shift-select
  19075. (org-call-for-shift-select 'forward-char))
  19076. (t (org-shiftselect-error))))
  19077. (defun org-shiftleft (&optional arg)
  19078. "Cycle the thing at point or in the current line, depending on context.
  19079. Depending on context, this does one of the following:
  19080. - switch a timestamp at point one day into the past
  19081. - on a headline, switch to the previous TODO keyword.
  19082. - on an item, switch entire list to the previous bullet type
  19083. - on a property line, switch to the previous allowed value
  19084. - on a clocktable definition line, move time block into the past"
  19085. (interactive "P")
  19086. (cond
  19087. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19088. ((and org-support-shift-select (org-region-active-p))
  19089. (org-call-for-shift-select 'backward-char))
  19090. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19091. ((and (not (eq org-support-shift-select 'always))
  19092. (org-at-heading-p))
  19093. (let ((org-inhibit-logging
  19094. (not org-treat-S-cursor-todo-selection-as-state-change))
  19095. (org-inhibit-blocking
  19096. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19097. (org-call-with-arg 'org-todo 'left)))
  19098. ((or (and org-support-shift-select
  19099. (not (eq org-support-shift-select 'always))
  19100. (org-at-item-bullet-p))
  19101. (and (not org-support-shift-select) (org-at-item-p)))
  19102. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19103. ((and (not (eq org-support-shift-select 'always))
  19104. (org-at-property-p))
  19105. (call-interactively 'org-property-previous-allowed-value))
  19106. ((org-clocktable-try-shift 'left arg))
  19107. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19108. (org-support-shift-select
  19109. (org-call-for-shift-select 'backward-char))
  19110. (t (org-shiftselect-error))))
  19111. (defun org-shiftcontrolright ()
  19112. "Switch to next TODO set."
  19113. (interactive)
  19114. (cond
  19115. ((and org-support-shift-select (org-region-active-p))
  19116. (org-call-for-shift-select 'forward-word))
  19117. ((and (not (eq org-support-shift-select 'always))
  19118. (org-at-heading-p))
  19119. (org-call-with-arg 'org-todo 'nextset))
  19120. (org-support-shift-select
  19121. (org-call-for-shift-select 'forward-word))
  19122. (t (org-shiftselect-error))))
  19123. (defun org-shiftcontrolleft ()
  19124. "Switch to previous TODO set."
  19125. (interactive)
  19126. (cond
  19127. ((and org-support-shift-select (org-region-active-p))
  19128. (org-call-for-shift-select 'backward-word))
  19129. ((and (not (eq org-support-shift-select 'always))
  19130. (org-at-heading-p))
  19131. (org-call-with-arg 'org-todo 'previousset))
  19132. (org-support-shift-select
  19133. (org-call-for-shift-select 'backward-word))
  19134. (t (org-shiftselect-error))))
  19135. (defun org-shiftcontrolup (&optional n)
  19136. "Change timestamps synchronously up in CLOCK log lines.
  19137. Optional argument N tells to change by that many units."
  19138. (interactive "P")
  19139. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19140. (let (org-support-shift-select)
  19141. (org-clock-timestamps-up n))
  19142. (user-error "Not at a clock log")))
  19143. (defun org-shiftcontroldown (&optional n)
  19144. "Change timestamps synchronously down in CLOCK log lines.
  19145. Optional argument N tells to change by that many units."
  19146. (interactive "P")
  19147. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19148. (let (org-support-shift-select)
  19149. (org-clock-timestamps-down n))
  19150. (user-error "Not at a clock log")))
  19151. (defun org-increase-number-at-point (&optional inc)
  19152. "Increment the number at point.
  19153. With an optional prefix numeric argument INC, increment using
  19154. this numeric value."
  19155. (interactive "p")
  19156. (if (not (number-at-point))
  19157. (user-error "Not on a number")
  19158. (unless inc (setq inc 1))
  19159. (let ((pos (point))
  19160. (beg (skip-chars-backward "-+^/*0-9eE."))
  19161. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19162. (setq nap (buffer-substring-no-properties
  19163. (+ pos beg) (+ pos beg end)))
  19164. (delete-region (+ pos beg) (+ pos beg end))
  19165. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19166. (when (org-at-table-p)
  19167. (org-table-align)
  19168. (org-table-end-of-field 1))))
  19169. (defun org-decrease-number-at-point (&optional inc)
  19170. "Decrement the number at point.
  19171. With an optional prefix numeric argument INC, decrement using
  19172. this numeric value."
  19173. (interactive "p")
  19174. (org-increase-number-at-point (- (or inc 1))))
  19175. (defun org-ctrl-c-ret ()
  19176. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19177. (interactive)
  19178. (cond
  19179. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19180. (t (call-interactively 'org-insert-heading))))
  19181. (defun org-find-visible ()
  19182. (let ((s (point)))
  19183. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19184. (get-char-property s 'invisible)))
  19185. s))
  19186. (defun org-find-invisible ()
  19187. (let ((s (point)))
  19188. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19189. (not (get-char-property s 'invisible))))
  19190. s))
  19191. (defun org-copy-visible (beg end)
  19192. "Copy the visible parts of the region."
  19193. (interactive "r")
  19194. (let (snippets s)
  19195. (save-excursion
  19196. (save-restriction
  19197. (narrow-to-region beg end)
  19198. (setq s (goto-char (point-min)))
  19199. (while (not (= (point) (point-max)))
  19200. (goto-char (org-find-invisible))
  19201. (push (buffer-substring s (point)) snippets)
  19202. (setq s (goto-char (org-find-visible))))))
  19203. (kill-new (apply 'concat (nreverse snippets)))))
  19204. (defun org-copy-special ()
  19205. "Copy region in table or copy current subtree.
  19206. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19207. context. See the individual commands for more information."
  19208. (interactive)
  19209. (call-interactively
  19210. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19211. (defun org-cut-special ()
  19212. "Cut region in table or cut current subtree.
  19213. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19214. context. See the individual commands for more information."
  19215. (interactive)
  19216. (call-interactively
  19217. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19218. (defun org-paste-special (arg)
  19219. "Paste rectangular region into table, or past subtree relative to level.
  19220. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19221. See the individual commands for more information."
  19222. (interactive "P")
  19223. (if (org-at-table-p)
  19224. (org-table-paste-rectangle)
  19225. (org-paste-subtree arg)))
  19226. (defun org-edit-special (&optional arg)
  19227. "Call a special editor for the element at point.
  19228. When at a table, call the formula editor with `org-table-edit-formulas'.
  19229. When in a source code block, call `org-edit-src-code'.
  19230. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19231. When in an export block, call `org-edit-export-block'.
  19232. When at an #+INCLUDE keyword, visit the included file.
  19233. When at a footnote reference, call `org-edit-footnote-reference'
  19234. On a link, call `ffap' to visit the link at point.
  19235. Otherwise, return a user error."
  19236. (interactive "P")
  19237. (let ((element (org-element-at-point)))
  19238. (barf-if-buffer-read-only)
  19239. (pcase (org-element-type element)
  19240. (`src-block
  19241. (if (not arg) (org-edit-src-code)
  19242. (let* ((info (org-babel-get-src-block-info))
  19243. (lang (nth 0 info))
  19244. (params (nth 2 info))
  19245. (session (cdr (assq :session params))))
  19246. (if (not session) (org-edit-src-code)
  19247. ;; At a src-block with a session and function called with
  19248. ;; an ARG: switch to the buffer related to the inferior
  19249. ;; process.
  19250. (switch-to-buffer
  19251. (funcall (intern (concat "org-babel-prep-session:" lang))
  19252. session params))))))
  19253. (`keyword
  19254. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19255. (org-open-link-from-string
  19256. (format "[[%s]]"
  19257. (expand-file-name
  19258. (let ((value (org-element-property :value element)))
  19259. (cond ((not (org-string-nw-p value))
  19260. (user-error "No file to edit"))
  19261. ((string-match "\\`\"\\(.*?\\)\"" value)
  19262. (match-string 1 value))
  19263. ((string-match "\\`[^ \t\"]\\S-*" value)
  19264. (match-string 0 value))
  19265. (t (user-error "No valid file specified")))))))
  19266. (user-error "No special environment to edit here")))
  19267. (`table
  19268. (if (eq (org-element-property :type element) 'table.el)
  19269. (org-edit-table.el)
  19270. (call-interactively 'org-table-edit-formulas)))
  19271. ;; Only Org tables contain `table-row' type elements.
  19272. (`table-row (call-interactively 'org-table-edit-formulas))
  19273. (`example-block (org-edit-src-code))
  19274. (`export-block (org-edit-export-block))
  19275. (`fixed-width (org-edit-fixed-width-region))
  19276. (_
  19277. ;; No notable element at point. Though, we may be at a link or
  19278. ;; a footnote reference, which are objects. Thus, scan deeper.
  19279. (let ((context (org-element-context element)))
  19280. (pcase (org-element-type context)
  19281. (`footnote-reference (org-edit-footnote-reference))
  19282. (`inline-src-block (org-edit-inline-src-code))
  19283. (`link (call-interactively #'ffap))
  19284. (_ (user-error "No special environment to edit here"))))))))
  19285. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19286. (defun org-ctrl-c-ctrl-c (&optional arg)
  19287. "Set tags in headline, or update according to changed information at point.
  19288. This command does many different things, depending on context:
  19289. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19290. this is what we do.
  19291. - If the cursor is on a statistics cookie, update it.
  19292. - If the cursor is in a headline, prompt for tags and insert them
  19293. into the current line, aligned to `org-tags-column'. When called
  19294. with prefix arg, realign all tags in the current buffer.
  19295. - If the cursor is in one of the special #+KEYWORD lines, this
  19296. triggers scanning the buffer for these lines and updating the
  19297. information.
  19298. - If the cursor is inside a table, realign the table. This command
  19299. works even if the automatic table editor has been turned off.
  19300. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19301. the entire table.
  19302. - If the cursor is at a footnote reference or definition, jump to
  19303. the corresponding definition or references, respectively.
  19304. - If the cursor is a the beginning of a dynamic block, update it.
  19305. - If the current buffer is a capture buffer, close note and file it.
  19306. - If the cursor is on a <<<target>>>, update radio targets and
  19307. corresponding links in this buffer.
  19308. - If the cursor is on a numbered item in a plain list, renumber the
  19309. ordered list.
  19310. - If the cursor is on a checkbox, toggle it.
  19311. - If the cursor is on a code block, evaluate it. The variable
  19312. `org-confirm-babel-evaluate' can be used to control prompting
  19313. before code block evaluation, by default every code block
  19314. evaluation requires confirmation. Code block evaluation can be
  19315. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19316. (interactive "P")
  19317. (cond
  19318. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19319. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19320. (org-remove-occur-highlights)
  19321. (message "Temporary highlights/overlays removed from current buffer"))
  19322. ((and (local-variable-p 'org-finish-function)
  19323. (fboundp org-finish-function))
  19324. (funcall org-finish-function))
  19325. ((org-babel-hash-at-point))
  19326. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19327. ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
  19328. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19329. (user-error
  19330. (substitute-command-keys
  19331. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19332. (t
  19333. (let* ((context
  19334. (org-element-lineage
  19335. (org-element-context)
  19336. ;; Limit to supported contexts.
  19337. '(babel-call clock dynamic-block footnote-definition
  19338. footnote-reference inline-babel-call inline-src-block
  19339. item keyword node-property paragraph plain-list
  19340. property-drawer radio-target src-block
  19341. statistics-cookie table table-cell table-row
  19342. timestamp)
  19343. t))
  19344. (type (org-element-type context)))
  19345. ;; For convenience: at the first line of a paragraph on the same
  19346. ;; line as an item, apply function on that item instead.
  19347. (when (eq type 'paragraph)
  19348. (let ((parent (org-element-property :parent context)))
  19349. (when (and (eq (org-element-type parent) 'item)
  19350. (= (line-beginning-position)
  19351. (org-element-property :begin parent)))
  19352. (setq context parent)
  19353. (setq type 'item))))
  19354. ;; Act according to type of element or object at point.
  19355. (pcase type
  19356. ((or `babel-call `inline-babel-call)
  19357. (let ((info (org-babel-lob-get-info context)))
  19358. (when info (org-babel-execute-src-block nil info))))
  19359. (`clock (org-clock-update-time-maybe))
  19360. (`dynamic-block
  19361. (save-excursion
  19362. (goto-char (org-element-property :post-affiliated context))
  19363. (org-update-dblock)))
  19364. (`footnote-definition
  19365. (goto-char (org-element-property :post-affiliated context))
  19366. (call-interactively 'org-footnote-action))
  19367. (`footnote-reference (call-interactively #'org-footnote-action))
  19368. ((or `headline `inlinetask)
  19369. (save-excursion (goto-char (org-element-property :begin context))
  19370. (call-interactively #'org-set-tags)))
  19371. ((or `inline-src-block `src-block)
  19372. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19373. (org-babel-eval-wipe-error-buffer)
  19374. (org-babel-execute-src-block
  19375. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19376. (`item
  19377. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19378. ;; unconditionally, whereas `C-u' will toggle its presence.
  19379. ;; Without a universal argument, if the item has a checkbox,
  19380. ;; toggle it. Otherwise repair the list.
  19381. (let* ((box (org-element-property :checkbox context))
  19382. (struct (org-element-property :structure context))
  19383. (old-struct (copy-tree struct))
  19384. (parents (org-list-parents-alist struct))
  19385. (prevs (org-list-prevs-alist struct))
  19386. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19387. (org-list-set-checkbox
  19388. (org-element-property :begin context) struct
  19389. (cond ((equal arg '(16)) "[-]")
  19390. ((and (not box) (equal arg '(4))) "[ ]")
  19391. ((or (not box) (equal arg '(4))) nil)
  19392. ((eq box 'on) "[ ]")
  19393. (t "[X]")))
  19394. ;; Mimic `org-list-write-struct' but with grabbing a return
  19395. ;; value from `org-list-struct-fix-box'.
  19396. (org-list-struct-fix-ind struct parents 2)
  19397. (org-list-struct-fix-item-end struct)
  19398. (org-list-struct-fix-bul struct prevs)
  19399. (org-list-struct-fix-ind struct parents)
  19400. (let ((block-item
  19401. (org-list-struct-fix-box struct parents prevs orderedp)))
  19402. (if (and box (equal struct old-struct))
  19403. (if (equal arg '(16))
  19404. (message "Checkboxes already reset")
  19405. (user-error "Cannot toggle this checkbox: %s"
  19406. (if (eq box 'on)
  19407. "all subitems checked"
  19408. "unchecked subitems")))
  19409. (org-list-struct-apply-struct struct old-struct)
  19410. (org-update-checkbox-count-maybe))
  19411. (when block-item
  19412. (message "Checkboxes were removed due to empty box at line %d"
  19413. (org-current-line block-item))))))
  19414. (`keyword
  19415. (let ((org-inhibit-startup-visibility-stuff t)
  19416. (org-startup-align-all-tables nil))
  19417. (when (boundp 'org-table-coordinate-overlays)
  19418. (mapc #'delete-overlay org-table-coordinate-overlays)
  19419. (setq org-table-coordinate-overlays nil))
  19420. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19421. (message "Local setup has been refreshed"))
  19422. (`plain-list
  19423. ;; At a plain list, with a double C-u argument, set
  19424. ;; checkboxes of each item to "[-]", whereas a single one
  19425. ;; will toggle their presence according to the state of the
  19426. ;; first item in the list. Without an argument, repair the
  19427. ;; list.
  19428. (let* ((begin (org-element-property :contents-begin context))
  19429. (beginm (move-marker (make-marker) begin))
  19430. (struct (org-element-property :structure context))
  19431. (old-struct (copy-tree struct))
  19432. (first-box (save-excursion
  19433. (goto-char begin)
  19434. (looking-at org-list-full-item-re)
  19435. (match-string-no-properties 3)))
  19436. (new-box (cond ((equal arg '(16)) "[-]")
  19437. ((equal arg '(4)) (unless first-box "[ ]"))
  19438. ((equal first-box "[X]") "[ ]")
  19439. (t "[X]"))))
  19440. (cond
  19441. (arg
  19442. (dolist (pos
  19443. (org-list-get-all-items
  19444. begin struct (org-list-prevs-alist struct)))
  19445. (org-list-set-checkbox pos struct new-box)))
  19446. ((and first-box (eq (point) begin))
  19447. ;; For convenience, when point is at bol on the first
  19448. ;; item of the list and no argument is provided, simply
  19449. ;; toggle checkbox of that item, if any.
  19450. (org-list-set-checkbox begin struct new-box)))
  19451. (org-list-write-struct
  19452. struct (org-list-parents-alist struct) old-struct)
  19453. (org-update-checkbox-count-maybe)
  19454. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19455. ((or `property-drawer `node-property)
  19456. (call-interactively #'org-property-action))
  19457. (`radio-target
  19458. (call-interactively #'org-update-radio-target-regexp))
  19459. (`statistics-cookie
  19460. (call-interactively #'org-update-statistics-cookies))
  19461. ((or `table `table-cell `table-row)
  19462. ;; At a table, recalculate every field and align it. Also
  19463. ;; send the table if necessary. If the table has
  19464. ;; a `table.el' type, just give up. At a table row or cell,
  19465. ;; maybe recalculate line but always align table.
  19466. (if (eq (org-element-property :type context) 'table.el)
  19467. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19468. Use `\\[org-edit-special]' to edit table.el tables"))
  19469. (let ((org-enable-table-editor t))
  19470. (if (or (eq type 'table)
  19471. ;; Check if point is at a TBLFM line.
  19472. (and (eq type 'table-row)
  19473. (= (point) (org-element-property :end context))))
  19474. (save-excursion
  19475. (if (org-at-TBLFM-p)
  19476. (progn (require 'org-table)
  19477. (org-table-calc-current-TBLFM))
  19478. (goto-char (org-element-property :contents-begin context))
  19479. (org-call-with-arg 'org-table-recalculate (or arg t))
  19480. (orgtbl-send-table 'maybe)))
  19481. (org-table-maybe-eval-formula)
  19482. (cond (arg (call-interactively #'org-table-recalculate))
  19483. ((org-table-maybe-recalculate-line))
  19484. (t (org-table-align)))))))
  19485. (`timestamp (org-timestamp-change 0 'day))
  19486. ((and `nil (guard (org-at-heading-p)))
  19487. ;; When point is on an unsupported object type, we can miss
  19488. ;; the fact that it also is at a heading. Handle it here.
  19489. (call-interactively #'org-set-tags))
  19490. ((guard
  19491. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19492. (_
  19493. (user-error
  19494. (substitute-command-keys
  19495. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19496. (defun org-mode-restart ()
  19497. (interactive)
  19498. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19499. (funcall major-mode)
  19500. (hack-local-variables)
  19501. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19502. (org-indent-mode -1)))
  19503. (message "%s restarted" major-mode))
  19504. (defun org-kill-note-or-show-branches ()
  19505. "Abort storing current note, or call `outline-show-branches'."
  19506. (interactive)
  19507. (if (not org-finish-function)
  19508. (progn
  19509. (outline-hide-subtree)
  19510. (call-interactively 'outline-show-branches))
  19511. (let ((org-note-abort t))
  19512. (funcall org-finish-function))))
  19513. (defun org-delete-indentation (&optional arg)
  19514. "Join current line to previous and fix whitespace at join.
  19515. If previous line is a headline add to headline title. Otherwise
  19516. the function calls `delete-indentation'.
  19517. With a non-nil optional argument, join it to the following one."
  19518. (interactive "*P")
  19519. (if (save-excursion
  19520. (beginning-of-line (if arg 1 0))
  19521. (let ((case-fold-search nil))
  19522. (looking-at org-complex-heading-regexp)))
  19523. ;; At headline.
  19524. (let ((tags-column (when (match-beginning 5)
  19525. (save-excursion (goto-char (match-beginning 5))
  19526. (current-column))))
  19527. (string (concat " " (progn (when arg (forward-line 1))
  19528. (org-trim (delete-and-extract-region
  19529. (line-beginning-position)
  19530. (line-end-position)))))))
  19531. (unless (bobp) (delete-region (point) (1- (point))))
  19532. (goto-char (or (match-end 4)
  19533. (match-beginning 5)
  19534. (match-end 0)))
  19535. (skip-chars-backward " \t")
  19536. (save-excursion (insert string))
  19537. ;; Adjust alignment of tags.
  19538. (cond
  19539. ((not tags-column)) ;no tags
  19540. (org-auto-align-tags (org-set-tags nil t))
  19541. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19542. (delete-indentation arg)))
  19543. (defun org-open-line (n)
  19544. "Insert a new row in tables, call `open-line' elsewhere.
  19545. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19546. As a special case, when a document starts with a table, allow to
  19547. call `open-line' on the very first character."
  19548. (interactive "*p")
  19549. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19550. (org-table-insert-row)
  19551. (open-line n)))
  19552. (defun org-return (&optional indent)
  19553. "Goto next table row or insert a newline.
  19554. Calls `org-table-next-row' or `newline', depending on context.
  19555. When optional INDENT argument is non-nil, call
  19556. `newline-and-indent' instead of `newline'.
  19557. When `org-return-follows-link' is non-nil and point is on
  19558. a timestamp or a link, call `org-open-at-point'. However, it
  19559. will not happen if point is in a table or on a \"dead\"
  19560. object (e.g., within a comment). In these case, you need to use
  19561. `org-open-at-point' directly."
  19562. (interactive)
  19563. (let ((context (if org-return-follows-link (org-element-context)
  19564. (org-element-at-point))))
  19565. (cond
  19566. ;; In a table, call `org-table-next-row'.
  19567. ((or (and (eq (org-element-type context) 'table)
  19568. (>= (point) (org-element-property :contents-begin context))
  19569. (< (point) (org-element-property :contents-end context)))
  19570. (org-element-lineage context '(table-row table-cell) t))
  19571. (org-table-justify-field-maybe)
  19572. (call-interactively #'org-table-next-row))
  19573. ;; On a link or a timestamp, call `org-open-at-point' if
  19574. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19575. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19576. ((and org-return-follows-link
  19577. (or (org-in-regexp org-ts-regexp-both nil t)
  19578. (org-in-regexp org-tsr-regexp-both nil t)
  19579. (org-in-regexp org-any-link-re nil t)))
  19580. (call-interactively #'org-open-at-point))
  19581. ;; Insert newline in heading, but preserve tags.
  19582. ((and (not (bolp))
  19583. (save-excursion (beginning-of-line)
  19584. (let ((case-fold-search nil))
  19585. (looking-at org-complex-heading-regexp))))
  19586. ;; At headline. Split line. However, if point is on keyword,
  19587. ;; priority cookie or tags, do not break any of them: add
  19588. ;; a newline after the headline instead.
  19589. (let ((tags-column (and (match-beginning 5)
  19590. (save-excursion (goto-char (match-beginning 5))
  19591. (current-column))))
  19592. (string
  19593. (when (and (match-end 4) (org-point-in-group (point) 4))
  19594. (delete-and-extract-region (point) (match-end 4)))))
  19595. ;; Adjust tag alignment.
  19596. (cond
  19597. ((not (and tags-column string)))
  19598. (org-auto-align-tags (org-set-tags nil t))
  19599. (t (org--align-tags-here tags-column))) ;preserve tags column
  19600. (end-of-line)
  19601. (org-show-entry)
  19602. (if indent (newline-and-indent) (newline))
  19603. (when string (save-excursion (insert (org-trim string))))))
  19604. ;; In a list, make sure indenting keeps trailing text within.
  19605. ((and indent
  19606. (not (eolp))
  19607. (org-element-lineage context '(item)))
  19608. (let ((trailing-data
  19609. (delete-and-extract-region (point) (line-end-position))))
  19610. (newline-and-indent)
  19611. (save-excursion (insert trailing-data))))
  19612. (t (if indent (newline-and-indent) (newline))))))
  19613. (defun org-return-indent ()
  19614. "Goto next table row or insert a newline and indent.
  19615. Calls `org-table-next-row' or `newline-and-indent', depending on
  19616. context. See the individual commands for more information."
  19617. (interactive)
  19618. (org-return t))
  19619. (defun org-ctrl-c-star ()
  19620. "Compute table, or change heading status of lines.
  19621. Calls `org-table-recalculate' or `org-toggle-heading',
  19622. depending on context."
  19623. (interactive)
  19624. (cond
  19625. ((org-at-table-p)
  19626. (call-interactively 'org-table-recalculate))
  19627. (t
  19628. ;; Convert all lines in region to list items
  19629. (call-interactively 'org-toggle-heading))))
  19630. (defun org-ctrl-c-minus ()
  19631. "Insert separator line in table or modify bullet status of line.
  19632. Also turns a plain line or a region of lines into list items.
  19633. Calls `org-table-insert-hline', `org-toggle-item', or
  19634. `org-cycle-list-bullet', depending on context."
  19635. (interactive)
  19636. (cond
  19637. ((org-at-table-p)
  19638. (call-interactively 'org-table-insert-hline))
  19639. ((org-region-active-p)
  19640. (call-interactively 'org-toggle-item))
  19641. ((org-in-item-p)
  19642. (call-interactively 'org-cycle-list-bullet))
  19643. (t
  19644. (call-interactively 'org-toggle-item))))
  19645. (defun org-toggle-heading (&optional nstars)
  19646. "Convert headings to normal text, or items or text to headings.
  19647. If there is no active region, only convert the current line.
  19648. With a `\\[universal-argument]' prefix, convert the whole list at
  19649. point into heading.
  19650. In a region:
  19651. - If the first non blank line is a headline, remove the stars
  19652. from all headlines in the region.
  19653. - If it is a normal line, turn each and every normal line (i.e.,
  19654. not an heading or an item) in the region into headings. If you
  19655. want to convert only the first line of this region, use one
  19656. universal prefix argument.
  19657. - If it is a plain list item, turn all plain list items into headings.
  19658. When converting a line into a heading, the number of stars is chosen
  19659. such that the lines become children of the current entry. However,
  19660. when a numeric prefix argument is given, its value determines the
  19661. number of stars to add."
  19662. (interactive "P")
  19663. (let ((skip-blanks
  19664. (function
  19665. ;; Return beginning of first non-blank line, starting from
  19666. ;; line at POS.
  19667. (lambda (pos)
  19668. (save-excursion
  19669. (goto-char pos)
  19670. (while (org-at-comment-p) (forward-line))
  19671. (skip-chars-forward " \r\t\n")
  19672. (point-at-bol)))))
  19673. beg end toggled)
  19674. ;; Determine boundaries of changes. If a universal prefix has
  19675. ;; been given, put the list in a region. If region ends at a bol,
  19676. ;; do not consider the last line to be in the region.
  19677. (when (and current-prefix-arg (org-at-item-p))
  19678. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19679. (org-mark-element))
  19680. (if (org-region-active-p)
  19681. (setq beg (funcall skip-blanks (region-beginning))
  19682. end (copy-marker (save-excursion
  19683. (goto-char (region-end))
  19684. (if (bolp) (point) (point-at-eol)))))
  19685. (setq beg (funcall skip-blanks (point-at-bol))
  19686. end (copy-marker (point-at-eol))))
  19687. ;; Ensure inline tasks don't count as headings.
  19688. (org-with-limited-levels
  19689. (save-excursion
  19690. (goto-char beg)
  19691. (cond
  19692. ;; Case 1. Started at an heading: de-star headings.
  19693. ((org-at-heading-p)
  19694. (while (< (point) end)
  19695. (when (org-at-heading-p t)
  19696. (looking-at org-outline-regexp) (replace-match "")
  19697. (setq toggled t))
  19698. (forward-line)))
  19699. ;; Case 2. Started at an item: change items into headlines.
  19700. ;; One star will be added by `org-list-to-subtree'.
  19701. ((org-at-item-p)
  19702. (while (< (point) end)
  19703. (when (org-at-item-p)
  19704. ;; Pay attention to cases when region ends before list.
  19705. (let* ((struct (org-list-struct))
  19706. (list-end
  19707. (min (org-list-get-bottom-point struct) (1+ end))))
  19708. (save-restriction
  19709. (narrow-to-region (point) list-end)
  19710. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19711. (setq toggled t))
  19712. (forward-line)))
  19713. ;; Case 3. Started at normal text: make every line an heading,
  19714. ;; skipping headlines and items.
  19715. (t (let* ((stars
  19716. (make-string
  19717. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19718. (add-stars
  19719. (cond (nstars "") ; stars from prefix only
  19720. ((equal stars "") "*") ; before first heading
  19721. (org-odd-levels-only "**") ; inside heading, odd
  19722. (t "*"))) ; inside heading, oddeven
  19723. (rpl (concat stars add-stars " "))
  19724. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19725. (while (< (point) (if (equal nstars '(4)) lend end))
  19726. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19727. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19728. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19729. (forward-line)))))))
  19730. (unless toggled (message "Cannot toggle heading from here"))))
  19731. (defun org-meta-return (&optional _arg)
  19732. "Insert a new heading or wrap a region in a table.
  19733. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19734. on context. See the individual commands for more information."
  19735. (interactive)
  19736. (org-check-before-invisible-edit 'insert)
  19737. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19738. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19739. #'org-insert-heading))))
  19740. ;;; Menu entries
  19741. (defsubst org-in-subtree-not-table-p ()
  19742. "Are we in a subtree and not in a table?"
  19743. (and (not (org-before-first-heading-p))
  19744. (not (org-at-table-p))))
  19745. ;; Define the Org mode menus
  19746. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19747. '("Tbl"
  19748. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19749. ["Next Field" org-cycle (org-at-table-p)]
  19750. ["Previous Field" org-shifttab (org-at-table-p)]
  19751. ["Next Row" org-return (org-at-table-p)]
  19752. "--"
  19753. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19754. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19755. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19756. "--"
  19757. ("Column"
  19758. ["Move Column Left" org-metaleft (org-at-table-p)]
  19759. ["Move Column Right" org-metaright (org-at-table-p)]
  19760. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19761. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19762. ("Row"
  19763. ["Move Row Up" org-metaup (org-at-table-p)]
  19764. ["Move Row Down" org-metadown (org-at-table-p)]
  19765. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19766. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19767. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19768. "--"
  19769. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19770. ("Rectangle"
  19771. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19772. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19773. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19774. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19775. "--"
  19776. ("Calculate"
  19777. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19778. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19779. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19780. "--"
  19781. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19782. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19783. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19784. "--"
  19785. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19786. "--"
  19787. ["Sum Column/Rectangle" org-table-sum
  19788. (or (org-at-table-p) (org-region-active-p))]
  19789. ["Which Column?" org-table-current-column (org-at-table-p)])
  19790. ["Debug Formulas"
  19791. org-table-toggle-formula-debugger
  19792. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19793. ["Show Col/Row Numbers"
  19794. org-table-toggle-coordinate-overlays
  19795. :style toggle
  19796. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19797. "--"
  19798. ["Create" org-table-create (and (not (org-at-table-p))
  19799. org-enable-table-editor)]
  19800. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19801. ["Import from File" org-table-import (not (org-at-table-p))]
  19802. ["Export to File" org-table-export (org-at-table-p)]
  19803. "--"
  19804. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19805. "--"
  19806. ("Plot"
  19807. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19808. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19809. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19810. '("Org"
  19811. ("Show/Hide"
  19812. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19813. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19814. ["Sparse Tree..." org-sparse-tree t]
  19815. ["Reveal Context" org-reveal t]
  19816. ["Show All" outline-show-all t]
  19817. "--"
  19818. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19819. "--"
  19820. ["New Heading" org-insert-heading t]
  19821. ("Navigate Headings"
  19822. ["Up" outline-up-heading t]
  19823. ["Next" outline-next-visible-heading t]
  19824. ["Previous" outline-previous-visible-heading t]
  19825. ["Next Same Level" outline-forward-same-level t]
  19826. ["Previous Same Level" outline-backward-same-level t]
  19827. "--"
  19828. ["Jump" org-goto t])
  19829. ("Edit Structure"
  19830. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19831. "--"
  19832. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19833. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19834. "--"
  19835. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19836. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19837. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19838. "--"
  19839. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19840. "--"
  19841. ["Copy visible text" org-copy-visible t]
  19842. "--"
  19843. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19844. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19845. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19846. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19847. "--"
  19848. ["Sort Region/Children" org-sort t]
  19849. "--"
  19850. ["Convert to odd levels" org-convert-to-odd-levels t]
  19851. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19852. ("Editing"
  19853. ["Emphasis..." org-emphasize t]
  19854. ["Edit Source Example" org-edit-special t]
  19855. "--"
  19856. ["Footnote new/jump" org-footnote-action t]
  19857. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19858. ("Archive"
  19859. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19860. "--"
  19861. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19862. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19863. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19864. )
  19865. "--"
  19866. ("Hyperlinks"
  19867. ["Store Link (Global)" org-store-link t]
  19868. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19869. ["Insert Link" org-insert-link t]
  19870. ["Follow Link" org-open-at-point t]
  19871. "--"
  19872. ["Next link" org-next-link t]
  19873. ["Previous link" org-previous-link t]
  19874. "--"
  19875. ["Descriptive Links"
  19876. org-toggle-link-display
  19877. :style radio
  19878. :selected org-descriptive-links
  19879. ]
  19880. ["Literal Links"
  19881. org-toggle-link-display
  19882. :style radio
  19883. :selected (not org-descriptive-links)])
  19884. "--"
  19885. ("TODO Lists"
  19886. ["TODO/DONE/-" org-todo t]
  19887. ("Select keyword"
  19888. ["Next keyword" org-shiftright (org-at-heading-p)]
  19889. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19890. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19891. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19892. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19893. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19894. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19895. "--"
  19896. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19897. :selected org-enforce-todo-dependencies :style toggle :active t]
  19898. "Settings for tree at point"
  19899. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19900. :selected (org-entry-get nil "ORDERED")
  19901. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19902. ["Do Children parallel" org-toggle-ordered-property :style radio
  19903. :selected (not (org-entry-get nil "ORDERED"))
  19904. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19905. "--"
  19906. ["Set Priority" org-priority t]
  19907. ["Priority Up" org-shiftup t]
  19908. ["Priority Down" org-shiftdown t]
  19909. "--"
  19910. ["Get news from all feeds" org-feed-update-all t]
  19911. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19912. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19913. ("TAGS and Properties"
  19914. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19915. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19916. "--"
  19917. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19918. ["Column view of properties" org-columns t]
  19919. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19920. ("Dates and Scheduling"
  19921. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19922. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19923. ("Change Date"
  19924. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19925. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19926. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19927. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19928. ["Compute Time Range" org-evaluate-time-range t]
  19929. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19930. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19931. "--"
  19932. ["Custom time format" org-toggle-time-stamp-overlays
  19933. :style radio :selected org-display-custom-times]
  19934. "--"
  19935. ["Goto Calendar" org-goto-calendar t]
  19936. ["Date from Calendar" org-date-from-calendar t]
  19937. "--"
  19938. ["Start/Restart Timer" org-timer-start t]
  19939. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19940. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19941. ["Insert Timer String" org-timer t]
  19942. ["Insert Timer Item" org-timer-item t])
  19943. ("Logging work"
  19944. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19945. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19946. ["Clock out" org-clock-out t]
  19947. ["Clock cancel" org-clock-cancel t]
  19948. "--"
  19949. ["Mark as default task" org-clock-mark-default-task t]
  19950. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19951. ["Goto running clock" org-clock-goto t]
  19952. "--"
  19953. ["Display times" org-clock-display t]
  19954. ["Create clock table" org-clock-report t]
  19955. "--"
  19956. ["Record DONE time"
  19957. (progn (setq org-log-done (not org-log-done))
  19958. (message "Switching to %s will %s record a timestamp"
  19959. (car org-done-keywords)
  19960. (if org-log-done "automatically" "not")))
  19961. :style toggle :selected org-log-done])
  19962. "--"
  19963. ["Agenda Command..." org-agenda t]
  19964. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19965. ("File List for Agenda")
  19966. ("Special views current file"
  19967. ["TODO Tree" org-show-todo-tree t]
  19968. ["Check Deadlines" org-check-deadlines t]
  19969. ["Timeline" org-timeline t]
  19970. ["Tags/Property tree" org-match-sparse-tree t])
  19971. "--"
  19972. ["Export/Publish..." org-export-dispatch t]
  19973. ("LaTeX"
  19974. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19975. :selected org-cdlatex-mode]
  19976. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19977. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19978. ["Modify math symbol" org-cdlatex-math-modify
  19979. (org-inside-LaTeX-fragment-p)]
  19980. ["Insert citation" org-reftex-citation t])
  19981. "--"
  19982. ("MobileOrg"
  19983. ["Push Files and Views" org-mobile-push t]
  19984. ["Get Captured and Flagged" org-mobile-pull t]
  19985. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19986. "--"
  19987. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19988. "--"
  19989. ("Documentation"
  19990. ["Show Version" org-version t]
  19991. ["Info Documentation" org-info t])
  19992. ("Customize"
  19993. ["Browse Org Group" org-customize t]
  19994. "--"
  19995. ["Expand This Menu" org-create-customize-menu
  19996. (fboundp 'customize-menu-create)])
  19997. ["Send bug report" org-submit-bug-report t]
  19998. "--"
  19999. ("Refresh/Reload"
  20000. ["Refresh setup current buffer" org-mode-restart t]
  20001. ["Reload Org (after update)" org-reload t]
  20002. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20003. ))
  20004. (defun org-info (&optional node)
  20005. "Read documentation for Org in the info system.
  20006. With optional NODE, go directly to that node."
  20007. (interactive)
  20008. (info (format "(org)%s" (or node ""))))
  20009. ;;;###autoload
  20010. (defun org-submit-bug-report ()
  20011. "Submit a bug report on Org via mail.
  20012. Don't hesitate to report any problems or inaccurate documentation.
  20013. If you don't have setup sending mail from (X)Emacs, please copy the
  20014. output buffer into your mail program, as it gives us important
  20015. information about your Org version and configuration."
  20016. (interactive)
  20017. (require 'reporter)
  20018. (defvar reporter-prompt-for-summary-p)
  20019. (org-load-modules-maybe)
  20020. (org-require-autoloaded-modules)
  20021. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20022. (reporter-submit-bug-report
  20023. "emacs-orgmode@gnu.org"
  20024. (org-version nil 'full)
  20025. (let (list)
  20026. (save-window-excursion
  20027. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20028. (delete-other-windows)
  20029. (erase-buffer)
  20030. (insert "You are about to submit a bug report to the Org mailing list.
  20031. We would like to add your full Org and Outline configuration to the
  20032. bug report. This greatly simplifies the work of the maintainer and
  20033. other experts on the mailing list.
  20034. HOWEVER, some variables you have customized may contain private
  20035. information. The names of customers, colleagues, or friends, might
  20036. appear in the form of file names, tags, todo states, or search strings.
  20037. If you answer yes to the prompt, you might want to check and remove
  20038. such private information before sending the email.")
  20039. (add-text-properties (point-min) (point-max) '(face org-warning))
  20040. (when (yes-or-no-p "Include your Org configuration ")
  20041. (mapatoms
  20042. (lambda (v)
  20043. (and (boundp v)
  20044. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20045. (or (and (symbol-value v)
  20046. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20047. (and
  20048. (get v 'custom-type) (get v 'standard-value)
  20049. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20050. (push v list)))))
  20051. (kill-buffer (get-buffer "*Warn about privacy*"))
  20052. list))
  20053. nil nil
  20054. "Remember to cover the basics, that is, what you expected to happen and
  20055. what in fact did happen. You don't know how to make a good report? See
  20056. http://orgmode.org/manual/Feedback.html#Feedback
  20057. Your bug report will be posted to the Org mailing list.
  20058. ------------------------------------------------------------------------")
  20059. (save-excursion
  20060. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20061. (replace-match "\\1Bug: \\3 [\\2]")))))
  20062. (defun org-install-agenda-files-menu ()
  20063. (let ((bl (buffer-list)))
  20064. (save-excursion
  20065. (while bl
  20066. (set-buffer (pop bl))
  20067. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20068. (when (derived-mode-p 'org-mode)
  20069. (easy-menu-change
  20070. '("Org") "File List for Agenda"
  20071. (append
  20072. (list
  20073. ["Edit File List" (org-edit-agenda-file-list) t]
  20074. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20075. ["Remove Current File from List" org-remove-file t]
  20076. ["Cycle through agenda files" org-cycle-agenda-files t]
  20077. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20078. "--")
  20079. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20080. ;;;; Documentation
  20081. (defun org-require-autoloaded-modules ()
  20082. (interactive)
  20083. (mapc #'require
  20084. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20085. org-table org-timer)))
  20086. ;;;###autoload
  20087. (defun org-reload (&optional uncompiled)
  20088. "Reload all org lisp files.
  20089. With prefix arg UNCOMPILED, load the uncompiled versions."
  20090. (interactive "P")
  20091. (require 'loadhist)
  20092. (let* ((org-dir (org-find-library-dir "org"))
  20093. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20094. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20095. (remove-re (format "\\`%s\\'"
  20096. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20097. (feats (delete-dups
  20098. (mapcar 'file-name-sans-extension
  20099. (mapcar 'file-name-nondirectory
  20100. (delq nil
  20101. (mapcar 'feature-file
  20102. features))))))
  20103. (lfeat (append
  20104. (sort
  20105. (setq feats
  20106. (delq nil (mapcar
  20107. (lambda (f)
  20108. (if (and (string-match feature-re f)
  20109. (not (string-match remove-re f)))
  20110. f nil))
  20111. feats)))
  20112. 'string-lessp)
  20113. (list "org-version" "org")))
  20114. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20115. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20116. load-uncore load-misses)
  20117. (setq load-misses
  20118. (delq 't
  20119. (mapcar (lambda (f)
  20120. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20121. (and (string= org-dir contrib-dir)
  20122. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20123. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20124. (add-to-list 'load-uncore f 'append)
  20125. 't)
  20126. f))
  20127. lfeat)))
  20128. (when load-uncore
  20129. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20130. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20131. (if load-misses
  20132. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20133. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20134. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20135. ;;;###autoload
  20136. (defun org-customize ()
  20137. "Call the customize function with org as argument."
  20138. (interactive)
  20139. (org-load-modules-maybe)
  20140. (org-require-autoloaded-modules)
  20141. (customize-browse 'org))
  20142. (defun org-create-customize-menu ()
  20143. "Create a full customization menu for Org mode, insert it into the menu."
  20144. (interactive)
  20145. (org-load-modules-maybe)
  20146. (org-require-autoloaded-modules)
  20147. (if (fboundp 'customize-menu-create)
  20148. (progn
  20149. (easy-menu-change
  20150. '("Org") "Customize"
  20151. `(["Browse Org group" org-customize t]
  20152. "--"
  20153. ,(customize-menu-create 'org)
  20154. ["Set" Custom-set t]
  20155. ["Save" Custom-save t]
  20156. ["Reset to Current" Custom-reset-current t]
  20157. ["Reset to Saved" Custom-reset-saved t]
  20158. ["Reset to Standard Settings" Custom-reset-standard t]))
  20159. (message "\"Org\"-menu now contains full customization menu"))
  20160. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20161. ;;;; Miscellaneous stuff
  20162. ;;; Generally useful functions
  20163. (defun org-get-at-eol (property n)
  20164. "Get text property PROPERTY at the end of line less N characters."
  20165. (get-text-property (- (point-at-eol) n) property))
  20166. (defun org-find-text-property-in-string (prop s)
  20167. "Return the first non-nil value of property PROP in string S."
  20168. (or (get-text-property 0 prop s)
  20169. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20170. prop s)))
  20171. (defun org-display-warning (message)
  20172. "Display the given MESSAGE as a warning."
  20173. (display-warning 'org message :warning))
  20174. (defun org-eval (form)
  20175. "Eval FORM and return result."
  20176. (condition-case error
  20177. (eval form)
  20178. (error (format "%%![Error: %s]" error))))
  20179. (defun org-in-clocktable-p ()
  20180. "Check if the cursor is in a clocktable."
  20181. (let ((pos (point)) start)
  20182. (save-excursion
  20183. (end-of-line 1)
  20184. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20185. (setq start (match-beginning 0))
  20186. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20187. (>= (match-end 0) pos)
  20188. start))))
  20189. (defun org-in-verbatim-emphasis ()
  20190. (save-match-data
  20191. (and (org-in-regexp org-emph-re 2)
  20192. (>= (point) (match-beginning 3))
  20193. (<= (point) (match-end 4))
  20194. (member (match-string 3) '("=" "~")))))
  20195. (defun org-overlay-display (ovl text &optional face evap)
  20196. "Make overlay OVL display TEXT with face FACE."
  20197. (overlay-put ovl 'display text)
  20198. (if face (overlay-put ovl 'face face))
  20199. (if evap (overlay-put ovl 'evaporate t)))
  20200. (defun org-overlay-before-string (ovl text &optional face evap)
  20201. "Make overlay OVL display TEXT with face FACE."
  20202. (if face (org-add-props text nil 'face face))
  20203. (overlay-put ovl 'before-string text)
  20204. (if evap (overlay-put ovl 'evaporate t)))
  20205. (defun org-find-overlays (prop &optional pos delete)
  20206. "Find all overlays specifying PROP at POS or point.
  20207. If DELETE is non-nil, delete all those overlays."
  20208. (let (found)
  20209. (dolist (ov (overlays-at (or pos (point))) found)
  20210. (cond ((not (overlay-get ov prop)))
  20211. (delete (delete-overlay ov))
  20212. (t (push ov found))))))
  20213. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20214. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20215. (if (and marker (marker-buffer marker)
  20216. (buffer-live-p (marker-buffer marker)))
  20217. (progn
  20218. (pop-to-buffer-same-window (marker-buffer marker))
  20219. (when (or (> marker (point-max)) (< marker (point-min)))
  20220. (widen))
  20221. (goto-char marker)
  20222. (org-show-context 'org-goto))
  20223. (if bookmark
  20224. (bookmark-jump bookmark)
  20225. (error "Cannot find location"))))
  20226. (defun org-quote-csv-field (s)
  20227. "Quote field for inclusion in CSV material."
  20228. (if (string-match "[\",]" s)
  20229. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20230. s))
  20231. (defun org-force-self-insert (N)
  20232. "Needed to enforce self-insert under remapping."
  20233. (interactive "p")
  20234. (self-insert-command N))
  20235. (defun org-string-width (s)
  20236. "Compute width of string, ignoring invisible characters.
  20237. This ignores character with invisibility property `org-link', and also
  20238. characters with property `org-cwidth', because these will become invisible
  20239. upon the next fontification round."
  20240. (let (b l)
  20241. (when (or (eq t buffer-invisibility-spec)
  20242. (assq 'org-link buffer-invisibility-spec))
  20243. (while (setq b (text-property-any 0 (length s)
  20244. 'invisible 'org-link s))
  20245. (setq s (concat (substring s 0 b)
  20246. (substring s (or (next-single-property-change
  20247. b 'invisible s)
  20248. (length s)))))))
  20249. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20250. (setq s (concat (substring s 0 b)
  20251. (substring s (or (next-single-property-change
  20252. b 'org-cwidth s)
  20253. (length s))))))
  20254. (setq l (string-width s) b -1)
  20255. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20256. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20257. l))
  20258. (defun org-shorten-string (s maxlength)
  20259. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20260. If the string is shorter or has length MAXLENGTH, just return the
  20261. original string. If it is longer, the functions finds a space in the
  20262. string, breaks this string off at that locations and adds three dots
  20263. as ellipsis. Including the ellipsis, the string will not be longer
  20264. than MAXLENGTH. If finding a good breaking point in the string does
  20265. not work, the string is just chopped off in the middle of a word
  20266. if necessary."
  20267. (if (<= (length s) maxlength)
  20268. s
  20269. (let* ((n (max (- maxlength 4) 1))
  20270. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20271. (if (string-match re s)
  20272. (concat (match-string 1 s) "...")
  20273. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20274. (defun org-get-indentation (&optional line)
  20275. "Get the indentation of the current line, interpreting tabs.
  20276. When LINE is given, assume it represents a line and compute its indentation."
  20277. (if line
  20278. (when (string-match "^ *" (org-remove-tabs line))
  20279. (match-end 0))
  20280. (save-excursion
  20281. (beginning-of-line 1)
  20282. (skip-chars-forward " \t")
  20283. (current-column))))
  20284. (defun org-get-string-indentation (s)
  20285. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20286. (let ((n -1) (i 0) (w tab-width) c)
  20287. (catch 'exit
  20288. (while (< (setq n (1+ n)) (length s))
  20289. (setq c (aref s n))
  20290. (cond ((= c ?\ ) (setq i (1+ i)))
  20291. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20292. (t (throw 'exit t)))))
  20293. i))
  20294. (defun org-remove-tabs (s &optional width)
  20295. "Replace tabulators in S with spaces.
  20296. Assumes that s is a single line, starting in column 0."
  20297. (setq width (or width tab-width))
  20298. (while (string-match "\t" s)
  20299. (setq s (replace-match
  20300. (make-string
  20301. (- (* width (/ (+ (match-beginning 0) width) width))
  20302. (match-beginning 0)) ?\ )
  20303. t t s)))
  20304. s)
  20305. (defun org-fix-indentation (line ind)
  20306. "Fix indentation in LINE.
  20307. IND is a cons cell with target and minimum indentation.
  20308. If the current indentation in LINE is smaller than the minimum,
  20309. leave it alone. If it is larger than ind, set it to the target."
  20310. (let* ((l (org-remove-tabs line))
  20311. (i (org-get-indentation l))
  20312. (i1 (car ind)) (i2 (cdr ind)))
  20313. (when (>= i i2) (setq l (substring line i2)))
  20314. (if (> i1 0)
  20315. (concat (make-string i1 ?\ ) l)
  20316. l)))
  20317. (defun org-remove-indentation (code &optional n)
  20318. "Remove maximum common indentation in string CODE and return it.
  20319. N may optionally be the number of columns to remove. Return CODE
  20320. as-is if removal failed."
  20321. (with-temp-buffer
  20322. (insert code)
  20323. (if (org-do-remove-indentation n) (buffer-string) code)))
  20324. (defun org-do-remove-indentation (&optional n)
  20325. "Remove the maximum common indentation from the buffer.
  20326. When optional argument N is a positive integer, remove exactly
  20327. that much characters from indentation, if possible. Return nil
  20328. if it fails."
  20329. (catch :exit
  20330. (goto-char (point-min))
  20331. ;; Find maximum common indentation, if not specified.
  20332. (let ((n (or n
  20333. (let ((min-ind (point-max)))
  20334. (save-excursion
  20335. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20336. (let ((ind (1- (current-column))))
  20337. (if (zerop ind) (throw :exit nil)
  20338. (setq min-ind (min min-ind ind))))))
  20339. min-ind))))
  20340. (if (zerop n) (throw :exit nil)
  20341. ;; Remove exactly N indentation, but give up if not possible.
  20342. (while (not (eobp))
  20343. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20344. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20345. ((< ind n) (throw :exit nil))
  20346. (t (indent-line-to (- ind n))))
  20347. (forward-line)))
  20348. ;; Signal success.
  20349. t))))
  20350. (defun org-fill-template (template alist)
  20351. "Find each %key of ALIST in TEMPLATE and replace it."
  20352. (let ((case-fold-search nil))
  20353. (dolist (entry (sort (copy-sequence alist)
  20354. (lambda (a b) (< (length (car a)) (length (car b))))))
  20355. (setq template
  20356. (replace-regexp-in-string
  20357. (concat "%" (regexp-quote (car entry)))
  20358. (or (cdr entry) "") template t t)))
  20359. template))
  20360. (defun org-base-buffer (buffer)
  20361. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20362. (if (not buffer)
  20363. buffer
  20364. (or (buffer-base-buffer buffer)
  20365. buffer)))
  20366. (defun org-wrap (string &optional width lines)
  20367. "Wrap string to either a number of lines, or a width in characters.
  20368. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20369. that costs. If there is a word longer than WIDTH, the text is actually
  20370. wrapped to the length of that word.
  20371. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20372. many lines, whatever width that takes.
  20373. The return value is a list of lines, without newlines at the end."
  20374. (let* ((words (org-split-string string "[ \t\n]+"))
  20375. (maxword (apply 'max (mapcar 'org-string-width words)))
  20376. w ll)
  20377. (cond (width
  20378. (org-do-wrap words (max maxword width)))
  20379. (lines
  20380. (setq w maxword)
  20381. (setq ll (org-do-wrap words maxword))
  20382. (if (<= (length ll) lines)
  20383. ll
  20384. (setq ll words)
  20385. (while (> (length ll) lines)
  20386. (setq w (1+ w))
  20387. (setq ll (org-do-wrap words w)))
  20388. ll))
  20389. (t (error "Cannot wrap this")))))
  20390. (defun org-do-wrap (words width)
  20391. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20392. (let (lines line)
  20393. (while words
  20394. (setq line (pop words))
  20395. (while (and words (< (+ (length line) (length (car words))) width))
  20396. (setq line (concat line " " (pop words))))
  20397. (setq lines (push line lines)))
  20398. (nreverse lines)))
  20399. (defun org-split-string (string &optional separators)
  20400. "Splits STRING into substrings at SEPARATORS.
  20401. SEPARATORS is a regular expression.
  20402. No empty strings are returned if there are matches at the beginning
  20403. and end of string."
  20404. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20405. (let ((start 0) notfirst list)
  20406. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20407. (if (and notfirst
  20408. (= start (match-beginning 0))
  20409. (< start (length string)))
  20410. (1+ start) start))
  20411. (< (match-beginning 0) (length string)))
  20412. (setq notfirst t)
  20413. (or (eq (match-beginning 0) 0)
  20414. (and (eq (match-beginning 0) (match-end 0))
  20415. (eq (match-beginning 0) start))
  20416. (push (substring string start (match-beginning 0)) list))
  20417. (setq start (match-end 0)))
  20418. (or (eq start (length string))
  20419. (push (substring string start) list))
  20420. (nreverse list)))
  20421. (defun org-quote-vert (s)
  20422. "Replace \"|\" with \"\\vert\"."
  20423. (while (string-match "|" s)
  20424. (setq s (replace-match "\\vert" t t s)))
  20425. s)
  20426. (defun org-uuidgen-p (s)
  20427. "Is S an ID created by UUIDGEN?"
  20428. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20429. (defun org-in-src-block-p (&optional inside)
  20430. "Whether point is in a code source block.
  20431. When INSIDE is non-nil, don't consider we are within a src block
  20432. when point is at #+BEGIN_SRC or #+END_SRC."
  20433. (let ((case-fold-search t))
  20434. (or (and (eq (get-char-property (point) 'src-block) t))
  20435. (and (not inside)
  20436. (save-match-data
  20437. (save-excursion
  20438. (beginning-of-line)
  20439. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20440. (defun org-context ()
  20441. "Return a list of contexts of the current cursor position.
  20442. If several contexts apply, all are returned.
  20443. Each context entry is a list with a symbol naming the context, and
  20444. two positions indicating start and end of the context. Possible
  20445. contexts are:
  20446. :headline anywhere in a headline
  20447. :headline-stars on the leading stars in a headline
  20448. :todo-keyword on a TODO keyword (including DONE) in a headline
  20449. :tags on the TAGS in a headline
  20450. :priority on the priority cookie in a headline
  20451. :item on the first line of a plain list item
  20452. :item-bullet on the bullet/number of a plain list item
  20453. :checkbox on the checkbox in a plain list item
  20454. :table in an Org table
  20455. :table-special on a special filed in a table
  20456. :table-table in a table.el table
  20457. :clocktable in a clocktable
  20458. :src-block in a source block
  20459. :link on a hyperlink
  20460. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20461. :target on a <<target>>
  20462. :radio-target on a <<<radio-target>>>
  20463. :latex-fragment on a LaTeX fragment
  20464. :latex-preview on a LaTeX fragment with overlaid preview image
  20465. This function expects the position to be visible because it uses font-lock
  20466. faces as a help to recognize the following contexts: :table-special, :link,
  20467. and :keyword."
  20468. (let* ((f (get-text-property (point) 'face))
  20469. (faces (if (listp f) f (list f)))
  20470. (case-fold-search t)
  20471. (p (point)) clist o)
  20472. ;; First the large context
  20473. (cond
  20474. ((org-at-heading-p t)
  20475. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20476. (when (progn
  20477. (beginning-of-line 1)
  20478. (looking-at org-todo-line-tags-regexp))
  20479. (push (org-point-in-group p 1 :headline-stars) clist)
  20480. (push (org-point-in-group p 2 :todo-keyword) clist)
  20481. (push (org-point-in-group p 4 :tags) clist))
  20482. (goto-char p)
  20483. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20484. (when (looking-at "\\[#[A-Z0-9]\\]")
  20485. (push (org-point-in-group p 0 :priority) clist)))
  20486. ((org-at-item-p)
  20487. (push (org-point-in-group p 2 :item-bullet) clist)
  20488. (push (list :item (point-at-bol)
  20489. (save-excursion (org-end-of-item) (point)))
  20490. clist)
  20491. (and (org-at-item-checkbox-p)
  20492. (push (org-point-in-group p 0 :checkbox) clist)))
  20493. ((org-at-table-p)
  20494. (push (list :table (org-table-begin) (org-table-end)) clist)
  20495. (when (memq 'org-formula faces)
  20496. (push (list :table-special
  20497. (previous-single-property-change p 'face)
  20498. (next-single-property-change p 'face)) clist)))
  20499. ((org-at-table-p 'any)
  20500. (push (list :table-table) clist)))
  20501. (goto-char p)
  20502. (let ((case-fold-search t))
  20503. ;; New the "medium" contexts: clocktables, source blocks
  20504. (cond ((org-in-clocktable-p)
  20505. (push (list :clocktable
  20506. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20507. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20508. (match-beginning 1))
  20509. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20510. (match-end 0))) clist))
  20511. ((org-in-src-block-p)
  20512. (push (list :src-block
  20513. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20514. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20515. (match-beginning 1))
  20516. (and (search-forward "#+END_SRC" nil t)
  20517. (match-beginning 0))) clist))))
  20518. (goto-char p)
  20519. ;; Now the small context
  20520. (cond
  20521. ((org-at-timestamp-p)
  20522. (push (org-point-in-group p 0 :timestamp) clist))
  20523. ((memq 'org-link faces)
  20524. (push (list :link
  20525. (previous-single-property-change p 'face)
  20526. (next-single-property-change p 'face)) clist))
  20527. ((memq 'org-special-keyword faces)
  20528. (push (list :keyword
  20529. (previous-single-property-change p 'face)
  20530. (next-single-property-change p 'face)) clist))
  20531. ((org-at-target-p)
  20532. (push (org-point-in-group p 0 :target) clist)
  20533. (goto-char (1- (match-beginning 0)))
  20534. (when (looking-at org-radio-target-regexp)
  20535. (push (org-point-in-group p 0 :radio-target) clist))
  20536. (goto-char p))
  20537. ((setq o (cl-some
  20538. (lambda (o)
  20539. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20540. o))
  20541. (overlays-at (point))))
  20542. (push (list :latex-fragment
  20543. (overlay-start o) (overlay-end o)) clist)
  20544. (push (list :latex-preview
  20545. (overlay-start o) (overlay-end o)) clist))
  20546. ((org-inside-LaTeX-fragment-p)
  20547. ;; FIXME: positions wrong.
  20548. (push (list :latex-fragment (point) (point)) clist)))
  20549. (setq clist (nreverse (delq nil clist)))
  20550. clist))
  20551. (defun org-in-regexp (regexp &optional nlines visually)
  20552. "Check if point is inside a match of REGEXP.
  20553. Normally only the current line is checked, but you can include
  20554. NLINES extra lines around point into the search. If VISUALLY is
  20555. set, require that the cursor is not after the match but really
  20556. on, so that the block visually is on the match.
  20557. Return nil or a cons cell (BEG . END) where BEG and END are,
  20558. respectively, the positions at the beginning and the end of the
  20559. match."
  20560. (catch :exit
  20561. (let ((pos (point))
  20562. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20563. (save-excursion
  20564. (beginning-of-line (- 1 (or nlines 0)))
  20565. (while (and (re-search-forward regexp eol t)
  20566. (<= (match-beginning 0) pos))
  20567. (let ((end (match-end 0)))
  20568. (when (or (> end pos) (and (= end pos) (not visually)))
  20569. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20570. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20571. "Non-nil when point is between matches of START-RE and END-RE.
  20572. Also return a non-nil value when point is on one of the matches.
  20573. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20574. buffer positions. Default values are the positions of headlines
  20575. surrounding the point.
  20576. The functions returns a cons cell whose car (resp. cdr) is the
  20577. position before START-RE (resp. after END-RE)."
  20578. (save-match-data
  20579. (let ((pos (point))
  20580. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20581. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20582. beg end)
  20583. (save-excursion
  20584. ;; Point is on a block when on START-RE or if START-RE can be
  20585. ;; found before it...
  20586. (and (or (org-in-regexp start-re)
  20587. (re-search-backward start-re limit-up t))
  20588. (setq beg (match-beginning 0))
  20589. ;; ... and END-RE after it...
  20590. (goto-char (match-end 0))
  20591. (re-search-forward end-re limit-down t)
  20592. (> (setq end (match-end 0)) pos)
  20593. ;; ... without another START-RE in-between.
  20594. (goto-char (match-beginning 0))
  20595. (not (re-search-backward start-re (1+ beg) t))
  20596. ;; Return value.
  20597. (cons beg end))))))
  20598. (defun org-in-block-p (names)
  20599. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20600. NAMES is a list of strings containing names of blocks.
  20601. Return first block name matched, or nil. Beware that in case of
  20602. nested blocks, the returned name may not belong to the closest
  20603. block from point."
  20604. (save-match-data
  20605. (catch 'exit
  20606. (let ((case-fold-search t)
  20607. (lim-up (save-excursion (outline-previous-heading)))
  20608. (lim-down (save-excursion (outline-next-heading))))
  20609. (dolist (name names)
  20610. (let ((n (regexp-quote name)))
  20611. (when (org-between-regexps-p
  20612. (concat "^[ \t]*#\\+begin_" n)
  20613. (concat "^[ \t]*#\\+end_" n)
  20614. lim-up lim-down)
  20615. (throw 'exit n)))))
  20616. nil)))
  20617. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20618. "Call `multi-occur' with buffers for all agenda files."
  20619. (interactive "sOrg-files matching: ")
  20620. (let* ((files (org-agenda-files))
  20621. (tnames (mapcar #'file-truename files))
  20622. (extra org-agenda-text-search-extra-files))
  20623. (when (eq (car extra) 'agenda-archives)
  20624. (setq extra (cdr extra))
  20625. (setq files (org-add-archive-files files)))
  20626. (dolist (f extra)
  20627. (unless (member (file-truename f) tnames)
  20628. (unless (member f files) (setq files (append files (list f))))
  20629. (setq tnames (append tnames (list (file-truename f))))))
  20630. (multi-occur
  20631. (mapcar (lambda (x)
  20632. (with-current-buffer
  20633. ;; FIXME: Why not just (find-file-noselect x)?
  20634. ;; Is it to avoid the "revert buffer" prompt?
  20635. (or (get-file-buffer x) (find-file-noselect x))
  20636. (widen)
  20637. (current-buffer)))
  20638. files)
  20639. regexp)))
  20640. (add-hook 'occur-mode-find-occurrence-hook
  20641. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20642. (defun org-occur-link-in-agenda-files ()
  20643. "Create a link and search for it in the agendas.
  20644. The link is not stored in `org-stored-links', it is just created
  20645. for the search purpose."
  20646. (interactive)
  20647. (let ((link (condition-case nil
  20648. (org-store-link nil)
  20649. (error "Unable to create a link to here"))))
  20650. (org-occur-in-agenda-files (regexp-quote link))))
  20651. (defun org-reverse-string (string)
  20652. "Return the reverse of STRING."
  20653. (apply 'string (reverse (string-to-list string))))
  20654. ;; defsubst org-uniquify must be defined before first use
  20655. (defun org-uniquify-alist (alist)
  20656. "Merge elements of ALIST with the same key.
  20657. For example, in this alist:
  20658. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20659. => \\='((a 1 3) (b 2))
  20660. merge (a 1) and (a 3) into (a 1 3).
  20661. The function returns the new ALIST."
  20662. (let (rtn)
  20663. (dolist (e alist rtn)
  20664. (let (n)
  20665. (if (not (assoc (car e) rtn))
  20666. (push e rtn)
  20667. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20668. (setq rtn (assq-delete-all (car e) rtn))
  20669. (push n rtn))))))
  20670. (defun org-delete-all (elts list)
  20671. "Remove all elements in ELTS from LIST.
  20672. Comparison is done with `equal'. It is a destructive operation
  20673. that may remove elements by altering the list structure."
  20674. (while elts
  20675. (setq list (delete (pop elts) list)))
  20676. list)
  20677. (defun org-back-over-empty-lines ()
  20678. "Move backwards over whitespace, to the beginning of the first empty line.
  20679. Returns the number of empty lines passed."
  20680. (let ((pos (point)))
  20681. (if (cdr (assq 'heading org-blank-before-new-entry))
  20682. (skip-chars-backward " \t\n\r")
  20683. (unless (eobp)
  20684. (forward-line -1)))
  20685. (beginning-of-line 2)
  20686. (goto-char (min (point) pos))
  20687. (count-lines (point) pos)))
  20688. (defun org-skip-whitespace ()
  20689. (skip-chars-forward " \t\n\r"))
  20690. (defun org-point-in-group (point group &optional context)
  20691. "Check if POINT is in match-group GROUP.
  20692. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20693. match. If the match group does not exist or point is not inside it,
  20694. return nil."
  20695. (and (match-beginning group)
  20696. (>= point (match-beginning group))
  20697. (<= point (match-end group))
  20698. (if context
  20699. (list context (match-beginning group) (match-end group))
  20700. t)))
  20701. (defun org-switch-to-buffer-other-window (&rest args)
  20702. "Switch to buffer in a second window on the current frame.
  20703. In particular, do not allow pop-up frames.
  20704. Returns the newly created buffer."
  20705. (org-no-popups
  20706. (apply 'switch-to-buffer-other-window args)))
  20707. (defun org-combine-plists (&rest plists)
  20708. "Create a single property list from all plists in PLISTS.
  20709. The process starts by copying the first list, and then setting properties
  20710. from the other lists. Settings in the last list are the most significant
  20711. ones and overrule settings in the other lists."
  20712. (let ((rtn (copy-sequence (pop plists)))
  20713. p v ls)
  20714. (while plists
  20715. (setq ls (pop plists))
  20716. (while ls
  20717. (setq p (pop ls) v (pop ls))
  20718. (setq rtn (plist-put rtn p v))))
  20719. rtn))
  20720. (defun org-replace-escapes (string table)
  20721. "Replace %-escapes in STRING with values in TABLE.
  20722. TABLE is an association list with keys like \"%a\" and string values.
  20723. The sequences in STRING may contain normal field width and padding information,
  20724. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20725. so values can contain further %-escapes if they are define later in TABLE."
  20726. (let ((tbl (copy-alist table))
  20727. (case-fold-search nil)
  20728. (pchg 0)
  20729. re rpl)
  20730. (dolist (e tbl)
  20731. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20732. (when (and (cdr e) (string-match re (cdr e)))
  20733. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20734. (safe "SREF"))
  20735. (add-text-properties 0 3 (list 'sref sref) safe)
  20736. (setcdr e (replace-match safe t t (cdr e)))))
  20737. (while (string-match re string)
  20738. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20739. (cdr e)))
  20740. (setq string (replace-match rpl t t string))))
  20741. (while (setq pchg (next-property-change pchg string))
  20742. (let ((sref (get-text-property pchg 'sref string)))
  20743. (when (and sref (string-match "SREF" string pchg))
  20744. (setq string (replace-match sref t t string)))))
  20745. string))
  20746. (defun org-find-base-buffer-visiting (file)
  20747. "Like `find-buffer-visiting' but always return the base buffer and
  20748. not an indirect buffer."
  20749. (let ((buf (or (get-file-buffer file)
  20750. (find-buffer-visiting file))))
  20751. (if buf
  20752. (or (buffer-base-buffer buf) buf)
  20753. nil)))
  20754. ;;; TODO: Only called once, from ox-odt which should probably use
  20755. ;;; org-export-inline-image-p or something.
  20756. (defun org-file-image-p (file)
  20757. "Return non-nil if FILE is an image."
  20758. (save-match-data
  20759. (string-match (image-file-name-regexp) file)))
  20760. (defun org-get-cursor-date (&optional with-time)
  20761. "Return the date at cursor in as a time.
  20762. This works in the calendar and in the agenda, anywhere else it just
  20763. returns the current time.
  20764. If WITH-TIME is non-nil, returns the time of the event at point (in
  20765. the agenda) or the current time of the day."
  20766. (let (date day defd tp hod mod)
  20767. (when with-time
  20768. (setq tp (get-text-property (point) 'time))
  20769. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20770. (setq hod (string-to-number (match-string 1 tp))
  20771. mod (string-to-number (match-string 2 tp))))
  20772. (or tp (let ((now (decode-time)))
  20773. (setq hod (nth 2 now)
  20774. mod (nth 1 now)))))
  20775. (cond
  20776. ((eq major-mode 'calendar-mode)
  20777. (setq date (calendar-cursor-to-date)
  20778. defd (encode-time 0 (or mod 0) (or hod 0)
  20779. (nth 1 date) (nth 0 date) (nth 2 date))))
  20780. ((eq major-mode 'org-agenda-mode)
  20781. (setq day (get-text-property (point) 'day))
  20782. (when day
  20783. (setq date (calendar-gregorian-from-absolute day)
  20784. defd (encode-time 0 (or mod 0) (or hod 0)
  20785. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20786. (or defd (current-time))))
  20787. (defun org-mark-subtree (&optional up)
  20788. "Mark the current subtree.
  20789. This puts point at the start of the current subtree, and mark at
  20790. the end. If a numeric prefix UP is given, move up into the
  20791. hierarchy of headlines by UP levels before marking the subtree."
  20792. (interactive "P")
  20793. (org-with-limited-levels
  20794. (cond ((org-at-heading-p) (beginning-of-line))
  20795. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20796. (t (outline-previous-visible-heading 1))))
  20797. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20798. (if (called-interactively-p 'any)
  20799. (call-interactively 'org-mark-element)
  20800. (org-mark-element)))
  20801. (defun org-file-newer-than-p (file time)
  20802. "Non-nil if FILE is newer than TIME.
  20803. FILE is a filename, as a string, TIME is a list of integers, as
  20804. returned by, e.g., `current-time'."
  20805. (and (file-exists-p file)
  20806. ;; Only compare times up to whole seconds as some file-systems
  20807. ;; (e.g. HFS+) do not retain any finer granularity. As
  20808. ;; a consequence, make sure we return non-nil when the two
  20809. ;; times are equal.
  20810. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20811. (cl-subseq time 0 2)))))
  20812. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20813. "Compile a SOURCE file using PROCESS.
  20814. PROCESS is either a function or a list of shell commands, as
  20815. strings. EXT is a file extension, without the leading dot, as
  20816. a string. It is used to check if the process actually succeeded.
  20817. PROCESS must create a file with the same base name and directory
  20818. as SOURCE, but ending with EXT. The function then returns its
  20819. filename. Otherwise, it raises an error. The error message can
  20820. then be refined by providing string ERR-MSG, which is appended to
  20821. the standard message.
  20822. If PROCESS is a function, it is called with a single argument:
  20823. the SOURCE file.
  20824. If it is a list of commands, each of them is called using
  20825. `shell-command'. By default, in each command, %b, %f, %F and %o
  20826. are replaced with, respectively, SOURCE base name, name, full
  20827. name and directory. It is possible, however, to use more
  20828. place-holders by specifying them in optional argument SPEC, as an
  20829. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20830. When PROCESS is a list of commands, optional argument LOG-BUF can
  20831. be set to a buffer or a buffer name. `shell-command' then uses
  20832. it for output."
  20833. (let* ((base-name (file-name-base source))
  20834. (full-name (file-truename source))
  20835. (out-dir (file-name-directory source))
  20836. (time (current-time))
  20837. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20838. (save-window-excursion
  20839. (pcase process
  20840. ((pred functionp) (funcall process (shell-quote-argument source)))
  20841. ((pred consp)
  20842. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20843. (spec (append spec
  20844. `((?b . ,(shell-quote-argument base-name))
  20845. (?f . ,(shell-quote-argument source))
  20846. (?F . ,(shell-quote-argument full-name))
  20847. (?o . ,(shell-quote-argument out-dir))))))
  20848. (dolist (command process)
  20849. (shell-command (format-spec command spec) log-buf))))
  20850. (_ (error "No valid command to process %S%s" source err-msg))))
  20851. ;; Check for process failure. Output file is expected to be
  20852. ;; located in the same directory as SOURCE.
  20853. (let ((output (expand-file-name (concat base-name "." ext) out-dir)))
  20854. (unless (org-file-newer-than-p output time)
  20855. (error (format "File %S wasn't produced%s" output err-msg)))
  20856. output)))
  20857. ;;; Indentation
  20858. (defun org--get-expected-indentation (element contentsp)
  20859. "Expected indentation column for current line, according to ELEMENT.
  20860. ELEMENT is an element containing point. CONTENTSP is non-nil
  20861. when indentation is to be computed according to contents of
  20862. ELEMENT."
  20863. (let ((type (org-element-type element))
  20864. (start (org-element-property :begin element))
  20865. (post-affiliated (org-element-property :post-affiliated element)))
  20866. (org-with-wide-buffer
  20867. (cond
  20868. (contentsp
  20869. (cl-case type
  20870. ((diary-sexp footnote-definition) 0)
  20871. ((headline inlinetask nil)
  20872. (if (not org-adapt-indentation) 0
  20873. (let ((level (org-current-level)))
  20874. (if level (1+ level) 0))))
  20875. ((item plain-list) (org-list-item-body-column post-affiliated))
  20876. (t
  20877. (goto-char start)
  20878. (org-get-indentation))))
  20879. ((memq type '(headline inlinetask nil))
  20880. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20881. (org--get-expected-indentation element t)
  20882. 0))
  20883. ((memq type '(diary-sexp footnote-definition)) 0)
  20884. ;; First paragraph of a footnote definition or an item.
  20885. ;; Indent like parent.
  20886. ((< (line-beginning-position) start)
  20887. (org--get-expected-indentation
  20888. (org-element-property :parent element) t))
  20889. ;; At first line: indent according to previous sibling, if any,
  20890. ;; ignoring footnote definitions and inline tasks, or parent's
  20891. ;; contents.
  20892. ((= (line-beginning-position) start)
  20893. (catch 'exit
  20894. (while t
  20895. (if (= (point-min) start) (throw 'exit 0)
  20896. (goto-char (1- start))
  20897. (let* ((previous (org-element-at-point))
  20898. (parent previous))
  20899. (while (and parent (<= (org-element-property :end parent) start))
  20900. (setq previous parent
  20901. parent (org-element-property :parent parent)))
  20902. (cond
  20903. ((not previous) (throw 'exit 0))
  20904. ((> (org-element-property :end previous) start)
  20905. (throw 'exit (org--get-expected-indentation previous t)))
  20906. ((memq (org-element-type previous)
  20907. '(footnote-definition inlinetask))
  20908. (setq start (org-element-property :begin previous)))
  20909. (t (goto-char (org-element-property :begin previous))
  20910. (throw 'exit
  20911. (if (bolp) (org-get-indentation)
  20912. ;; At first paragraph in an item or
  20913. ;; a footnote definition.
  20914. (org--get-expected-indentation
  20915. (org-element-property :parent previous) t))))))))))
  20916. ;; Otherwise, move to the first non-blank line above.
  20917. (t
  20918. (beginning-of-line)
  20919. (let ((pos (point)))
  20920. (skip-chars-backward " \r\t\n")
  20921. (cond
  20922. ;; Two blank lines end a footnote definition or a plain
  20923. ;; list. When we indent an empty line after them, the
  20924. ;; containing list or footnote definition is over, so it
  20925. ;; qualifies as a previous sibling. Therefore, we indent
  20926. ;; like its first line.
  20927. ((and (memq type '(footnote-definition plain-list))
  20928. (> (count-lines (point) pos) 2))
  20929. (goto-char start)
  20930. (org-get-indentation))
  20931. ;; Line above is the first one of a paragraph at the
  20932. ;; beginning of an item or a footnote definition. Indent
  20933. ;; like parent.
  20934. ((< (line-beginning-position) start)
  20935. (org--get-expected-indentation
  20936. (org-element-property :parent element) t))
  20937. ;; Line above is the beginning of an element, i.e., point
  20938. ;; was originally on the blank lines between element's start
  20939. ;; and contents.
  20940. ((= (line-beginning-position) post-affiliated)
  20941. (org--get-expected-indentation element t))
  20942. ;; POS is after contents in a greater element. Indent like
  20943. ;; the beginning of the element.
  20944. ;;
  20945. ;; As a special case, if point is at the end of a footnote
  20946. ;; definition or an item, indent like the very last element
  20947. ;; within. If that last element is an item, indent like its
  20948. ;; contents.
  20949. ((and (not (eq type 'paragraph))
  20950. (let ((cend (org-element-property :contents-end element)))
  20951. (and cend (<= cend pos))))
  20952. (if (memq type '(footnote-definition item plain-list))
  20953. (let ((last (org-element-at-point)))
  20954. (org--get-expected-indentation
  20955. last (eq (org-element-type last) 'item)))
  20956. (goto-char start)
  20957. (org-get-indentation)))
  20958. ;; In any other case, indent like the current line.
  20959. (t (org-get-indentation)))))))))
  20960. (defun org--align-node-property ()
  20961. "Align node property at point.
  20962. Alignment is done according to `org-property-format', which see."
  20963. (when (save-excursion
  20964. (beginning-of-line)
  20965. (looking-at org-property-re))
  20966. (replace-match
  20967. (concat (match-string 4)
  20968. (org-trim
  20969. (format org-property-format (match-string 1) (match-string 3))))
  20970. t t)))
  20971. (defun org-indent-line ()
  20972. "Indent line depending on context.
  20973. Indentation is done according to the following rules:
  20974. - Footnote definitions, diary sexps, headlines and inline tasks
  20975. have to start at column 0.
  20976. - On the very first line of an element, consider, in order, the
  20977. next rules until one matches:
  20978. 1. If there's a sibling element before, ignoring footnote
  20979. definitions and inline tasks, indent like its first line.
  20980. 2. If element has a parent, indent like its contents. More
  20981. precisely, if parent is an item, indent after the
  20982. description part, if any, or the bullet (see
  20983. `org-list-description-max-indent'). Else, indent like
  20984. parent's first line.
  20985. 3. Otherwise, indent relatively to current level, if
  20986. `org-adapt-indentation' is non-nil, or to left margin.
  20987. - On a blank line at the end of an element, indent according to
  20988. the type of the element. More precisely
  20989. 1. If element is a plain list, an item, or a footnote
  20990. definition, indent like the very last element within.
  20991. 2. If element is a paragraph, indent like its last non blank
  20992. line.
  20993. 3. Otherwise, indent like its very first line.
  20994. - In the code part of a source block, use language major mode
  20995. to indent current line if `org-src-tab-acts-natively' is
  20996. non-nil. If it is nil, do nothing.
  20997. - Otherwise, indent like the first non-blank line above.
  20998. The function doesn't indent an item as it could break the whole
  20999. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  21000. `\\[org-shiftmetaright]'.
  21001. Also align node properties according to `org-property-format'."
  21002. (interactive)
  21003. (cond
  21004. (orgstruct-is-++
  21005. (let ((indent-line-function
  21006. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  21007. (indent-according-to-mode)))
  21008. ((org-at-heading-p) 'noindent)
  21009. (t
  21010. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21011. (type (org-element-type element)))
  21012. (cond ((and (memq type '(plain-list item))
  21013. (= (line-beginning-position)
  21014. (org-element-property :post-affiliated element)))
  21015. 'noindent)
  21016. ((and (eq type 'src-block)
  21017. org-src-tab-acts-natively
  21018. (> (line-beginning-position)
  21019. (org-element-property :post-affiliated element))
  21020. (< (line-beginning-position)
  21021. (org-with-wide-buffer
  21022. (goto-char (org-element-property :end element))
  21023. (skip-chars-backward " \r\t\n")
  21024. (line-beginning-position))))
  21025. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21026. (t
  21027. (let ((column (org--get-expected-indentation element nil)))
  21028. ;; Preserve current column.
  21029. (if (<= (current-column) (current-indentation))
  21030. (indent-line-to column)
  21031. (save-excursion (indent-line-to column))))
  21032. ;; Align node property. Also preserve current column.
  21033. (when (eq type 'node-property)
  21034. (let ((column (current-column)))
  21035. (org--align-node-property)
  21036. (org-move-to-column column)))))))))
  21037. (defun org-indent-region (start end)
  21038. "Indent each non-blank line in the region.
  21039. Called from a program, START and END specify the region to
  21040. indent. The function will not indent contents of example blocks,
  21041. verse blocks and export blocks as leading white spaces are
  21042. assumed to be significant there."
  21043. (interactive "r")
  21044. (save-excursion
  21045. (goto-char start)
  21046. (skip-chars-forward " \r\t\n")
  21047. (unless (eobp) (beginning-of-line))
  21048. (let ((indent-to
  21049. (lambda (ind pos)
  21050. ;; Set IND as indentation for all lines between point and
  21051. ;; POS. Blank lines are ignored. Leave point after POS
  21052. ;; once done.
  21053. (let ((limit (copy-marker pos)))
  21054. (while (< (point) limit)
  21055. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21056. (forward-line))
  21057. (set-marker limit nil))))
  21058. (end (copy-marker end)))
  21059. (while (< (point) end)
  21060. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21061. (let* ((element (org-element-at-point))
  21062. (type (org-element-type element))
  21063. (element-end (copy-marker (org-element-property :end element)))
  21064. (ind (org--get-expected-indentation element nil)))
  21065. (cond
  21066. ((or (memq type '(paragraph table table-row))
  21067. (not (or (org-element-property :contents-begin element)
  21068. (memq type
  21069. '(example-block export-block src-block)))))
  21070. ;; Elements here are indented as a single block. Also
  21071. ;; align node properties.
  21072. (when (eq type 'node-property)
  21073. (org--align-node-property)
  21074. (beginning-of-line))
  21075. (funcall indent-to ind (min element-end end)))
  21076. (t
  21077. ;; Elements in this category consist of three parts:
  21078. ;; before the contents, the contents, and after the
  21079. ;; contents. The contents are treated specially,
  21080. ;; according to the element type, or not indented at
  21081. ;; all. Other parts are indented as a single block.
  21082. (let* ((post (copy-marker
  21083. (org-element-property :post-affiliated element)))
  21084. (cbeg
  21085. (copy-marker
  21086. (cond
  21087. ((not (org-element-property :contents-begin element))
  21088. ;; Fake contents for source blocks.
  21089. (org-with-wide-buffer
  21090. (goto-char post)
  21091. (forward-line)
  21092. (point)))
  21093. ((memq type '(footnote-definition item plain-list))
  21094. ;; Contents in these elements could start on
  21095. ;; the same line as the beginning of the
  21096. ;; element. Make sure we start indenting
  21097. ;; from the second line.
  21098. (org-with-wide-buffer
  21099. (goto-char post)
  21100. (end-of-line)
  21101. (skip-chars-forward " \r\t\n")
  21102. (if (eobp) (point) (line-beginning-position))))
  21103. (t (org-element-property :contents-begin element)))))
  21104. (cend (copy-marker
  21105. (or (org-element-property :contents-end element)
  21106. ;; Fake contents for source blocks.
  21107. (org-with-wide-buffer
  21108. (goto-char element-end)
  21109. (skip-chars-backward " \r\t\n")
  21110. (line-beginning-position)))
  21111. t)))
  21112. ;; Do not change items indentation individually as it
  21113. ;; might break the list as a whole. On the other
  21114. ;; hand, when at a plain list, indent it as a whole.
  21115. (cond ((eq type 'plain-list)
  21116. (let ((offset (- ind (org-get-indentation))))
  21117. (unless (zerop offset)
  21118. (indent-rigidly (org-element-property :begin element)
  21119. (org-element-property :end element)
  21120. offset))
  21121. (goto-char cbeg)))
  21122. ((eq type 'item) (goto-char cbeg))
  21123. (t (funcall indent-to ind (min cbeg end))))
  21124. (when (< (point) end)
  21125. (cl-case type
  21126. ((example-block export-block verse-block))
  21127. (src-block
  21128. ;; In a source block, indent source code
  21129. ;; according to language major mode, but only if
  21130. ;; `org-src-tab-acts-natively' is non-nil.
  21131. (when (and (< (point) end) org-src-tab-acts-natively)
  21132. (ignore-errors
  21133. (org-babel-do-in-edit-buffer
  21134. (indent-region (point-min) (point-max))))))
  21135. (t (org-indent-region (point) (min cend end))))
  21136. (goto-char (min cend end))
  21137. (when (< (point) end)
  21138. (funcall indent-to ind (min element-end end))))
  21139. (set-marker post nil)
  21140. (set-marker cbeg nil)
  21141. (set-marker cend nil))))
  21142. (set-marker element-end nil))))
  21143. (set-marker end nil))))
  21144. (defun org-indent-drawer ()
  21145. "Indent the drawer at point."
  21146. (interactive)
  21147. (unless (save-excursion
  21148. (beginning-of-line)
  21149. (looking-at-p org-drawer-regexp))
  21150. (user-error "Not at a drawer"))
  21151. (let ((element (org-element-at-point)))
  21152. (unless (memq (org-element-type element) '(drawer property-drawer))
  21153. (user-error "Not at a drawer"))
  21154. (org-with-wide-buffer
  21155. (org-indent-region (org-element-property :begin element)
  21156. (org-element-property :end element))))
  21157. (message "Drawer at point indented"))
  21158. (defun org-indent-block ()
  21159. "Indent the block at point."
  21160. (interactive)
  21161. (unless (save-excursion
  21162. (beginning-of-line)
  21163. (let ((case-fold-search t))
  21164. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21165. (user-error "Not at a block"))
  21166. (let ((element (org-element-at-point)))
  21167. (unless (memq (org-element-type element)
  21168. '(comment-block center-block dynamic-block example-block
  21169. export-block quote-block special-block
  21170. src-block verse-block))
  21171. (user-error "Not at a block"))
  21172. (org-with-wide-buffer
  21173. (org-indent-region (org-element-property :begin element)
  21174. (org-element-property :end element))))
  21175. (message "Block at point indented"))
  21176. ;;; Filling
  21177. ;; We use our own fill-paragraph and auto-fill functions.
  21178. ;; `org-fill-paragraph' relies on adaptive filling and context
  21179. ;; checking. Appropriate `fill-prefix' is computed with
  21180. ;; `org-adaptive-fill-function'.
  21181. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21182. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21183. ;; `org-adaptive-fill-function' value. Internally,
  21184. ;; `org-comment-line-break-function' breaks the line.
  21185. ;; `org-setup-filling' installs filling and auto-filling related
  21186. ;; variables during `org-mode' initialization.
  21187. (defvar org-element-paragraph-separate) ; org-element.el
  21188. (defun org-setup-filling ()
  21189. (require 'org-element)
  21190. ;; Prevent auto-fill from inserting unwanted new items.
  21191. (when (boundp 'fill-nobreak-predicate)
  21192. (setq-local
  21193. fill-nobreak-predicate
  21194. (org-uniquify
  21195. (append fill-nobreak-predicate
  21196. '(org-fill-line-break-nobreak-p
  21197. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21198. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21199. (setq-local paragraph-start paragraph-ending)
  21200. (setq-local paragraph-separate paragraph-ending))
  21201. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21202. (setq-local auto-fill-inhibit-regexp nil)
  21203. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21204. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21205. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21206. (defun org-fill-line-break-nobreak-p ()
  21207. "Non-nil when a new line at point would create an Org line break."
  21208. (save-excursion
  21209. (skip-chars-backward "[ \t]")
  21210. (skip-chars-backward "\\\\")
  21211. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21212. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21213. "Non-nil when a new line at point would split a timestamp."
  21214. (and (org-at-timestamp-p t)
  21215. (not (looking-at org-ts-regexp-both))))
  21216. (declare-function message-in-body-p "message" ())
  21217. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21218. (defun org-adaptive-fill-function ()
  21219. "Compute a fill prefix for the current line.
  21220. Return fill prefix, as a string, or nil if current line isn't
  21221. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21222. matches in paragraphs or comments, use it."
  21223. (catch 'exit
  21224. (when (derived-mode-p 'message-mode)
  21225. (save-excursion
  21226. (beginning-of-line)
  21227. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21228. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21229. ((looking-at message-cite-prefix-regexp)
  21230. (throw 'exit (match-string-no-properties 0)))
  21231. ((looking-at org-outline-regexp)
  21232. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21233. (org-with-wide-buffer
  21234. (unless (org-at-heading-p)
  21235. (let* ((p (line-beginning-position))
  21236. (element (save-excursion
  21237. (beginning-of-line)
  21238. (org-element-at-point)))
  21239. (type (org-element-type element))
  21240. (post-affiliated (org-element-property :post-affiliated element)))
  21241. (unless (< p post-affiliated)
  21242. (cl-case type
  21243. (comment
  21244. (save-excursion
  21245. (beginning-of-line)
  21246. (looking-at "[ \t]*")
  21247. (concat (match-string 0) "# ")))
  21248. (footnote-definition "")
  21249. ((item plain-list)
  21250. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21251. (paragraph
  21252. ;; Fill prefix is usually the same as the current line,
  21253. ;; unless the paragraph is at the beginning of an item.
  21254. (let ((parent (org-element-property :parent element)))
  21255. (save-excursion
  21256. (beginning-of-line)
  21257. (cond ((eq (org-element-type parent) 'item)
  21258. (make-string (org-list-item-body-column
  21259. (org-element-property :begin parent))
  21260. ?\s))
  21261. ((and adaptive-fill-regexp
  21262. ;; Locally disable
  21263. ;; `adaptive-fill-function' to let
  21264. ;; `fill-context-prefix' handle
  21265. ;; `adaptive-fill-regexp' variable.
  21266. (let (adaptive-fill-function)
  21267. (fill-context-prefix
  21268. post-affiliated
  21269. (org-element-property :end element)))))
  21270. ((looking-at "[ \t]+") (match-string 0))
  21271. (t "")))))
  21272. (comment-block
  21273. ;; Only fill contents if P is within block boundaries.
  21274. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21275. (forward-line)
  21276. (point)))
  21277. (cend (save-excursion
  21278. (goto-char (org-element-property :end element))
  21279. (skip-chars-backward " \r\t\n")
  21280. (line-beginning-position))))
  21281. (when (and (>= p cbeg) (< p cend))
  21282. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21283. (match-string 0)
  21284. "")))))))))))
  21285. (declare-function message-goto-body "message" ())
  21286. (defvar message-cite-prefix-regexp) ; From message.el
  21287. (defun org-fill-paragraph (&optional justify)
  21288. "Fill element at point, when applicable.
  21289. This function only applies to comment blocks, comments, example
  21290. blocks and paragraphs. Also, as a special case, re-align table
  21291. when point is at one.
  21292. If JUSTIFY is non-nil (interactively, with prefix argument),
  21293. justify as well. If `sentence-end-double-space' is non-nil, then
  21294. period followed by one space does not end a sentence, so don't
  21295. break a line there. The variable `fill-column' controls the
  21296. width for filling.
  21297. For convenience, when point is at a plain list, an item or
  21298. a footnote definition, try to fill the first paragraph within."
  21299. (interactive)
  21300. (if (and (derived-mode-p 'message-mode)
  21301. (or (not (message-in-body-p))
  21302. (save-excursion (move-beginning-of-line 1)
  21303. (looking-at message-cite-prefix-regexp))))
  21304. ;; First ensure filling is correct in message-mode.
  21305. (let ((fill-paragraph-function
  21306. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21307. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21308. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21309. (paragraph-separate
  21310. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21311. (fill-paragraph nil))
  21312. (with-syntax-table org-mode-transpose-word-syntax-table
  21313. ;; Move to end of line in order to get the first paragraph
  21314. ;; within a plain list or a footnote definition.
  21315. (let ((element (save-excursion
  21316. (end-of-line)
  21317. (or (ignore-errors (org-element-at-point))
  21318. (user-error "An element cannot be parsed line %d"
  21319. (line-number-at-pos (point)))))))
  21320. ;; First check if point is in a blank line at the beginning of
  21321. ;; the buffer. In that case, ignore filling.
  21322. (cl-case (org-element-type element)
  21323. ;; Use major mode filling function is src blocks.
  21324. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21325. ;; Align Org tables, leave table.el tables as-is.
  21326. (table-row (org-table-align) t)
  21327. (table
  21328. (when (eq (org-element-property :type element) 'org)
  21329. (save-excursion
  21330. (goto-char (org-element-property :post-affiliated element))
  21331. (org-table-align)))
  21332. t)
  21333. (paragraph
  21334. ;; Paragraphs may contain `line-break' type objects.
  21335. (let ((beg (max (point-min)
  21336. (org-element-property :contents-begin element)))
  21337. (end (min (point-max)
  21338. (org-element-property :contents-end element))))
  21339. ;; Do nothing if point is at an affiliated keyword.
  21340. (if (< (line-end-position) beg) t
  21341. (when (derived-mode-p 'message-mode)
  21342. ;; In `message-mode', do not fill following citation
  21343. ;; in current paragraph nor text before message body.
  21344. (let ((body-start (save-excursion (message-goto-body))))
  21345. (when body-start (setq beg (max body-start beg))))
  21346. (when (save-excursion
  21347. (re-search-forward
  21348. (concat "^" message-cite-prefix-regexp) end t))
  21349. (setq end (match-beginning 0))))
  21350. ;; Fill paragraph, taking line breaks into account.
  21351. (save-excursion
  21352. (goto-char beg)
  21353. (let ((cuts (list beg)))
  21354. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21355. (when (eq 'line-break
  21356. (org-element-type
  21357. (save-excursion (backward-char)
  21358. (org-element-context))))
  21359. (push (point) cuts)))
  21360. (dolist (c (delq end cuts))
  21361. (fill-region-as-paragraph c end justify)
  21362. (setq end c))))
  21363. t)))
  21364. ;; Contents of `comment-block' type elements should be
  21365. ;; filled as plain text, but only if point is within block
  21366. ;; markers.
  21367. (comment-block
  21368. (let* ((case-fold-search t)
  21369. (beg (save-excursion
  21370. (goto-char (org-element-property :begin element))
  21371. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21372. (forward-line)
  21373. (point)))
  21374. (end (save-excursion
  21375. (goto-char (org-element-property :end element))
  21376. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21377. (line-beginning-position))))
  21378. (if (or (< (point) beg) (> (point) end)) t
  21379. (fill-region-as-paragraph
  21380. (save-excursion (end-of-line)
  21381. (re-search-backward "^[ \t]*$" beg 'move)
  21382. (line-beginning-position))
  21383. (save-excursion (beginning-of-line)
  21384. (re-search-forward "^[ \t]*$" end 'move)
  21385. (line-beginning-position))
  21386. justify))))
  21387. ;; Fill comments.
  21388. (comment
  21389. (let ((begin (org-element-property :post-affiliated element))
  21390. (end (org-element-property :end element)))
  21391. (when (and (>= (point) begin) (<= (point) end))
  21392. (let ((begin (save-excursion
  21393. (end-of-line)
  21394. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21395. (progn (forward-line) (point))
  21396. begin)))
  21397. (end (save-excursion
  21398. (end-of-line)
  21399. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21400. (1- (line-beginning-position))
  21401. (skip-chars-backward " \r\t\n")
  21402. (line-end-position)))))
  21403. ;; Do not fill comments when at a blank line.
  21404. (when (> end begin)
  21405. (let ((fill-prefix
  21406. (save-excursion
  21407. (beginning-of-line)
  21408. (looking-at "[ \t]*#")
  21409. (let ((comment-prefix (match-string 0)))
  21410. (goto-char (match-end 0))
  21411. (if (looking-at adaptive-fill-regexp)
  21412. (concat comment-prefix (match-string 0))
  21413. (concat comment-prefix " "))))))
  21414. (save-excursion
  21415. (fill-region-as-paragraph begin end justify))))))
  21416. t))
  21417. ;; Ignore every other element.
  21418. (otherwise t))))))
  21419. (defun org-auto-fill-function ()
  21420. "Auto-fill function."
  21421. ;; Check if auto-filling is meaningful.
  21422. (let ((fc (current-fill-column)))
  21423. (when (and fc (> (current-column) fc))
  21424. (let* ((fill-prefix (org-adaptive-fill-function))
  21425. ;; Enforce empty fill prefix, if required. Otherwise, it
  21426. ;; will be computed again.
  21427. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21428. (when fill-prefix (do-auto-fill))))))
  21429. (defun org-comment-line-break-function (&optional soft)
  21430. "Break line at point and indent, continuing comment if within one.
  21431. The inserted newline is marked hard if variable
  21432. `use-hard-newlines' is true, unless optional argument SOFT is
  21433. non-nil."
  21434. (if soft (insert-and-inherit ?\n) (newline 1))
  21435. (save-excursion (forward-char -1) (delete-horizontal-space))
  21436. (delete-horizontal-space)
  21437. (indent-to-left-margin)
  21438. (insert-before-markers-and-inherit fill-prefix))
  21439. ;;; Fixed Width Areas
  21440. (defun org-toggle-fixed-width ()
  21441. "Toggle fixed-width markup.
  21442. Add or remove fixed-width markup on current line, whenever it
  21443. makes sense. Return an error otherwise.
  21444. If a region is active and if it contains only fixed-width areas
  21445. or blank lines, remove all fixed-width markup in it. If the
  21446. region contains anything else, convert all non-fixed-width lines
  21447. to fixed-width ones.
  21448. Blank lines at the end of the region are ignored unless the
  21449. region only contains such lines."
  21450. (interactive)
  21451. (if (not (org-region-active-p))
  21452. ;; No region:
  21453. ;;
  21454. ;; Remove fixed width marker only in a fixed-with element.
  21455. ;;
  21456. ;; Add fixed width maker in paragraphs, in blank lines after
  21457. ;; elements or at the beginning of a headline or an inlinetask,
  21458. ;; and before any one-line elements (e.g., a clock).
  21459. (progn
  21460. (beginning-of-line)
  21461. (let* ((element (org-element-at-point))
  21462. (type (org-element-type element)))
  21463. (cond
  21464. ((and (eq type 'fixed-width)
  21465. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21466. (replace-match
  21467. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21468. ((and (memq type '(babel-call clock comment diary-sexp headline
  21469. horizontal-rule keyword paragraph
  21470. planning))
  21471. (<= (org-element-property :post-affiliated element) (point)))
  21472. (skip-chars-forward " \t")
  21473. (insert ": "))
  21474. ((and (looking-at-p "[ \t]*$")
  21475. (or (eq type 'inlinetask)
  21476. (save-excursion
  21477. (skip-chars-forward " \r\t\n")
  21478. (<= (org-element-property :end element) (point)))))
  21479. (delete-region (point) (line-end-position))
  21480. (org-indent-line)
  21481. (insert ": "))
  21482. (t (user-error "Cannot insert a fixed-width line here")))))
  21483. ;; Region active.
  21484. (let* ((begin (save-excursion
  21485. (goto-char (region-beginning))
  21486. (line-beginning-position)))
  21487. (end (copy-marker
  21488. (save-excursion
  21489. (goto-char (region-end))
  21490. (unless (eolp) (beginning-of-line))
  21491. (if (save-excursion (re-search-backward "\\S-" begin t))
  21492. (progn (skip-chars-backward " \r\t\n") (point))
  21493. (point)))))
  21494. (all-fixed-width-p
  21495. (catch 'not-all-p
  21496. (save-excursion
  21497. (goto-char begin)
  21498. (skip-chars-forward " \r\t\n")
  21499. (when (eobp) (throw 'not-all-p nil))
  21500. (while (< (point) end)
  21501. (let ((element (org-element-at-point)))
  21502. (if (eq (org-element-type element) 'fixed-width)
  21503. (goto-char (org-element-property :end element))
  21504. (throw 'not-all-p nil))))
  21505. t))))
  21506. (if all-fixed-width-p
  21507. (save-excursion
  21508. (goto-char begin)
  21509. (while (< (point) end)
  21510. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21511. (replace-match
  21512. "" nil nil nil
  21513. (if (= (line-end-position) (match-end 0)) 0 1)))
  21514. (forward-line)))
  21515. (let ((min-ind (point-max)))
  21516. ;; Find minimum indentation across all lines.
  21517. (save-excursion
  21518. (goto-char begin)
  21519. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21520. (setq min-ind 0)
  21521. (catch 'zerop
  21522. (while (< (point) end)
  21523. (unless (looking-at-p "[ \t]*$")
  21524. (let ((ind (org-get-indentation)))
  21525. (setq min-ind (min min-ind ind))
  21526. (when (zerop ind) (throw 'zerop t))))
  21527. (forward-line)))))
  21528. ;; Loop over all lines and add fixed-width markup everywhere
  21529. ;; but in fixed-width lines.
  21530. (save-excursion
  21531. (goto-char begin)
  21532. (while (< (point) end)
  21533. (cond
  21534. ((org-at-heading-p)
  21535. (insert ": ")
  21536. (forward-line)
  21537. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21538. (insert ":")
  21539. (forward-line)))
  21540. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21541. (let* ((element (org-element-at-point))
  21542. (element-end (org-element-property :end element)))
  21543. (if (eq (org-element-type element) 'fixed-width)
  21544. (progn (goto-char element-end)
  21545. (skip-chars-backward " \r\t\n")
  21546. (forward-line))
  21547. (let ((limit (min end element-end)))
  21548. (while (< (point) limit)
  21549. (org-move-to-column min-ind t)
  21550. (insert ": ")
  21551. (forward-line))))))
  21552. (t
  21553. (org-move-to-column min-ind t)
  21554. (insert ": ")
  21555. (forward-line)))))))
  21556. (set-marker end nil))))
  21557. ;;; Comments
  21558. ;; Org comments syntax is quite complex. It requires the entire line
  21559. ;; to be just a comment. Also, even with the right syntax at the
  21560. ;; beginning of line, some some elements (i.e. verse-block or
  21561. ;; example-block) don't accept comments. Usual Emacs comment commands
  21562. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21563. ;; Org still relies on `comment-dwim', but cannot trust
  21564. ;; `comment-only-p'. So, `comment-region-function' and
  21565. ;; `uncomment-region-function' both point
  21566. ;; to`org-comment-or-uncomment-region'. Eventually,
  21567. ;; `org-insert-comment' takes care of insertion of comments at the
  21568. ;; beginning of line.
  21569. ;; `org-setup-comments-handling' install comments related variables
  21570. ;; during `org-mode' initialization.
  21571. (defun org-setup-comments-handling ()
  21572. (interactive)
  21573. (setq-local comment-use-syntax nil)
  21574. (setq-local comment-start "# ")
  21575. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21576. (setq-local comment-insert-comment-function 'org-insert-comment)
  21577. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21578. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21579. (defun org-insert-comment ()
  21580. "Insert an empty comment above current line.
  21581. If the line is empty, insert comment at its beginning. When
  21582. point is within a source block, comment according to the related
  21583. major mode."
  21584. (if (let ((element (org-element-at-point)))
  21585. (and (eq (org-element-type element) 'src-block)
  21586. (< (save-excursion
  21587. (goto-char (org-element-property :post-affiliated element))
  21588. (line-end-position))
  21589. (point))
  21590. (> (save-excursion
  21591. (goto-char (org-element-property :end element))
  21592. (skip-chars-backward " \r\t\n")
  21593. (line-beginning-position))
  21594. (point))))
  21595. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21596. (beginning-of-line)
  21597. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21598. (open-line 1))
  21599. (org-indent-line)
  21600. (insert "# ")))
  21601. (defvar comment-empty-lines) ; From newcomment.el.
  21602. (defun org-comment-or-uncomment-region (beg end &rest _)
  21603. "Comment or uncomment each non-blank line in the region.
  21604. Uncomment each non-blank line between BEG and END if it only
  21605. contains commented lines. Otherwise, comment them. If region is
  21606. strictly within a source block, use appropriate comment syntax."
  21607. (if (let ((element (org-element-at-point)))
  21608. (and (eq (org-element-type element) 'src-block)
  21609. (< (save-excursion
  21610. (goto-char (org-element-property :post-affiliated element))
  21611. (line-end-position))
  21612. beg)
  21613. (>= (save-excursion
  21614. (goto-char (org-element-property :end element))
  21615. (skip-chars-backward " \r\t\n")
  21616. (line-beginning-position))
  21617. end)))
  21618. ;; Translate region boundaries for the Org buffer to the source
  21619. ;; buffer.
  21620. (let ((offset (- end beg)))
  21621. (save-excursion
  21622. (goto-char beg)
  21623. (org-babel-do-in-edit-buffer
  21624. (comment-or-uncomment-region (point) (+ offset (point))))))
  21625. (save-restriction
  21626. ;; Restrict region
  21627. (narrow-to-region (save-excursion (goto-char beg)
  21628. (skip-chars-forward " \r\t\n" end)
  21629. (line-beginning-position))
  21630. (save-excursion (goto-char end)
  21631. (skip-chars-backward " \r\t\n" beg)
  21632. (line-end-position)))
  21633. (let ((uncommentp
  21634. ;; UNCOMMENTP is non-nil when every non blank line between
  21635. ;; BEG and END is a comment.
  21636. (save-excursion
  21637. (goto-char (point-min))
  21638. (while (and (not (eobp))
  21639. (let ((element (org-element-at-point)))
  21640. (and (eq (org-element-type element) 'comment)
  21641. (goto-char (min (point-max)
  21642. (org-element-property
  21643. :end element)))))))
  21644. (eobp))))
  21645. (if uncommentp
  21646. ;; Only blank lines and comments in region: uncomment it.
  21647. (save-excursion
  21648. (goto-char (point-min))
  21649. (while (not (eobp))
  21650. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21651. (replace-match "" nil nil nil 1))
  21652. (forward-line)))
  21653. ;; Comment each line in region.
  21654. (let ((min-indent (point-max)))
  21655. ;; First find the minimum indentation across all lines.
  21656. (save-excursion
  21657. (goto-char (point-min))
  21658. (while (and (not (eobp)) (not (zerop min-indent)))
  21659. (unless (looking-at "[ \t]*$")
  21660. (setq min-indent (min min-indent (current-indentation))))
  21661. (forward-line)))
  21662. ;; Then loop over all lines.
  21663. (save-excursion
  21664. (goto-char (point-min))
  21665. (while (not (eobp))
  21666. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21667. ;; Don't get fooled by invisible text (e.g. link path)
  21668. ;; when moving to column MIN-INDENT.
  21669. (let ((buffer-invisibility-spec nil))
  21670. (org-move-to-column min-indent t))
  21671. (insert comment-start))
  21672. (forward-line)))))))))
  21673. (defun org-comment-dwim (_arg)
  21674. "Call `comment-dwim' within a source edit buffer if needed."
  21675. (interactive "*P")
  21676. (if (org-in-src-block-p)
  21677. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21678. (call-interactively 'comment-dwim)))
  21679. ;;; Timestamps API
  21680. ;; This section contains tools to operate on timestamp objects, as
  21681. ;; returned by, e.g. `org-element-context'.
  21682. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21683. "Encode TIMESTAMP object into Emacs internal time.
  21684. Use end of date range or time range when END is non-nil."
  21685. (apply #'encode-time
  21686. (cons 0
  21687. (mapcar
  21688. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21689. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21690. '(:minute-start :hour-start :day-start :month-start
  21691. :year-start))))))
  21692. (defun org-timestamp-has-time-p (timestamp)
  21693. "Non-nil when TIMESTAMP has a time specified."
  21694. (org-element-property :hour-start timestamp))
  21695. (defun org-timestamp-format (timestamp format &optional end utc)
  21696. "Format a TIMESTAMP object into a string.
  21697. FORMAT is a format specifier to be passed to
  21698. `format-time-string'.
  21699. When optional argument END is non-nil, use end of date-range or
  21700. time-range, if possible.
  21701. When optional argument UTC is non-nil, time will be expressed as
  21702. Universal Time."
  21703. (format-time-string
  21704. format (org-timestamp--to-internal-time timestamp end)
  21705. (and utc t)))
  21706. (defun org-timestamp-split-range (timestamp &optional end)
  21707. "Extract a TIMESTAMP object from a date or time range.
  21708. END, when non-nil, means extract the end of the range.
  21709. Otherwise, extract its start.
  21710. Return a new timestamp object."
  21711. (let ((type (org-element-property :type timestamp)))
  21712. (if (memq type '(active inactive diary)) timestamp
  21713. (let ((split-ts (org-element-copy timestamp)))
  21714. ;; Set new type.
  21715. (org-element-put-property
  21716. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21717. ;; Copy start properties over end properties if END is
  21718. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21719. (let ((p-alist '((:minute-start . :minute-end)
  21720. (:hour-start . :hour-end)
  21721. (:day-start . :day-end)
  21722. (:month-start . :month-end)
  21723. (:year-start . :year-end))))
  21724. (dolist (p-cell p-alist)
  21725. (org-element-put-property
  21726. split-ts
  21727. (funcall (if end #'car #'cdr) p-cell)
  21728. (org-element-property
  21729. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21730. ;; Eventually refresh `:raw-value'.
  21731. (org-element-put-property split-ts :raw-value nil)
  21732. (org-element-put-property
  21733. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21734. (defun org-timestamp-translate (timestamp &optional boundary)
  21735. "Translate TIMESTAMP object to custom format.
  21736. Format string is defined in `org-time-stamp-custom-formats',
  21737. which see.
  21738. When optional argument BOUNDARY is non-nil, it is either the
  21739. symbol `start' or `end'. In this case, only translate the
  21740. starting or ending part of TIMESTAMP if it is a date or time
  21741. range. Otherwise, translate both parts.
  21742. Return timestamp as-is if `org-display-custom-times' is nil or if
  21743. it has a `diary' type."
  21744. (let ((type (org-element-property :type timestamp)))
  21745. (if (or (not org-display-custom-times) (eq type 'diary))
  21746. (org-element-interpret-data timestamp)
  21747. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21748. org-time-stamp-custom-formats)))
  21749. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21750. (concat (org-timestamp-format timestamp fmt)
  21751. "--"
  21752. (org-timestamp-format timestamp fmt t))
  21753. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21754. ;;; Other stuff.
  21755. (defvar reftex-docstruct-symbol)
  21756. (defvar org--rds)
  21757. (defun org-reftex-citation ()
  21758. "Use reftex-citation to insert a citation into the buffer.
  21759. This looks for a line like
  21760. #+BIBLIOGRAPHY: foo plain option:-d
  21761. and derives from it that foo.bib is the bibliography file relevant
  21762. for this document. It then installs the necessary environment for RefTeX
  21763. to work in this buffer and calls `reftex-citation' to insert a citation
  21764. into the buffer.
  21765. Export of such citations to both LaTeX and HTML is handled by the contributed
  21766. package ox-bibtex by Taru Karttunen."
  21767. (interactive)
  21768. (let ((reftex-docstruct-symbol 'org--rds)
  21769. org--rds bib)
  21770. (org-with-wide-buffer
  21771. (let ((case-fold-search t)
  21772. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21773. (if (not (save-excursion
  21774. (or (re-search-forward re nil t)
  21775. (re-search-backward re nil t))))
  21776. (user-error "No bibliography defined in file")
  21777. (setq bib (concat (match-string 1) ".bib")
  21778. org--rds (list (list 'bib bib))))))
  21779. (call-interactively 'reftex-citation)))
  21780. ;;;; Functions extending outline functionality
  21781. (defun org-beginning-of-line (&optional n)
  21782. "Go to the beginning of the current visible line.
  21783. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21784. tags on the first attempt, and only move to after the tags when
  21785. the cursor is already beyond the end of the headline.
  21786. With argument N not nil or 1, move forward N - 1 lines first."
  21787. (interactive "^p")
  21788. (let ((origin (point))
  21789. (special (pcase org-special-ctrl-a/e
  21790. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21791. deactivate-mark)
  21792. ;; First move to a visible line.
  21793. (if (bound-and-true-p visual-line-mode)
  21794. (beginning-of-visual-line n)
  21795. (move-beginning-of-line n)
  21796. ;; `move-beginning-of-line' may leave point after invisible
  21797. ;; characters if line starts with such of these (e.g., with
  21798. ;; a link at column 0). Really move to the beginning of the
  21799. ;; current visible line.
  21800. (beginning-of-line))
  21801. (cond
  21802. ;; No special behavior. Point is already at the beginning of
  21803. ;; a line, logical or visual.
  21804. ((not special))
  21805. ;; `beginning-of-visual-line' left point before logical beginning
  21806. ;; of line: point is at the beginning of a visual line. Bail
  21807. ;; out.
  21808. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21809. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21810. ;; At a headline, special position is before the title, but
  21811. ;; after any TODO keyword or priority cookie.
  21812. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21813. (line-end-position)))
  21814. (bol (point)))
  21815. (if (eq special 'reversed)
  21816. (when (and (= origin bol) (eq last-command this-command))
  21817. (goto-char refpos))
  21818. (when (or (> origin refpos) (= origin bol))
  21819. (goto-char refpos)))))
  21820. ((and (looking-at org-list-full-item-re)
  21821. (memq (org-element-type (save-match-data (org-element-at-point)))
  21822. '(item plain-list)))
  21823. ;; Set special position at first white space character after
  21824. ;; bullet, and check-box, if any.
  21825. (let ((after-bullet
  21826. (let ((box (match-end 3)))
  21827. (cond ((not box) (match-end 1))
  21828. ((eq (char-after box) ?\s) (1+ box))
  21829. (t box)))))
  21830. (if (eq special 'reversed)
  21831. (when (and (= (point) origin) (eq last-command this-command))
  21832. (goto-char after-bullet))
  21833. (when (or (> origin after-bullet) (= (point) origin))
  21834. (goto-char after-bullet)))))
  21835. ;; No special context. Point is already at beginning of line.
  21836. (t nil))))
  21837. (defun org-end-of-line (&optional n)
  21838. "Go to the end of the line, but before ellipsis, if any.
  21839. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21840. tags on the first attempt, and only move to after the tags when
  21841. the cursor is already beyond the end of the headline.
  21842. With argument N not nil or 1, move forward N - 1 lines first."
  21843. (interactive "^p")
  21844. (let ((origin (point))
  21845. (special (pcase org-special-ctrl-a/e
  21846. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21847. deactivate-mark)
  21848. ;; First move to a visible line.
  21849. (if (bound-and-true-p visual-line-mode)
  21850. (beginning-of-visual-line n)
  21851. (move-beginning-of-line n))
  21852. (cond
  21853. ;; At a headline, with tags.
  21854. ((and special
  21855. (save-excursion
  21856. (beginning-of-line)
  21857. (let ((case-fold-search nil))
  21858. (looking-at org-complex-heading-regexp)))
  21859. (match-end 5))
  21860. (let ((tags (save-excursion
  21861. (goto-char (match-beginning 5))
  21862. (skip-chars-backward " \t")
  21863. (point)))
  21864. (visual-end (and (bound-and-true-p visual-line-mode)
  21865. (save-excursion
  21866. (end-of-visual-line)
  21867. (point)))))
  21868. ;; If `end-of-visual-line' brings us before end of line or
  21869. ;; even tags, i.e., the headline spans over multiple visual
  21870. ;; lines, move there.
  21871. (cond ((and visual-end
  21872. (< visual-end tags)
  21873. (<= origin visual-end))
  21874. (goto-char visual-end))
  21875. ((eq special 'reversed)
  21876. (if (and (= origin (line-end-position))
  21877. (eq this-command last-command))
  21878. (goto-char tags)
  21879. (end-of-line)))
  21880. (t
  21881. (if (or (< origin tags) (= origin (line-end-position)))
  21882. (goto-char tags)
  21883. (end-of-line))))))
  21884. ((bound-and-true-p visual-line-mode)
  21885. (let ((bol (line-beginning-position)))
  21886. (end-of-visual-line)
  21887. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21888. ;; end of a line, backtrack and use `end-of-line' instead.
  21889. (when (/= bol (line-beginning-position))
  21890. (goto-char bol)
  21891. (end-of-line))))
  21892. (t (end-of-line)))))
  21893. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21894. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21895. (defun org-backward-sentence (&optional _arg)
  21896. "Go to beginning of sentence, or beginning of table field.
  21897. This will call `backward-sentence' or `org-table-beginning-of-field',
  21898. depending on context."
  21899. (interactive)
  21900. (let* ((element (org-element-at-point))
  21901. (contents-begin (org-element-property :contents-begin element))
  21902. (table (org-element-lineage element '(table) t)))
  21903. (if (and table
  21904. (> (point) contents-begin)
  21905. (<= (point) (org-element-property :contents-end table)))
  21906. (call-interactively #'org-table-beginning-of-field)
  21907. (save-restriction
  21908. (when (and contents-begin
  21909. (< (point-min) contents-begin)
  21910. (> (point) contents-begin))
  21911. (narrow-to-region contents-begin
  21912. (org-element-property :contents-end element)))
  21913. (call-interactively #'backward-sentence)))))
  21914. (defun org-forward-sentence (&optional _arg)
  21915. "Go to end of sentence, or end of table field.
  21916. This will call `forward-sentence' or `org-table-end-of-field',
  21917. depending on context."
  21918. (interactive)
  21919. (let* ((element (org-element-at-point))
  21920. (contents-end (org-element-property :contents-end element))
  21921. (table (org-element-lineage element '(table) t)))
  21922. (if (and table
  21923. (>= (point) (org-element-property :contents-begin table))
  21924. (< (point) contents-end))
  21925. (call-interactively #'org-table-end-of-field)
  21926. (save-restriction
  21927. (when (and contents-end
  21928. (> (point-max) contents-end)
  21929. ;; Skip blank lines between elements.
  21930. (< (org-element-property :end element)
  21931. (save-excursion (goto-char contents-end)
  21932. (skip-chars-forward " \r\t\n"))))
  21933. (narrow-to-region (org-element-property :contents-begin element)
  21934. contents-end))
  21935. (call-interactively #'forward-sentence)))))
  21936. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21937. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21938. (defun org-kill-line (&optional _arg)
  21939. "Kill line, to tags or end of line."
  21940. (interactive)
  21941. (cond
  21942. ((or (not org-special-ctrl-k)
  21943. (bolp)
  21944. (not (org-at-heading-p)))
  21945. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21946. org-ctrl-k-protect-subtree
  21947. (or (eq org-ctrl-k-protect-subtree 'error)
  21948. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21949. (user-error "C-k aborted as it would kill a hidden subtree"))
  21950. (call-interactively
  21951. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21952. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21953. (kill-region (point) (match-beginning 1))
  21954. (org-set-tags nil t))
  21955. (t (kill-region (point) (point-at-eol)))))
  21956. (define-key org-mode-map "\C-k" 'org-kill-line)
  21957. (defun org-yank (&optional arg)
  21958. "Yank. If the kill is a subtree, treat it specially.
  21959. This command will look at the current kill and check if is a single
  21960. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21961. cursor is at the beginning of a line or after the stars of a currently
  21962. empty headline, then the yank is handled specially. How exactly depends
  21963. on the value of the following variables.
  21964. `org-yank-folded-subtrees'
  21965. By default, this variable is non-nil, which results in
  21966. subtree(s) being folded after insertion, except if doing so
  21967. would swallow text after the yanked text.
  21968. `org-yank-adjusted-subtrees'
  21969. When non-nil (the default value is nil), the subtree will be
  21970. promoted or demoted in order to fit into the local outline tree
  21971. structure, which means that the level will be adjusted so that it
  21972. becomes the smaller one of the two *visible* surrounding headings.
  21973. Any prefix to this command will cause `yank' to be called directly with
  21974. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21975. will just
  21976. plainly yank the text as it is.
  21977. \[1] The test checks if the first non-white line is a heading
  21978. and if there are no other headings with fewer stars."
  21979. (interactive "P")
  21980. (org-yank-generic 'yank arg))
  21981. (defun org-yank-generic (command arg)
  21982. "Perform some yank-like command.
  21983. This function implements the behavior described in the `org-yank'
  21984. documentation. However, it has been generalized to work for any
  21985. interactive command with similar behavior."
  21986. ;; pretend to be command COMMAND
  21987. (setq this-command command)
  21988. (if arg
  21989. (call-interactively command)
  21990. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21991. (and (org-kill-is-subtree-p)
  21992. (or (bolp)
  21993. (and (looking-at "[ \t]*$")
  21994. (string-match
  21995. "\\`\\*+\\'"
  21996. (buffer-substring (point-at-bol) (point)))))))
  21997. swallowp)
  21998. (cond
  21999. ((and subtreep org-yank-folded-subtrees)
  22000. (let ((beg (point))
  22001. end)
  22002. (if (and subtreep org-yank-adjusted-subtrees)
  22003. (org-paste-subtree nil nil 'for-yank)
  22004. (call-interactively command))
  22005. (setq end (point))
  22006. (goto-char beg)
  22007. (when (and (bolp) subtreep
  22008. (not (setq swallowp
  22009. (org-yank-folding-would-swallow-text beg end))))
  22010. (org-with-limited-levels
  22011. (or (looking-at org-outline-regexp)
  22012. (re-search-forward org-outline-regexp-bol end t))
  22013. (while (and (< (point) end) (looking-at org-outline-regexp))
  22014. (outline-hide-subtree)
  22015. (org-cycle-show-empty-lines 'folded)
  22016. (condition-case nil
  22017. (outline-forward-same-level 1)
  22018. (error (goto-char end))))))
  22019. (when swallowp
  22020. (message
  22021. "Inserted text not folded because that would swallow text"))
  22022. (goto-char end)
  22023. (skip-chars-forward " \t\n\r")
  22024. (beginning-of-line 1)
  22025. (push-mark beg 'nomsg)))
  22026. ((and subtreep org-yank-adjusted-subtrees)
  22027. (let ((beg (point-at-bol)))
  22028. (org-paste-subtree nil nil 'for-yank)
  22029. (push-mark beg 'nomsg)))
  22030. (t
  22031. (call-interactively command))))))
  22032. (defun org-yank-folding-would-swallow-text (beg end)
  22033. "Would hide-subtree at BEG swallow any text after END?"
  22034. (let (level)
  22035. (org-with-limited-levels
  22036. (save-excursion
  22037. (goto-char beg)
  22038. (when (or (looking-at org-outline-regexp)
  22039. (re-search-forward org-outline-regexp-bol end t))
  22040. (setq level (org-outline-level)))
  22041. (goto-char end)
  22042. (skip-chars-forward " \t\r\n\v\f")
  22043. (not (or (eobp)
  22044. (and (bolp) (looking-at-p org-outline-regexp)
  22045. (<= (org-outline-level) level))))))))
  22046. (define-key org-mode-map "\C-y" 'org-yank)
  22047. (defun org-truely-invisible-p ()
  22048. "Check if point is at a character currently not visible.
  22049. This version does not only check the character property, but also
  22050. `visible-mode'."
  22051. ;; Early versions of noutline don't have `outline-invisible-p'.
  22052. (unless (bound-and-true-p visible-mode)
  22053. (outline-invisible-p)))
  22054. (defun org-invisible-p2 ()
  22055. "Check if point is at a character currently not visible."
  22056. (save-excursion
  22057. (when (and (eolp) (not (bobp))) (backward-char 1))
  22058. ;; Early versions of noutline don't have `outline-invisible-p'.
  22059. (outline-invisible-p)))
  22060. (defun org-back-to-heading (&optional invisible-ok)
  22061. "Call `outline-back-to-heading', but provide a better error message."
  22062. (condition-case nil
  22063. (outline-back-to-heading invisible-ok)
  22064. (error (error "Before first headline at position %d in buffer %s"
  22065. (point) (current-buffer)))))
  22066. (defun org-before-first-heading-p ()
  22067. "Before first heading?"
  22068. (save-excursion
  22069. (end-of-line)
  22070. (null (re-search-backward org-outline-regexp-bol nil t))))
  22071. (defun org-at-heading-p (&optional ignored)
  22072. (outline-on-heading-p t))
  22073. (defun org-in-commented-heading-p (&optional no-inheritance)
  22074. "Non-nil if point is under a commented heading.
  22075. This function also checks ancestors of the current headline,
  22076. unless optional argument NO-INHERITANCE is non-nil."
  22077. (cond
  22078. ((org-before-first-heading-p) nil)
  22079. ((let ((headline (nth 4 (org-heading-components))))
  22080. (and headline
  22081. (let ((case-fold-search nil))
  22082. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22083. headline)))))
  22084. (no-inheritance nil)
  22085. (t
  22086. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22087. (defun org-at-comment-p nil
  22088. "Is cursor in a commented line?"
  22089. (save-excursion
  22090. (save-match-data
  22091. (beginning-of-line)
  22092. (looking-at "^[ \t]*# "))))
  22093. (defun org-at-drawer-p nil
  22094. "Is cursor at a drawer keyword?"
  22095. (save-excursion
  22096. (move-beginning-of-line 1)
  22097. (looking-at org-drawer-regexp)))
  22098. (defun org-at-block-p nil
  22099. "Is cursor at a block keyword?"
  22100. (save-excursion
  22101. (move-beginning-of-line 1)
  22102. (looking-at org-block-regexp)))
  22103. (defun org-point-at-end-of-empty-headline ()
  22104. "If point is at the end of an empty headline, return t, else nil.
  22105. If the heading only contains a TODO keyword, it is still still considered
  22106. empty."
  22107. (let ((case-fold-search nil))
  22108. (and (looking-at "[ \t]*$")
  22109. org-todo-line-regexp
  22110. (save-excursion
  22111. (beginning-of-line)
  22112. (looking-at org-todo-line-regexp)
  22113. (string= (match-string 3) "")))))
  22114. (defun org-at-heading-or-item-p ()
  22115. (or (org-at-heading-p) (org-at-item-p)))
  22116. (defun org-at-target-p ()
  22117. (or (org-in-regexp org-radio-target-regexp)
  22118. (org-in-regexp org-target-regexp)))
  22119. ;; Compatibility alias with Org versions < 7.8.03
  22120. (defalias 'org-on-target-p 'org-at-target-p)
  22121. (defun org-up-heading-all (arg)
  22122. "Move to the heading line of which the present line is a subheading.
  22123. This function considers both visible and invisible heading lines.
  22124. With argument, move up ARG levels."
  22125. (outline-up-heading arg t))
  22126. (defun org-up-heading-safe ()
  22127. "Move to the heading line of which the present line is a subheading.
  22128. This version will not throw an error. It will return the level of the
  22129. headline found, or nil if no higher level is found.
  22130. Also, this function will be a lot faster than `outline-up-heading',
  22131. because it relies on stars being the outline starters. This can really
  22132. make a significant difference in outlines with very many siblings."
  22133. (when (ignore-errors (org-back-to-heading t))
  22134. (let ((level-up (1- (funcall outline-level))))
  22135. (and (> level-up 0)
  22136. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22137. (funcall outline-level)))))
  22138. (defun org-first-sibling-p ()
  22139. "Is this heading the first child of its parents?"
  22140. (interactive)
  22141. (let ((re org-outline-regexp-bol)
  22142. level l)
  22143. (unless (org-at-heading-p t)
  22144. (user-error "Not at a heading"))
  22145. (setq level (funcall outline-level))
  22146. (save-excursion
  22147. (if (not (re-search-backward re nil t))
  22148. t
  22149. (setq l (funcall outline-level))
  22150. (< l level)))))
  22151. (defun org-goto-sibling (&optional previous)
  22152. "Goto the next sibling, even if it is invisible.
  22153. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22154. when a sibling was found. When none is found, return nil and don't
  22155. move point."
  22156. (let ((fun (if previous 're-search-backward 're-search-forward))
  22157. (pos (point))
  22158. (re org-outline-regexp-bol)
  22159. level l)
  22160. (when (ignore-errors (org-back-to-heading t))
  22161. (setq level (funcall outline-level))
  22162. (catch 'exit
  22163. (or previous (forward-char 1))
  22164. (while (funcall fun re nil t)
  22165. (setq l (funcall outline-level))
  22166. (when (< l level) (goto-char pos) (throw 'exit nil))
  22167. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22168. (goto-char pos)
  22169. nil))))
  22170. (defun org-show-siblings ()
  22171. "Show all siblings of the current headline."
  22172. (save-excursion
  22173. (while (org-goto-sibling) (org-flag-heading nil)))
  22174. (save-excursion
  22175. (while (org-goto-sibling 'previous)
  22176. (org-flag-heading nil))))
  22177. (defun org-goto-first-child ()
  22178. "Goto the first child, even if it is invisible.
  22179. Return t when a child was found. Otherwise don't move point and
  22180. return nil."
  22181. (let (level (pos (point)) (re org-outline-regexp-bol))
  22182. (when (ignore-errors (org-back-to-heading t))
  22183. (setq level (outline-level))
  22184. (forward-char 1)
  22185. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22186. (progn (goto-char (match-beginning 0)) t)
  22187. (goto-char pos) nil))))
  22188. (defun org-show-hidden-entry ()
  22189. "Show an entry where even the heading is hidden."
  22190. (save-excursion
  22191. (org-show-entry)))
  22192. (defun org-flag-heading (flag &optional entry)
  22193. "Flag the current heading. FLAG non-nil means make invisible.
  22194. When ENTRY is non-nil, show the entire entry."
  22195. (save-excursion
  22196. (org-back-to-heading t)
  22197. ;; Check if we should show the entire entry
  22198. (if entry
  22199. (progn
  22200. (org-show-entry)
  22201. (save-excursion
  22202. (and (outline-next-heading)
  22203. (org-flag-heading nil))))
  22204. (outline-flag-region (max (point-min) (1- (point)))
  22205. (save-excursion (outline-end-of-heading) (point))
  22206. flag))))
  22207. (defun org-get-next-sibling ()
  22208. "Move to next heading of the same level, and return point.
  22209. If there is no such heading, return nil.
  22210. This is like outline-next-sibling, but invisible headings are ok."
  22211. (let ((level (funcall outline-level)))
  22212. (outline-next-heading)
  22213. (while (and (not (eobp)) (> (funcall outline-level) level))
  22214. (outline-next-heading))
  22215. (unless (or (eobp) (< (funcall outline-level) level))
  22216. (point))))
  22217. (defun org-get-last-sibling ()
  22218. "Move to previous heading of the same level, and return point.
  22219. If there is no such heading, return nil."
  22220. (let ((opoint (point))
  22221. (level (funcall outline-level)))
  22222. (outline-previous-heading)
  22223. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22224. (while (and (> (funcall outline-level) level)
  22225. (not (bobp)))
  22226. (outline-previous-heading))
  22227. (unless (< (funcall outline-level) level)
  22228. (point)))))
  22229. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22230. "Goto to the end of a subtree."
  22231. ;; This contains an exact copy of the original function, but it uses
  22232. ;; `org-back-to-heading', to make it work also in invisible
  22233. ;; trees. And is uses an invisible-ok argument.
  22234. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22235. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22236. ;; with many children and grandchildren etc, this can be much faster
  22237. ;; than the outline version.
  22238. (org-back-to-heading invisible-ok)
  22239. (let ((first t)
  22240. (level (funcall outline-level)))
  22241. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22242. ;; A true heading (not a plain list item), in Org
  22243. ;; This means we can easily find the end by looking
  22244. ;; only for the right number of stars. Using a regexp to do
  22245. ;; this is so much faster than using a Lisp loop.
  22246. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22247. (forward-char 1)
  22248. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22249. ;; something else, do it the slow way
  22250. (while (and (not (eobp))
  22251. (or first (> (funcall outline-level) level)))
  22252. (setq first nil)
  22253. (outline-next-heading)))
  22254. (unless to-heading
  22255. (when (memq (preceding-char) '(?\n ?\^M))
  22256. ;; Go to end of line before heading
  22257. (forward-char -1)
  22258. (when (memq (preceding-char) '(?\n ?\^M))
  22259. ;; leave blank line before heading
  22260. (forward-char -1)))))
  22261. (point))
  22262. (defun org-end-of-meta-data (&optional full)
  22263. "Skip planning line and properties drawer in current entry.
  22264. When optional argument FULL is non-nil, also skip empty lines,
  22265. clocking lines and regular drawers at the beginning of the
  22266. entry."
  22267. (org-back-to-heading t)
  22268. (forward-line)
  22269. (when (looking-at-p org-planning-line-re) (forward-line))
  22270. (when (looking-at org-property-drawer-re)
  22271. (goto-char (match-end 0))
  22272. (forward-line))
  22273. (when (and full (not (org-at-heading-p)))
  22274. (catch 'exit
  22275. (let ((end (save-excursion (outline-next-heading) (point)))
  22276. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22277. (while (not (eobp))
  22278. (cond ((looking-at-p org-drawer-regexp)
  22279. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22280. (forward-line)
  22281. (throw 'exit t)))
  22282. ((looking-at-p re) (forward-line))
  22283. (t (throw 'exit t))))))))
  22284. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22285. "Move forward to the ARG'th subheading at same level as this one.
  22286. Stop at the first and last subheadings of a superior heading.
  22287. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22288. non-nil it will also look at invisible ones."
  22289. (interactive "p")
  22290. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22291. (if (and arg (< arg 0))
  22292. (goto-char (point-min))
  22293. (outline-next-heading))
  22294. (org-at-heading-p)
  22295. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22296. (f (if (and arg (< arg 0))
  22297. 're-search-backward
  22298. 're-search-forward))
  22299. (count (if arg (abs arg) 1))
  22300. (result (point)))
  22301. (while (and (prog1 (> count 0)
  22302. (forward-char (if (and arg (< arg 0)) -1 1)))
  22303. (funcall f org-outline-regexp-bol nil 'move))
  22304. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22305. (cond ((< l level) (setq count 0))
  22306. ((and (= l level)
  22307. (or invisible-ok
  22308. (progn
  22309. (goto-char (line-beginning-position))
  22310. (not (outline-invisible-p)))))
  22311. (setq count (1- count))
  22312. (when (eq l level)
  22313. (setq result (point)))))))
  22314. (goto-char result))
  22315. (beginning-of-line 1)))
  22316. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22317. "Move backward to the ARG'th subheading at same level as this one.
  22318. Stop at the first and last subheadings of a superior heading."
  22319. (interactive "p")
  22320. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22321. (defun org-next-visible-heading (arg)
  22322. "Move to the next visible heading.
  22323. This function wraps `outline-next-visible-heading' with
  22324. `org-with-limited-levels' in order to skip over inline tasks and
  22325. respect customization of `org-odd-levels-only'."
  22326. (interactive "p")
  22327. (org-with-limited-levels
  22328. (outline-next-visible-heading arg)))
  22329. (defun org-previous-visible-heading (arg)
  22330. "Move to the previous visible heading.
  22331. This function wraps `outline-previous-visible-heading' with
  22332. `org-with-limited-levels' in order to skip over inline tasks and
  22333. respect customization of `org-odd-levels-only'."
  22334. (interactive "p")
  22335. (org-with-limited-levels
  22336. (outline-previous-visible-heading arg)))
  22337. (defun org-next-block (arg &optional backward block-regexp)
  22338. "Jump to the next block.
  22339. With a prefix argument ARG, jump forward ARG many blocks.
  22340. When BACKWARD is non-nil, jump to the previous block.
  22341. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22342. Match data is set according to this regexp when the function
  22343. returns.
  22344. Return point at beginning of the opening line of found block.
  22345. Throw an error if no block is found."
  22346. (interactive "p")
  22347. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22348. (case-fold-search t)
  22349. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22350. (count (or arg 1))
  22351. (origin (point))
  22352. last-element)
  22353. (if backward (beginning-of-line) (end-of-line))
  22354. (while (and (> count 0) (funcall search-fn re nil t))
  22355. (let ((element (save-excursion
  22356. (goto-char (match-beginning 0))
  22357. (save-match-data (org-element-at-point)))))
  22358. (when (and (memq (org-element-type element)
  22359. '(center-block comment-block dynamic-block
  22360. example-block export-block quote-block
  22361. special-block src-block verse-block))
  22362. (<= (match-beginning 0)
  22363. (org-element-property :post-affiliated element)))
  22364. (setq last-element element)
  22365. (cl-decf count))))
  22366. (if (= count 0)
  22367. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22368. (save-match-data (org-show-context)))
  22369. (goto-char origin)
  22370. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22371. (defun org-previous-block (arg &optional block-regexp)
  22372. "Jump to the previous block.
  22373. With a prefix argument ARG, jump backward ARG many source blocks.
  22374. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22375. (interactive "p")
  22376. (org-next-block arg t block-regexp))
  22377. (defun org-forward-paragraph ()
  22378. "Move forward to beginning of next paragraph or equivalent.
  22379. The function moves point to the beginning of the next visible
  22380. structural element, which can be a paragraph, a table, a list
  22381. item, etc. It also provides some special moves for convenience:
  22382. - On an affiliated keyword, jump to the beginning of the
  22383. relative element.
  22384. - On an item or a footnote definition, move to the second
  22385. element inside, if any.
  22386. - On a table or a property drawer, jump after it.
  22387. - On a verse or source block, stop after blank lines."
  22388. (interactive)
  22389. (when (eobp) (user-error "Cannot move further down"))
  22390. (let* ((deactivate-mark nil)
  22391. (element (org-element-at-point))
  22392. (type (org-element-type element))
  22393. (post-affiliated (org-element-property :post-affiliated element))
  22394. (contents-begin (org-element-property :contents-begin element))
  22395. (contents-end (org-element-property :contents-end element))
  22396. (end (let ((end (org-element-property :end element)) (parent element))
  22397. (while (and (setq parent (org-element-property :parent parent))
  22398. (= (org-element-property :contents-end parent) end))
  22399. (setq end (org-element-property :end parent)))
  22400. end)))
  22401. (cond ((not element)
  22402. (skip-chars-forward " \r\t\n")
  22403. (or (eobp) (beginning-of-line)))
  22404. ;; On affiliated keywords, move to element's beginning.
  22405. ((< (point) post-affiliated)
  22406. (goto-char post-affiliated))
  22407. ;; At a table row, move to the end of the table. Similarly,
  22408. ;; at a node property, move to the end of the property
  22409. ;; drawer.
  22410. ((memq type '(node-property table-row))
  22411. (goto-char (org-element-property
  22412. :end (org-element-property :parent element))))
  22413. ((memq type '(property-drawer table)) (goto-char end))
  22414. ;; Consider blank lines as separators in verse and source
  22415. ;; blocks to ease editing.
  22416. ((memq type '(src-block verse-block))
  22417. (when (eq type 'src-block)
  22418. (setq contents-end
  22419. (save-excursion (goto-char end)
  22420. (skip-chars-backward " \r\t\n")
  22421. (line-beginning-position))))
  22422. (beginning-of-line)
  22423. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22424. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22425. (goto-char end)
  22426. (skip-chars-forward " \r\t\n")
  22427. (if (= (point) contents-end) (goto-char end)
  22428. (beginning-of-line))))
  22429. ;; With no contents, just skip element.
  22430. ((not contents-begin) (goto-char end))
  22431. ;; If contents are invisible, skip the element altogether.
  22432. ((outline-invisible-p (line-end-position))
  22433. (cl-case type
  22434. (headline
  22435. (org-with-limited-levels (outline-next-visible-heading 1)))
  22436. ;; At a plain list, make sure we move to the next item
  22437. ;; instead of skipping the whole list.
  22438. (plain-list (forward-char)
  22439. (org-forward-paragraph))
  22440. (otherwise (goto-char end))))
  22441. ((>= (point) contents-end) (goto-char end))
  22442. ((>= (point) contents-begin)
  22443. ;; This can only happen on paragraphs and plain lists.
  22444. (cl-case type
  22445. (paragraph (goto-char end))
  22446. ;; At a plain list, try to move to second element in
  22447. ;; first item, if possible.
  22448. (plain-list (end-of-line)
  22449. (org-forward-paragraph))))
  22450. ;; When contents start on the middle of a line (e.g. in
  22451. ;; items and footnote definitions), try to reach first
  22452. ;; element starting after current line.
  22453. ((> (line-end-position) contents-begin)
  22454. (end-of-line)
  22455. (org-forward-paragraph))
  22456. (t (goto-char contents-begin)))))
  22457. (defun org-backward-paragraph ()
  22458. "Move backward to start of previous paragraph or equivalent.
  22459. The function moves point to the beginning of the current
  22460. structural element, which can be a paragraph, a table, a list
  22461. item, etc., or to the beginning of the previous visible one if
  22462. point is already there. It also provides some special moves for
  22463. convenience:
  22464. - On an affiliated keyword, jump to the first one.
  22465. - On a table or a property drawer, move to its beginning.
  22466. - On a verse or source block, stop before blank lines."
  22467. (interactive)
  22468. (when (bobp) (user-error "Cannot move further up"))
  22469. (let* ((deactivate-mark nil)
  22470. (element (org-element-at-point))
  22471. (type (org-element-type element))
  22472. (contents-begin (org-element-property :contents-begin element))
  22473. (contents-end (org-element-property :contents-end element))
  22474. (post-affiliated (org-element-property :post-affiliated element))
  22475. (begin (org-element-property :begin element)))
  22476. (cond
  22477. ((not element) (goto-char (point-min)))
  22478. ((= (point) begin)
  22479. (backward-char)
  22480. (org-backward-paragraph))
  22481. ((<= (point) post-affiliated) (goto-char begin))
  22482. ((memq type '(node-property table-row))
  22483. (goto-char (org-element-property
  22484. :post-affiliated (org-element-property :parent element))))
  22485. ((memq type '(property-drawer table)) (goto-char begin))
  22486. ((memq type '(src-block verse-block))
  22487. (when (eq type 'src-block)
  22488. (setq contents-begin
  22489. (save-excursion (goto-char begin) (forward-line) (point))))
  22490. (if (= (point) contents-begin) (goto-char post-affiliated)
  22491. ;; Inside a verse block, see blank lines as paragraph
  22492. ;; separators.
  22493. (let ((origin (point)))
  22494. (skip-chars-backward " \r\t\n" contents-begin)
  22495. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22496. (skip-chars-forward " \r\t\n" origin)
  22497. (if (= (point) origin) (goto-char contents-begin)
  22498. (beginning-of-line))))))
  22499. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22500. ((eq type 'paragraph)
  22501. (goto-char contents-begin)
  22502. ;; When at first paragraph in an item or a footnote definition,
  22503. ;; move directly to beginning of line.
  22504. (let ((parent-contents
  22505. (org-element-property
  22506. :contents-begin (org-element-property :parent element))))
  22507. (when (and parent-contents (= parent-contents contents-begin))
  22508. (beginning-of-line))))
  22509. ;; At the end of a greater element, move to the beginning of the
  22510. ;; last element within.
  22511. ((>= (point) contents-end)
  22512. (goto-char (1- contents-end))
  22513. (org-backward-paragraph))
  22514. (t (goto-char (or post-affiliated begin))))
  22515. ;; Ensure we never leave point invisible.
  22516. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22517. (defun org-forward-element ()
  22518. "Move forward by one element.
  22519. Move to the next element at the same level, when possible."
  22520. (interactive)
  22521. (cond ((eobp) (user-error "Cannot move further down"))
  22522. ((org-with-limited-levels (org-at-heading-p))
  22523. (let ((origin (point)))
  22524. (goto-char (org-end-of-subtree nil t))
  22525. (unless (org-with-limited-levels (org-at-heading-p))
  22526. (goto-char origin)
  22527. (user-error "Cannot move further down"))))
  22528. (t
  22529. (let* ((elem (org-element-at-point))
  22530. (end (org-element-property :end elem))
  22531. (parent (org-element-property :parent elem)))
  22532. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22533. (goto-char (org-element-property :end parent)))
  22534. ((integer-or-marker-p end) (goto-char end))
  22535. (t (message "No element at point")))))))
  22536. (defun org-backward-element ()
  22537. "Move backward by one element.
  22538. Move to the previous element at the same level, when possible."
  22539. (interactive)
  22540. (cond ((bobp) (user-error "Cannot move further up"))
  22541. ((org-with-limited-levels (org-at-heading-p))
  22542. ;; At a headline, move to the previous one, if any, or stay
  22543. ;; here.
  22544. (let ((origin (point)))
  22545. (org-with-limited-levels (org-backward-heading-same-level 1))
  22546. ;; When current headline has no sibling above, move to its
  22547. ;; parent.
  22548. (when (= (point) origin)
  22549. (or (org-with-limited-levels (org-up-heading-safe))
  22550. (progn (goto-char origin)
  22551. (user-error "Cannot move further up"))))))
  22552. (t
  22553. (let* ((elem (org-element-at-point))
  22554. (beg (org-element-property :begin elem)))
  22555. (cond
  22556. ;; Move to beginning of current element if point isn't
  22557. ;; there already.
  22558. ((null beg) (message "No element at point"))
  22559. ((/= (point) beg) (goto-char beg))
  22560. (t (goto-char beg)
  22561. (skip-chars-backward " \r\t\n")
  22562. (unless (bobp)
  22563. (let ((prev (org-element-at-point)))
  22564. (goto-char (org-element-property :begin prev))
  22565. (while (and (setq prev (org-element-property :parent prev))
  22566. (<= (org-element-property :end prev) beg))
  22567. (goto-char (org-element-property :begin prev)))))))))))
  22568. (defun org-up-element ()
  22569. "Move to upper element."
  22570. (interactive)
  22571. (if (org-with-limited-levels (org-at-heading-p))
  22572. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22573. (let* ((elem (org-element-at-point))
  22574. (parent (org-element-property :parent elem)))
  22575. (if parent (goto-char (org-element-property :begin parent))
  22576. (if (org-with-limited-levels (org-before-first-heading-p))
  22577. (user-error "No surrounding element")
  22578. (org-with-limited-levels (org-back-to-heading)))))))
  22579. (defvar org-element-greater-elements)
  22580. (defun org-down-element ()
  22581. "Move to inner element."
  22582. (interactive)
  22583. (let ((element (org-element-at-point)))
  22584. (cond
  22585. ((memq (org-element-type element) '(plain-list table))
  22586. (goto-char (org-element-property :contents-begin element))
  22587. (forward-char))
  22588. ((memq (org-element-type element) org-element-greater-elements)
  22589. ;; If contents are hidden, first disclose them.
  22590. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22591. (goto-char (or (org-element-property :contents-begin element)
  22592. (user-error "No content for this element"))))
  22593. (t (user-error "No inner element")))))
  22594. (defun org-drag-element-backward ()
  22595. "Move backward element at point."
  22596. (interactive)
  22597. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22598. (let* ((elem (org-element-at-point))
  22599. (prev-elem
  22600. (save-excursion
  22601. (goto-char (org-element-property :begin elem))
  22602. (skip-chars-backward " \r\t\n")
  22603. (unless (bobp)
  22604. (let* ((beg (org-element-property :begin elem))
  22605. (prev (org-element-at-point))
  22606. (up prev))
  22607. (while (and (setq up (org-element-property :parent up))
  22608. (<= (org-element-property :end up) beg))
  22609. (setq prev up))
  22610. prev)))))
  22611. ;; Error out if no previous element or previous element is
  22612. ;; a parent of the current one.
  22613. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22614. (user-error "Cannot drag element backward")
  22615. (let ((pos (point)))
  22616. (org-element-swap-A-B prev-elem elem)
  22617. (goto-char (+ (org-element-property :begin prev-elem)
  22618. (- pos (org-element-property :begin elem)))))))))
  22619. (defun org-drag-element-forward ()
  22620. "Move forward element at point."
  22621. (interactive)
  22622. (let* ((pos (point))
  22623. (elem (org-element-at-point)))
  22624. (when (= (point-max) (org-element-property :end elem))
  22625. (user-error "Cannot drag element forward"))
  22626. (goto-char (org-element-property :end elem))
  22627. (let ((next-elem (org-element-at-point)))
  22628. (when (or (org-element-nested-p elem next-elem)
  22629. (and (eq (org-element-type next-elem) 'headline)
  22630. (not (eq (org-element-type elem) 'headline))))
  22631. (goto-char pos)
  22632. (user-error "Cannot drag element forward"))
  22633. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22634. ;; body's length (without final blanks) and by the length of
  22635. ;; blanks between ELEM and NEXT-ELEM.
  22636. (let ((size-next (- (save-excursion
  22637. (goto-char (org-element-property :end next-elem))
  22638. (skip-chars-backward " \r\t\n")
  22639. (forward-line)
  22640. ;; Small correction if buffer doesn't end
  22641. ;; with a newline character.
  22642. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22643. (org-element-property :begin next-elem)))
  22644. (size-blank (- (org-element-property :end elem)
  22645. (save-excursion
  22646. (goto-char (org-element-property :end elem))
  22647. (skip-chars-backward " \r\t\n")
  22648. (forward-line)
  22649. (point)))))
  22650. (org-element-swap-A-B elem next-elem)
  22651. (goto-char (+ pos size-next size-blank))))))
  22652. (defun org-drag-line-forward (arg)
  22653. "Drag the line at point ARG lines forward."
  22654. (interactive "p")
  22655. (dotimes (_ (abs arg))
  22656. (let ((c (current-column)))
  22657. (if (< 0 arg)
  22658. (progn
  22659. (beginning-of-line 2)
  22660. (transpose-lines 1)
  22661. (beginning-of-line 0))
  22662. (transpose-lines 1)
  22663. (beginning-of-line -1))
  22664. (org-move-to-column c))))
  22665. (defun org-drag-line-backward (arg)
  22666. "Drag the line at point ARG lines backward."
  22667. (interactive "p")
  22668. (org-drag-line-forward (- arg)))
  22669. (defun org-mark-element ()
  22670. "Put point at beginning of this element, mark at end.
  22671. Interactively, if this command is repeated or (in Transient Mark
  22672. mode) if the mark is active, it marks the next element after the
  22673. ones already marked."
  22674. (interactive)
  22675. (let (deactivate-mark)
  22676. (if (and (called-interactively-p 'any)
  22677. (or (and (eq last-command this-command) (mark t))
  22678. (and transient-mark-mode mark-active)))
  22679. (set-mark
  22680. (save-excursion
  22681. (goto-char (mark))
  22682. (goto-char (org-element-property :end (org-element-at-point)))))
  22683. (let ((element (org-element-at-point)))
  22684. (end-of-line)
  22685. (push-mark (org-element-property :end element) t t)
  22686. (goto-char (org-element-property :begin element))))))
  22687. (defun org-narrow-to-element ()
  22688. "Narrow buffer to current element."
  22689. (interactive)
  22690. (let ((elem (org-element-at-point)))
  22691. (cond
  22692. ((eq (car elem) 'headline)
  22693. (narrow-to-region
  22694. (org-element-property :begin elem)
  22695. (org-element-property :end elem)))
  22696. ((memq (car elem) org-element-greater-elements)
  22697. (narrow-to-region
  22698. (org-element-property :contents-begin elem)
  22699. (org-element-property :contents-end elem)))
  22700. (t
  22701. (narrow-to-region
  22702. (org-element-property :begin elem)
  22703. (org-element-property :end elem))))))
  22704. (defun org-transpose-element ()
  22705. "Transpose current and previous elements, keeping blank lines between.
  22706. Point is moved after both elements."
  22707. (interactive)
  22708. (org-skip-whitespace)
  22709. (let ((end (org-element-property :end (org-element-at-point))))
  22710. (org-drag-element-backward)
  22711. (goto-char end)))
  22712. (defun org-unindent-buffer ()
  22713. "Un-indent the visible part of the buffer.
  22714. Relative indentation (between items, inside blocks, etc.) isn't
  22715. modified."
  22716. (interactive)
  22717. (unless (eq major-mode 'org-mode)
  22718. (user-error "Cannot un-indent a buffer not in Org mode"))
  22719. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22720. (unindent-tree
  22721. (lambda (contents)
  22722. (dolist (element (reverse contents))
  22723. (if (memq (org-element-type element) '(headline section))
  22724. (funcall unindent-tree (org-element-contents element))
  22725. (save-excursion
  22726. (save-restriction
  22727. (narrow-to-region
  22728. (org-element-property :begin element)
  22729. (org-element-property :end element))
  22730. (org-do-remove-indentation))))))))
  22731. (funcall unindent-tree (org-element-contents parse-tree))))
  22732. (defun org-show-children (&optional level)
  22733. "Show all direct subheadings of this heading.
  22734. Prefix arg LEVEL is how many levels below the current level
  22735. should be shown. Default is enough to cause the following
  22736. heading to appear."
  22737. (interactive "p")
  22738. ;; If `orgstruct-mode' is active, use the slower version.
  22739. (if orgstruct-mode (call-interactively #'outline-show-children)
  22740. (save-excursion
  22741. (org-back-to-heading t)
  22742. (let* ((current-level (funcall outline-level))
  22743. (max-level (org-get-valid-level
  22744. current-level
  22745. (if level (prefix-numeric-value level) 1)))
  22746. (end (save-excursion (org-end-of-subtree t t)))
  22747. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22748. (past-first-child nil)
  22749. ;; Make sure to skip inlinetasks.
  22750. (re (format regexp-fmt
  22751. current-level
  22752. (cond
  22753. ((not (featurep 'org-inlinetask)) "")
  22754. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22755. 3))
  22756. (t (1- org-inlinetask-min-level))))))
  22757. ;; Display parent heading.
  22758. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22759. (forward-line)
  22760. ;; Display children. First child may be deeper than expected
  22761. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22762. ;; MAX-LEVEL accordingly.
  22763. (while (re-search-forward re end t)
  22764. (unless past-first-child
  22765. (setq re (format regexp-fmt
  22766. current-level
  22767. (max (funcall outline-level) max-level)))
  22768. (setq past-first-child t))
  22769. (outline-flag-region
  22770. (line-end-position 0) (line-end-position) nil))))))
  22771. (defun org-show-subtree ()
  22772. "Show everything after this heading at deeper levels."
  22773. (interactive)
  22774. (outline-flag-region
  22775. (point)
  22776. (save-excursion
  22777. (org-end-of-subtree t t))
  22778. nil))
  22779. (defun org-show-entry ()
  22780. "Show the body directly following this heading.
  22781. Show the heading too, if it is currently invisible."
  22782. (interactive)
  22783. (save-excursion
  22784. (ignore-errors
  22785. (org-back-to-heading t)
  22786. (outline-flag-region
  22787. (max (point-min) (1- (point)))
  22788. (save-excursion
  22789. (if (re-search-forward
  22790. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22791. (match-beginning 1)
  22792. (point-max)))
  22793. nil)
  22794. (org-cycle-hide-drawers 'children))))
  22795. (defun org-make-options-regexp (kwds &optional extra)
  22796. "Make a regular expression for keyword lines.
  22797. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22798. when non-nil, is a regexp matching keywords names."
  22799. (concat "^[ \t]*#\\+\\("
  22800. (regexp-opt kwds)
  22801. (and extra (concat (and kwds "\\|") extra))
  22802. "\\):[ \t]*\\(.*\\)"))
  22803. ;;;; Integration with and fixes for other packages
  22804. ;;; Imenu support
  22805. (defvar-local org-imenu-markers nil
  22806. "All markers currently used by Imenu.")
  22807. (defun org-imenu-new-marker (&optional pos)
  22808. "Return a new marker for use by Imenu, and remember the marker."
  22809. (let ((m (make-marker)))
  22810. (move-marker m (or pos (point)))
  22811. (push m org-imenu-markers)
  22812. m))
  22813. (defun org-imenu-get-tree ()
  22814. "Produce the index for Imenu."
  22815. (dolist (x org-imenu-markers) (move-marker x nil))
  22816. (setq org-imenu-markers nil)
  22817. (let* ((case-fold-search nil)
  22818. (n org-imenu-depth)
  22819. (re (concat "^" (org-get-limited-outline-regexp)))
  22820. (subs (make-vector (1+ n) nil))
  22821. (last-level 0)
  22822. m level head0 head)
  22823. (org-with-wide-buffer
  22824. (goto-char (point-max))
  22825. (while (re-search-backward re nil t)
  22826. (setq level (org-reduced-level (funcall outline-level)))
  22827. (when (and (<= level n)
  22828. (looking-at org-complex-heading-regexp)
  22829. (setq head0 (match-string-no-properties 4)))
  22830. (setq head (org-link-display-format head0)
  22831. m (org-imenu-new-marker))
  22832. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22833. (if (>= level last-level)
  22834. (push (cons head m) (aref subs level))
  22835. (push (cons head (aref subs (1+ level))) (aref subs level))
  22836. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22837. (setq last-level level))))
  22838. (aref subs 1)))
  22839. (eval-after-load "imenu"
  22840. '(progn
  22841. (add-hook 'imenu-after-jump-hook
  22842. (lambda ()
  22843. (when (derived-mode-p 'org-mode)
  22844. (org-show-context 'org-goto))))))
  22845. (defun org-link-display-format (s)
  22846. "Replace links in string S with their description.
  22847. If there is no description, use the link target."
  22848. (save-match-data
  22849. (replace-regexp-in-string
  22850. org-bracket-link-analytic-regexp
  22851. (lambda (m)
  22852. (if (match-end 5) (match-string 5 m)
  22853. (concat (match-string 1 m) (match-string 3 m))))
  22854. s nil t)))
  22855. (defun org-toggle-link-display ()
  22856. "Toggle the literal or descriptive display of links."
  22857. (interactive)
  22858. (if org-descriptive-links
  22859. (progn (org-remove-from-invisibility-spec '(org-link))
  22860. (org-restart-font-lock)
  22861. (setq org-descriptive-links nil))
  22862. (progn (add-to-invisibility-spec '(org-link))
  22863. (org-restart-font-lock)
  22864. (setq org-descriptive-links t))))
  22865. ;; Speedbar support
  22866. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22867. "Overlay marking the agenda restriction line in speedbar.")
  22868. (overlay-put org-speedbar-restriction-lock-overlay
  22869. 'face 'org-agenda-restriction-lock)
  22870. (overlay-put org-speedbar-restriction-lock-overlay
  22871. 'help-echo "Agendas are currently limited to this item.")
  22872. (delete-overlay org-speedbar-restriction-lock-overlay)
  22873. (defun org-speedbar-set-agenda-restriction ()
  22874. "Restrict future agenda commands to the location at point in speedbar.
  22875. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22876. (interactive)
  22877. (require 'org-agenda)
  22878. (let (p m tp np dir txt)
  22879. (cond
  22880. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22881. 'org-imenu t))
  22882. (setq m (get-text-property p 'org-imenu-marker))
  22883. (with-current-buffer (marker-buffer m)
  22884. (goto-char m)
  22885. (org-agenda-set-restriction-lock 'subtree)))
  22886. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22887. 'speedbar-function 'speedbar-find-file))
  22888. (setq tp (previous-single-property-change
  22889. (1+ p) 'speedbar-function)
  22890. np (next-single-property-change
  22891. tp 'speedbar-function)
  22892. dir (speedbar-line-directory)
  22893. txt (buffer-substring-no-properties (or tp (point-min))
  22894. (or np (point-max))))
  22895. (with-current-buffer (find-file-noselect
  22896. (let ((default-directory dir))
  22897. (expand-file-name txt)))
  22898. (unless (derived-mode-p 'org-mode)
  22899. (user-error "Cannot restrict to non-Org mode file"))
  22900. (org-agenda-set-restriction-lock 'file)))
  22901. (t (user-error "Don't know how to restrict Org mode agenda")))
  22902. (move-overlay org-speedbar-restriction-lock-overlay
  22903. (point-at-bol) (point-at-eol))
  22904. (setq current-prefix-arg nil)
  22905. (org-agenda-maybe-redo)))
  22906. (defvar speedbar-file-key-map)
  22907. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22908. (eval-after-load "speedbar"
  22909. '(progn
  22910. (speedbar-add-supported-extension ".org")
  22911. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22912. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22913. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22914. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22915. (add-hook 'speedbar-visiting-tag-hook
  22916. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22917. ;;; Fixes and Hacks for problems with other packages
  22918. (defun org--flyspell-object-check-p (element)
  22919. "Non-nil when Flyspell can check object at point.
  22920. ELEMENT is the element at point."
  22921. (let ((object (save-excursion
  22922. (when (looking-at-p "\\>") (backward-char))
  22923. (org-element-context element))))
  22924. (cl-case (org-element-type object)
  22925. ;; Prevent checks in links due to keybinding conflict with
  22926. ;; Flyspell.
  22927. ((code entity export-snippet inline-babel-call
  22928. inline-src-block line-break latex-fragment link macro
  22929. statistics-cookie target timestamp verbatim)
  22930. nil)
  22931. (footnote-reference
  22932. ;; Only in inline footnotes, within the definition.
  22933. (and (eq (org-element-property :type object) 'inline)
  22934. (< (save-excursion
  22935. (goto-char (org-element-property :begin object))
  22936. (search-forward ":" nil t 2))
  22937. (point))))
  22938. (otherwise t))))
  22939. (defun org-mode-flyspell-verify ()
  22940. "Function used for `flyspell-generic-check-word-predicate'."
  22941. (if (org-at-heading-p)
  22942. ;; At a headline or an inlinetask, check title only. This is
  22943. ;; faster than relying on `org-element-at-point'.
  22944. (and (save-excursion (beginning-of-line)
  22945. (and (let ((case-fold-search t))
  22946. (not (looking-at-p "\\*+ END[ \t]*$")))
  22947. (let ((case-fold-search nil))
  22948. (looking-at org-complex-heading-regexp))))
  22949. (match-beginning 4)
  22950. (>= (point) (match-beginning 4))
  22951. (or (not (match-beginning 5))
  22952. (< (point) (match-beginning 5))))
  22953. (let* ((element (org-element-at-point))
  22954. (post-affiliated (org-element-property :post-affiliated element)))
  22955. (cond
  22956. ;; Ignore checks in all affiliated keywords but captions.
  22957. ((< (point) post-affiliated)
  22958. (and (save-excursion
  22959. (beginning-of-line)
  22960. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22961. (> (point) (match-end 0))
  22962. (org--flyspell-object-check-p element)))
  22963. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22964. ((let ((log (org-log-into-drawer)))
  22965. (and log
  22966. (let ((drawer (org-element-lineage element '(drawer))))
  22967. (and drawer
  22968. (eq (compare-strings
  22969. log nil nil
  22970. (org-element-property :drawer-name drawer) nil nil t)
  22971. t)))))
  22972. nil)
  22973. (t
  22974. (cl-case (org-element-type element)
  22975. ((comment quote-section) t)
  22976. (comment-block
  22977. ;; Allow checks between block markers, not on them.
  22978. (and (> (line-beginning-position) post-affiliated)
  22979. (save-excursion
  22980. (end-of-line)
  22981. (skip-chars-forward " \r\t\n")
  22982. (< (point) (org-element-property :end element)))))
  22983. ;; Arbitrary list of keywords where checks are meaningful.
  22984. ;; Make sure point is on the value part of the element.
  22985. (keyword
  22986. (and (member (org-element-property :key element)
  22987. '("DESCRIPTION" "TITLE"))
  22988. (save-excursion
  22989. (search-backward ":" (line-beginning-position) t))))
  22990. ;; Check is globally allowed in paragraphs verse blocks and
  22991. ;; table rows (after affiliated keywords) but some objects
  22992. ;; must not be affected.
  22993. ((paragraph table-row verse-block)
  22994. (let ((cbeg (org-element-property :contents-begin element))
  22995. (cend (org-element-property :contents-end element)))
  22996. (and cbeg (>= (point) cbeg) (< (point) cend)
  22997. (org--flyspell-object-check-p element))))))))))
  22998. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22999. (defun org-remove-flyspell-overlays-in (beg end)
  23000. "Remove flyspell overlays in region."
  23001. (and (bound-and-true-p flyspell-mode)
  23002. (fboundp 'flyspell-delete-region-overlays)
  23003. (flyspell-delete-region-overlays beg end)))
  23004. (defvar flyspell-delayed-commands)
  23005. (eval-after-load "flyspell"
  23006. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23007. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23008. (eval-after-load "bookmark"
  23009. '(if (boundp 'bookmark-after-jump-hook)
  23010. ;; We can use the hook
  23011. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23012. ;; Hook not available, use advice
  23013. (defadvice bookmark-jump (after org-make-visible activate)
  23014. "Make the position visible."
  23015. (org-bookmark-jump-unhide))))
  23016. ;; Make sure saveplace shows the location if it was hidden
  23017. (eval-after-load "saveplace"
  23018. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23019. "Make the position visible."
  23020. (org-bookmark-jump-unhide)))
  23021. ;; Make sure ecb shows the location if it was hidden
  23022. (eval-after-load "ecb"
  23023. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23024. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23025. (when (derived-mode-p 'org-mode)
  23026. (org-show-context))))
  23027. (defun org-bookmark-jump-unhide ()
  23028. "Unhide the current position, to show the bookmark location."
  23029. (and (derived-mode-p 'org-mode)
  23030. (or (outline-invisible-p)
  23031. (save-excursion (goto-char (max (point-min) (1- (point))))
  23032. (outline-invisible-p)))
  23033. (org-show-context 'bookmark-jump)))
  23034. (defun org-mark-jump-unhide ()
  23035. "Make the point visible with `org-show-context' after jumping to the mark."
  23036. (when (and (derived-mode-p 'org-mode)
  23037. (outline-invisible-p))
  23038. (org-show-context 'mark-goto)))
  23039. (eval-after-load "simple"
  23040. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23041. "Make the point visible with `org-show-context'."
  23042. (org-mark-jump-unhide)))
  23043. (eval-after-load "simple"
  23044. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23045. "Make the point visible with `org-show-context'."
  23046. (org-mark-jump-unhide)))
  23047. (eval-after-load "simple"
  23048. '(defadvice pop-global-mark (after org-make-visible activate)
  23049. "Make the point visible with `org-show-context'."
  23050. (org-mark-jump-unhide)))
  23051. ;; Make session.el ignore our circular variable
  23052. (defvar session-globals-exclude)
  23053. (eval-after-load "session"
  23054. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23055. ;;;; Finish up
  23056. (provide 'org)
  23057. (run-hooks 'org-load-hook)
  23058. ;;; org.el ends here