org.el 953 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocktable-shift "org-clock" (dir n))
  118. (declare-function org-element-at-point "org-element" ())
  119. (declare-function org-element-cache-refresh "org-element" (pos))
  120. (declare-function org-element-cache-reset "org-element" (&optional all))
  121. (declare-function org-element-contents "org-element" (element))
  122. (declare-function org-element-context "org-element" (&optional element))
  123. (declare-function org-element-copy "org-element" (datum))
  124. (declare-function org-element-interpret-data "org-element" (data))
  125. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  126. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  127. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  128. (declare-function org-element-property "org-element" (property element))
  129. (declare-function org-element-put-property "org-element" (element property value))
  130. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  131. (declare-function org-element-type "org-element" (element))
  132. (declare-function org-element-update-syntax "org-element" ())
  133. (declare-function org-id-find-id-file "org-id" (id))
  134. (declare-function org-id-get-create "org-id" (&optional force))
  135. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  136. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  137. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  138. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  139. (declare-function org-table-align "org-table" ())
  140. (declare-function org-table-begin "org-table" (&optional table-type))
  141. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  142. (declare-function org-table-blank-field "org-table" ())
  143. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  144. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  145. (declare-function org-table-cut-region "org-table" (beg end))
  146. (declare-function org-table-edit-field "org-table" (arg))
  147. (declare-function org-table-end "org-table" (&optional table-type))
  148. (declare-function org-table-end-of-field "org-table" (&optional n))
  149. (declare-function org-table-insert-row "org-table" (&optional arg))
  150. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  151. (declare-function org-table-maybe-eval-formula "org-table" ())
  152. (declare-function org-table-maybe-recalculate-line "org-table" ())
  153. (declare-function org-table-next-row "org-table" ())
  154. (declare-function org-table-paste-rectangle "org-table" ())
  155. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  156. (declare-function org-table-wrap-region "org-table" (arg))
  157. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  158. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  159. (declare-function orgtbl-mode "org-table" (&optional arg))
  160. (declare-function org-export-get-backend "ox" (name))
  161. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  162. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  163. (defsubst org-uniquify (list)
  164. "Non-destructively remove duplicate elements from LIST."
  165. (let ((res (copy-sequence list))) (delete-dups res)))
  166. (defsubst org-get-at-bol (property)
  167. "Get text property PROPERTY at the beginning of line."
  168. (get-text-property (point-at-bol) property))
  169. (defsubst org-trim (s &optional keep-lead)
  170. "Remove whitespace at the beginning and the end of string S.
  171. When optional argument KEEP-LEAD is non-nil, removing blank lines
  172. at the beginning of the string does not affect leading indentation."
  173. (replace-regexp-in-string
  174. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  175. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  176. ;; load languages based on value of `org-babel-load-languages'
  177. (defvar org-babel-load-languages)
  178. ;;;###autoload
  179. (defun org-babel-do-load-languages (sym value)
  180. "Load the languages defined in `org-babel-load-languages'."
  181. (set-default sym value)
  182. (dolist (pair org-babel-load-languages)
  183. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  184. (if active
  185. (require (intern (concat "ob-" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-execute:" lang)))
  188. (funcall 'fmakunbound
  189. (intern (concat "org-babel-expand-body:" lang)))))))
  190. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  191. ;;;###autoload
  192. (defun org-babel-load-file (file &optional compile)
  193. "Load Emacs Lisp source code blocks in the Org FILE.
  194. This function exports the source code using `org-babel-tangle'
  195. and then loads the resulting file using `load-file'. With prefix
  196. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  197. file to byte-code before it is loaded."
  198. (interactive "fFile to load: \nP")
  199. (let* ((age (lambda (file)
  200. (float-time
  201. (time-subtract (current-time)
  202. (nth 5 (or (file-attributes (file-truename file))
  203. (file-attributes file)))))))
  204. (base-name (file-name-sans-extension file))
  205. (exported-file (concat base-name ".el")))
  206. ;; tangle if the Org file is newer than the elisp file
  207. (unless (and (file-exists-p exported-file)
  208. (> (funcall age file) (funcall age exported-file)))
  209. ;; Tangle-file traversal returns reversed list of tangled files
  210. ;; and we want to evaluate the first target.
  211. (setq exported-file
  212. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  213. (message "%s %s"
  214. (if compile
  215. (progn (byte-compile-file exported-file 'load)
  216. "Compiled and loaded")
  217. (progn (load-file exported-file) "Loaded"))
  218. exported-file)))
  219. (defcustom org-babel-load-languages '((emacs-lisp . t))
  220. "Languages which can be evaluated in Org buffers.
  221. This list can be used to load support for any of the languages
  222. below, note that each language will depend on a different set of
  223. system executables and/or Emacs modes. When a language is
  224. \"loaded\", then code blocks in that language can be evaluated
  225. with `org-babel-execute-src-block' bound by default to C-c
  226. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  227. be set to remove code block evaluation from the C-c C-c
  228. keybinding. By default only Emacs Lisp (which has no
  229. requirements) is loaded."
  230. :group 'org-babel
  231. :set 'org-babel-do-load-languages
  232. :version "24.1"
  233. :type '(alist :tag "Babel Languages"
  234. :key-type
  235. (choice
  236. (const :tag "Awk" awk)
  237. (const :tag "C" C)
  238. (const :tag "R" R)
  239. (const :tag "Asymptote" asymptote)
  240. (const :tag "Calc" calc)
  241. (const :tag "Clojure" clojure)
  242. (const :tag "CSS" css)
  243. (const :tag "Ditaa" ditaa)
  244. (const :tag "Dot" dot)
  245. (const :tag "Emacs Lisp" emacs-lisp)
  246. (const :tag "Forth" forth)
  247. (const :tag "Fortran" fortran)
  248. (const :tag "Gnuplot" gnuplot)
  249. (const :tag "Haskell" haskell)
  250. (const :tag "IO" io)
  251. (const :tag "J" J)
  252. (const :tag "Java" java)
  253. (const :tag "Javascript" js)
  254. (const :tag "LaTeX" latex)
  255. (const :tag "Ledger" ledger)
  256. (const :tag "Lilypond" lilypond)
  257. (const :tag "Lisp" lisp)
  258. (const :tag "Makefile" makefile)
  259. (const :tag "Maxima" maxima)
  260. (const :tag "Matlab" matlab)
  261. (const :tag "Mscgen" mscgen)
  262. (const :tag "Ocaml" ocaml)
  263. (const :tag "Octave" octave)
  264. (const :tag "Org" org)
  265. (const :tag "Perl" perl)
  266. (const :tag "Pico Lisp" picolisp)
  267. (const :tag "PlantUML" plantuml)
  268. (const :tag "Python" python)
  269. (const :tag "Ruby" ruby)
  270. (const :tag "Sass" sass)
  271. (const :tag "Scala" scala)
  272. (const :tag "Scheme" scheme)
  273. (const :tag "Screen" screen)
  274. (const :tag "Shell Script" shell)
  275. (const :tag "Shen" shen)
  276. (const :tag "Sql" sql)
  277. (const :tag "Sqlite" sqlite)
  278. (const :tag "Stan" stan)
  279. (const :tag "ebnf2ps" ebnf2ps))
  280. :value-type (boolean :tag "Activate" :value t)))
  281. ;;;; Customization variables
  282. (defcustom org-clone-delete-id nil
  283. "Remove ID property of clones of a subtree.
  284. When non-nil, clones of a subtree don't inherit the ID property.
  285. Otherwise they inherit the ID property with a new unique
  286. identifier."
  287. :type 'boolean
  288. :version "24.1"
  289. :group 'org-id)
  290. ;;; Version
  291. (org-check-version)
  292. ;;;###autoload
  293. (defun org-version (&optional here full message)
  294. "Show the Org version.
  295. Interactively, or when MESSAGE is non-nil, show it in echo area.
  296. With prefix argument, or when HERE is non-nil, insert it at point.
  297. In non-interactive uses, a reduced version string is output unless
  298. FULL is given."
  299. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  300. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  301. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  302. (load-suffixes (list ".el"))
  303. (org-install-dir
  304. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  305. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  306. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  307. (let* ((load-suffixes save-load-suffixes)
  308. (release (org-release))
  309. (git-version (org-git-version))
  310. (version (format "Org mode version %s (%s @ %s)"
  311. release
  312. git-version
  313. (if org-install-dir
  314. (if (string= org-dir org-install-dir)
  315. org-install-dir
  316. (concat "mixed installation! "
  317. org-install-dir
  318. " and "
  319. org-dir))
  320. "org-loaddefs.el can not be found!")))
  321. (version1 (if full version release)))
  322. (when here (insert version1))
  323. (when message (message "%s" version1))
  324. version1)))
  325. (defconst org-version (org-version))
  326. ;;; Syntax Constants
  327. ;;;; Block
  328. (defconst org-block-regexp
  329. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  330. "Regular expression for hiding blocks.")
  331. (defconst org-dblock-start-re
  332. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  333. "Matches the start line of a dynamic block, with parameters.")
  334. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  335. "Matches the end of a dynamic block.")
  336. ;;;; Clock and Planning
  337. (defconst org-clock-string "CLOCK:"
  338. "String used as prefix for timestamps clocking work hours on an item.")
  339. (defvar org-closed-string "CLOSED:"
  340. "String used as the prefix for timestamps logging closing a TODO entry.")
  341. (defvar org-deadline-string "DEADLINE:"
  342. "String to mark deadline entries.
  343. \\<org-mode-map>
  344. A deadline is this string, followed by a time stamp. It must be
  345. a word, terminated by a colon. You can insert a schedule keyword
  346. and a timestamp with `\\[org-deadline]'.")
  347. (defvar org-scheduled-string "SCHEDULED:"
  348. "String to mark scheduled TODO entries.
  349. \\<org-mode-map>
  350. A schedule is this string, followed by a time stamp. It must be
  351. a word, terminated by a colon. You can insert a schedule keyword
  352. and a timestamp with `\\[org-schedule]'.")
  353. (defconst org-ds-keyword-length
  354. (+ 2
  355. (apply #'max
  356. (mapcar #'length
  357. (list org-deadline-string org-scheduled-string
  358. org-clock-string org-closed-string))))
  359. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  360. (defconst org-planning-line-re
  361. (concat "^[ \t]*"
  362. (regexp-opt
  363. (list org-closed-string org-deadline-string org-scheduled-string)
  364. t))
  365. "Matches a line with planning info.
  366. Matched keyword is in group 1.")
  367. (defconst org-clock-line-re
  368. (concat "^[ \t]*" org-clock-string)
  369. "Matches a line with clock info.")
  370. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  371. "Matches the DEADLINE keyword.")
  372. (defconst org-deadline-time-regexp
  373. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  374. "Matches the DEADLINE keyword together with a time stamp.")
  375. (defconst org-deadline-time-hour-regexp
  376. (concat "\\<" org-deadline-string
  377. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  378. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  379. (defconst org-deadline-line-regexp
  380. (concat "\\<\\(" org-deadline-string "\\).*")
  381. "Matches the DEADLINE keyword and the rest of the line.")
  382. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  383. "Matches the SCHEDULED keyword.")
  384. (defconst org-scheduled-time-regexp
  385. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  386. "Matches the SCHEDULED keyword together with a time stamp.")
  387. (defconst org-scheduled-time-hour-regexp
  388. (concat "\\<" org-scheduled-string
  389. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  390. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  391. (defconst org-closed-time-regexp
  392. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  393. "Matches the CLOSED keyword together with a time stamp.")
  394. (defconst org-keyword-time-regexp
  395. (concat "\\<"
  396. (regexp-opt
  397. (list org-scheduled-string org-deadline-string org-closed-string
  398. org-clock-string)
  399. t)
  400. " *[[<]\\([^]>]+\\)[]>]")
  401. "Matches any of the 4 keywords, together with the time stamp.")
  402. (defconst org-keyword-time-not-clock-regexp
  403. (concat
  404. "\\<"
  405. (regexp-opt
  406. (list org-scheduled-string org-deadline-string org-closed-string) t)
  407. " *[[<]\\([^]>]+\\)[]>]")
  408. "Matches any of the 3 keywords, together with the time stamp.")
  409. (defconst org-maybe-keyword-time-regexp
  410. (concat "\\(\\<"
  411. (regexp-opt
  412. (list org-scheduled-string org-deadline-string org-closed-string
  413. org-clock-string)
  414. t)
  415. "\\)?"
  416. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  417. "\\|"
  418. "<%%([^\r\n>]*>\\)")
  419. "Matches a timestamp, possibly preceded by a keyword.")
  420. (defconst org-all-time-keywords
  421. (mapcar (lambda (w) (substring w 0 -1))
  422. (list org-scheduled-string org-deadline-string
  423. org-clock-string org-closed-string))
  424. "List of time keywords.")
  425. ;;;; Drawer
  426. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  427. "Matches first or last line of a hidden block.
  428. Group 1 contains drawer's name or \"END\".")
  429. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  430. "Regular expression matching the first line of a property drawer.")
  431. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a property drawer.")
  433. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  434. "Regular expression matching the first line of a clock drawer.")
  435. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  436. "Regular expression matching the last line of a clock drawer.")
  437. (defconst org-property-drawer-re
  438. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  439. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  440. "[ \t]*:END:[ \t]*$")
  441. "Matches an entire property drawer.")
  442. (defconst org-clock-drawer-re
  443. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  444. org-clock-drawer-end-re "\\)\n?")
  445. "Matches an entire clock drawer.")
  446. ;;;; Headline
  447. (defconst org-heading-keyword-regexp-format
  448. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  449. "Printf format for a regexp matching a headline with some keyword.
  450. This regexp will match the headline of any node which has the
  451. exact keyword that is put into the format. The keyword isn't in
  452. any group by default, but the stars and the body are.")
  453. (defconst org-heading-keyword-maybe-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline, possibly with some keyword.
  456. This regexp can match any headline with the specified keyword, or
  457. without a keyword. The keyword isn't in any group by default,
  458. but the stars and the body are.")
  459. (defconst org-archive-tag "ARCHIVE"
  460. "The tag that marks a subtree as archived.
  461. An archived subtree does not open during visibility cycling, and does
  462. not contribute to the agenda listings.")
  463. (defconst org-comment-string "COMMENT"
  464. "Entries starting with this keyword will never be exported.
  465. \\<org-mode-map>
  466. An entry can be toggled between COMMENT and normal with
  467. `\\[org-toggle-comment]'.")
  468. ;;;; LaTeX Environments and Fragments
  469. (defconst org-latex-regexps
  470. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  471. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  472. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  473. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  474. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  475. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  476. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  477. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  478. "Regular expressions for matching embedded LaTeX.")
  479. ;;;; Node Property
  480. (defconst org-effort-property "Effort"
  481. "The property that is being used to keep track of effort estimates.
  482. Effort estimates given in this property need to have the format H:MM.")
  483. ;;;; Table
  484. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  485. "Detect an org-type or table-type table.")
  486. (defconst org-table-line-regexp "^[ \t]*|"
  487. "Detect an org-type table line.")
  488. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  489. "Detect an org-type table line.")
  490. (defconst org-table-hline-regexp "^[ \t]*|-"
  491. "Detect an org-type table hline.")
  492. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  493. "Detect a table-type table hline.")
  494. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  495. "Detect the first line outside a table when searching from within it.
  496. This works for both table types.")
  497. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  498. "Detect a #+TBLFM line.")
  499. ;;;; Timestamp
  500. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  501. "Regular expression for fast time stamp matching.")
  502. (defconst org-ts-regexp-inactive
  503. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  504. "Regular expression for fast inactive time stamp matching.")
  505. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  506. "Regular expression for fast time stamp matching.")
  507. (defconst org-ts-regexp0
  508. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  509. "Regular expression matching time strings for analysis.
  510. This one does not require the space after the date, so it can be used
  511. on a string that terminates immediately after the date.")
  512. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  513. "Regular expression matching time strings for analysis.")
  514. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  515. "Regular expression matching time stamps, with groups.")
  516. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  517. "Regular expression matching time stamps (also [..]), with groups.")
  518. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tr-regexp-both
  521. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  522. "Regular expression matching a time stamp range.")
  523. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  524. org-ts-regexp "\\)?")
  525. "Regular expression matching a time stamp or time stamp range.")
  526. (defconst org-tsr-regexp-both
  527. (concat org-ts-regexp-both "\\(--?-?"
  528. org-ts-regexp-both "\\)?")
  529. "Regular expression matching a time stamp or time stamp range.
  530. The time stamps may be either active or inactive.")
  531. (defconst org-repeat-re
  532. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  533. "Regular expression for specifying repeated events.
  534. After a match, group 1 contains the repeat expression.")
  535. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  536. "Formats for `format-time-string' which are used for time stamps.")
  537. ;;; The custom variables
  538. (defgroup org nil
  539. "Outline-based notes management and organizer."
  540. :tag "Org"
  541. :group 'outlines
  542. :group 'calendar)
  543. (defcustom org-mode-hook nil
  544. "Mode hook for Org mode, run after the mode was turned on."
  545. :group 'org
  546. :type 'hook)
  547. (defcustom org-load-hook nil
  548. "Hook that is run after org.el has been loaded."
  549. :group 'org
  550. :type 'hook)
  551. (defcustom org-log-buffer-setup-hook nil
  552. "Hook that is run after an Org log buffer is created."
  553. :group 'org
  554. :version "24.1"
  555. :type 'hook)
  556. (defvar org-modules) ; defined below
  557. (defvar org-modules-loaded nil
  558. "Have the modules been loaded already?")
  559. (defun org-load-modules-maybe (&optional force)
  560. "Load all extensions listed in `org-modules'."
  561. (when (or force (not org-modules-loaded))
  562. (dolist (ext org-modules)
  563. (condition-case nil (require ext)
  564. (error (message "Problems while trying to load feature `%s'" ext))))
  565. (setq org-modules-loaded t)))
  566. (defun org-set-modules (var value)
  567. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  568. (set var value)
  569. (when (featurep 'org)
  570. (org-load-modules-maybe 'force)
  571. (org-element-cache-reset 'all)))
  572. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  573. "Modules that should always be loaded together with org.el.
  574. If a description starts with <C>, the file is not part of Emacs
  575. and loading it will require that you have downloaded and properly
  576. installed the Org mode distribution.
  577. You can also use this system to load external packages (i.e. neither Org
  578. core modules, nor modules from the CONTRIB directory). Just add symbols
  579. to the end of the list. If the package is called org-xyz.el, then you need
  580. to add the symbol `xyz', and the package must have a call to:
  581. (provide \\='org-xyz)
  582. For export specific modules, see also `org-export-backends'."
  583. :group 'org
  584. :set 'org-set-modules
  585. :version "24.4"
  586. :package-version '(Org . "8.0")
  587. :type
  588. '(set :greedy t
  589. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  590. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  591. (const :tag " crypt: Encryption of subtrees" org-crypt)
  592. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  593. (const :tag " docview: Links to doc-view buffers" org-docview)
  594. (const :tag " eww: Store link to url of eww" org-eww)
  595. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  596. (const :tag " habit: Track your consistency with habits" org-habit)
  597. (const :tag " id: Global IDs for identifying entries" org-id)
  598. (const :tag " info: Links to Info nodes" org-info)
  599. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  600. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  601. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  602. (const :tag " mouse: Additional mouse support" org-mouse)
  603. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  604. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  605. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  606. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  607. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  608. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  609. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  610. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  611. (const :tag "C collector: Collect properties into tables" org-collector)
  612. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  613. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  614. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  615. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  616. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  617. (const :tag "C eval: Include command output as text" org-eval)
  618. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  619. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  620. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  621. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  622. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  623. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  624. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  625. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  626. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  627. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  628. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  629. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  630. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  631. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  632. (const :tag "C registry: A registry for Org links" org-registry)
  633. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  634. (const :tag "C secretary: Team management with org-mode" org-secretary)
  635. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  636. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  637. (const :tag "C track: Keep up with Org mode development" org-track)
  638. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  639. (const :tag "C vm: Links to VM folders/messages" org-vm)
  640. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  641. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  642. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  643. (defvar org-export-registered-backends) ; From ox.el.
  644. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  645. (declare-function org-export-backend-name "ox" (backend) t)
  646. (defcustom org-export-backends '(ascii html icalendar latex odt)
  647. "List of export back-ends that should be always available.
  648. If a description starts with <C>, the file is not part of Emacs
  649. and loading it will require that you have downloaded and properly
  650. installed the Org mode distribution.
  651. Unlike to `org-modules', libraries in this list will not be
  652. loaded along with Org, but only once the export framework is
  653. needed.
  654. This variable needs to be set before org.el is loaded. If you
  655. need to make a change while Emacs is running, use the customize
  656. interface or run the following code, where VAL stands for the new
  657. value of the variable, after updating it:
  658. (progn
  659. (setq org-export-registered-backends
  660. (cl-remove-if-not
  661. (lambda (backend)
  662. (let ((name (org-export-backend-name backend)))
  663. (or (memq name val)
  664. (catch \\='parentp
  665. (dolist (b val)
  666. (and (org-export-derived-backend-p b name)
  667. (throw \\='parentp t)))))))
  668. org-export-registered-backends))
  669. (let ((new-list (mapcar #\\='org-export-backend-name
  670. org-export-registered-backends)))
  671. (dolist (backend val)
  672. (cond
  673. ((not (load (format \"ox-%s\" backend) t t))
  674. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  675. backend))
  676. ((not (memq backend new-list)) (push backend new-list))))
  677. (set-default \\='org-export-backends new-list)))
  678. Adding a back-end to this list will also pull the back-end it
  679. depends on, if any."
  680. :group 'org
  681. :group 'org-export
  682. :version "26.1"
  683. :package-version '(Org . "9.0")
  684. :initialize 'custom-initialize-set
  685. :set (lambda (var val)
  686. (if (not (featurep 'ox)) (set-default var val)
  687. ;; Any back-end not required anymore (not present in VAL and not
  688. ;; a parent of any back-end in the new value) is removed from the
  689. ;; list of registered back-ends.
  690. (setq org-export-registered-backends
  691. (cl-remove-if-not
  692. (lambda (backend)
  693. (let ((name (org-export-backend-name backend)))
  694. (or (memq name val)
  695. (catch 'parentp
  696. (dolist (b val)
  697. (and (org-export-derived-backend-p b name)
  698. (throw 'parentp t)))))))
  699. org-export-registered-backends))
  700. ;; Now build NEW-LIST of both new back-ends and required
  701. ;; parents.
  702. (let ((new-list (mapcar #'org-export-backend-name
  703. org-export-registered-backends)))
  704. (dolist (backend val)
  705. (cond
  706. ((not (load (format "ox-%s" backend) t t))
  707. (message "Problems while trying to load export back-end `%s'"
  708. backend))
  709. ((not (memq backend new-list)) (push backend new-list))))
  710. ;; Set VAR to that list with fixed dependencies.
  711. (set-default var new-list))))
  712. :type '(set :greedy t
  713. (const :tag " ascii Export buffer to ASCII format" ascii)
  714. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  715. (const :tag " html Export buffer to HTML format" html)
  716. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  717. (const :tag " latex Export buffer to LaTeX format" latex)
  718. (const :tag " man Export buffer to MAN format" man)
  719. (const :tag " md Export buffer to Markdown format" md)
  720. (const :tag " odt Export buffer to ODT format" odt)
  721. (const :tag " org Export buffer to Org format" org)
  722. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  723. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  724. (const :tag "C deck Export buffer to deck.js presentations" deck)
  725. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  726. (const :tag "C groff Export buffer to Groff format" groff)
  727. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  728. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  729. (const :tag "C s5 Export buffer to s5 presentations" s5)
  730. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  731. (eval-after-load 'ox
  732. '(dolist (backend org-export-backends)
  733. (condition-case nil (require (intern (format "ox-%s" backend)))
  734. (error (message "Problems while trying to load export back-end `%s'"
  735. backend)))))
  736. (defcustom org-support-shift-select nil
  737. "Non-nil means make shift-cursor commands select text when possible.
  738. \\<org-mode-map>\
  739. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  740. start selecting a region, or enlarge regions started in this way.
  741. In Org mode, in special contexts, these same keys are used for
  742. other purposes, important enough to compete with shift selection.
  743. Org tries to balance these needs by supporting `shift-select-mode'
  744. outside these special contexts, under control of this variable.
  745. The default of this variable is nil, to avoid confusing behavior. Shifted
  746. cursor keys will then execute Org commands in the following contexts:
  747. - on a headline, changing TODO state (left/right) and priority (up/down)
  748. - on a time stamp, changing the time
  749. - in a plain list item, changing the bullet type
  750. - in a property definition line, switching between allowed values
  751. - in the BEGIN line of a clock table (changing the time block).
  752. Outside these contexts, the commands will throw an error.
  753. When this variable is t and the cursor is not in a special
  754. context, Org mode will support shift-selection for making and
  755. enlarging regions. To make this more effective, the bullet
  756. cycling will no longer happen anywhere in an item line, but only
  757. if the cursor is exactly on the bullet.
  758. If you set this variable to the symbol `always', then the keys
  759. will not be special in headlines, property lines, and item lines,
  760. to make shift selection work there as well. If this is what you
  761. want, you can use the following alternative commands:
  762. `\\[org-todo]' and `\\[org-priority]' \
  763. to change TODO state and priority,
  764. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  765. can be used to switch TODO sets,
  766. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  767. and properties can be edited by hand or in column view.
  768. However, when the cursor is on a timestamp, shift-cursor commands
  769. will still edit the time stamp - this is just too good to give up."
  770. :group 'org
  771. :type '(choice
  772. (const :tag "Never" nil)
  773. (const :tag "When outside special context" t)
  774. (const :tag "Everywhere except timestamps" always)))
  775. (defcustom org-loop-over-headlines-in-active-region nil
  776. "Shall some commands act upon headlines in the active region?
  777. When set to t, some commands will be performed in all headlines
  778. within the active region.
  779. When set to `start-level', some commands will be performed in all
  780. headlines within the active region, provided that these headlines
  781. are of the same level than the first one.
  782. When set to a string, those commands will be performed on the
  783. matching headlines within the active region. Such string must be
  784. a tags/property/todo match as it is used in the agenda tags view.
  785. The list of commands is: `org-schedule', `org-deadline',
  786. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  787. `org-archive-to-archive-sibling'. The archiving commands skip
  788. already archived entries."
  789. :type '(choice (const :tag "Don't loop" nil)
  790. (const :tag "All headlines in active region" t)
  791. (const :tag "In active region, headlines at the same level than the first one" start-level)
  792. (string :tag "Tags/Property/Todo matcher"))
  793. :version "24.1"
  794. :group 'org-todo
  795. :group 'org-archive)
  796. (defgroup org-startup nil
  797. "Options concerning startup of Org mode."
  798. :tag "Org Startup"
  799. :group 'org)
  800. (defcustom org-startup-folded t
  801. "Non-nil means entering Org mode will switch to OVERVIEW.
  802. This can also be configured on a per-file basis by adding one of
  803. the following lines anywhere in the buffer:
  804. #+STARTUP: fold (or `overview', this is equivalent)
  805. #+STARTUP: nofold (or `showall', this is equivalent)
  806. #+STARTUP: content
  807. #+STARTUP: showeverything
  808. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  809. to ignore this option when Org opens agenda files for the first
  810. time."
  811. :group 'org-startup
  812. :type '(choice
  813. (const :tag "nofold: show all" nil)
  814. (const :tag "fold: overview" t)
  815. (const :tag "content: all headlines" content)
  816. (const :tag "show everything, even drawers" showeverything)))
  817. (defcustom org-startup-truncated t
  818. "Non-nil means entering Org mode will set `truncate-lines'.
  819. This is useful since some lines containing links can be very long and
  820. uninteresting. Also tables look terrible when wrapped.
  821. The variable `org-startup-truncated' allows to configure
  822. truncation for Org mode different to the other modes that use the
  823. variable `truncate-lines' and as a shortcut instead of putting
  824. the variable `truncate-lines' into the `org-mode-hook'. If one
  825. wants to configure truncation for Org mode not statically but
  826. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  827. the variable `truncate-lines' has to be used because in such a
  828. case it is too late to set the variable `org-startup-truncated'."
  829. :group 'org-startup
  830. :type 'boolean)
  831. (defcustom org-startup-indented nil
  832. "Non-nil means turn on `org-indent-mode' on startup.
  833. This can also be configured on a per-file basis by adding one of
  834. the following lines anywhere in the buffer:
  835. #+STARTUP: indent
  836. #+STARTUP: noindent"
  837. :group 'org-structure
  838. :type '(choice
  839. (const :tag "Not" nil)
  840. (const :tag "Globally (slow on startup in large files)" t)))
  841. (defcustom org-use-sub-superscripts t
  842. "Non-nil means interpret \"_\" and \"^\" for display.
  843. If you want to control how Org exports those characters, see
  844. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  845. used to be an alias for `org-export-with-sub-superscripts' in
  846. Org <8.0, it is not anymore.
  847. When this option is turned on, you can use TeX-like syntax for
  848. sub- and superscripts within the buffer. Several characters after
  849. \"_\" or \"^\" will be considered as a single item - so grouping
  850. with {} is normally not needed. For example, the following things
  851. will be parsed as single sub- or superscripts:
  852. 10^24 or 10^tau several digits will be considered 1 item.
  853. 10^-12 or 10^-tau a leading sign with digits or a word
  854. x^2-y^3 will be read as x^2 - y^3, because items are
  855. terminated by almost any nonword/nondigit char.
  856. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  857. Still, ambiguity is possible. So when in doubt, use {} to enclose
  858. the sub/superscript. If you set this variable to the symbol `{}',
  859. the braces are *required* in order to trigger interpretations as
  860. sub/superscript. This can be helpful in documents that need \"_\"
  861. frequently in plain text."
  862. :group 'org-startup
  863. :version "24.4"
  864. :package-version '(Org . "8.0")
  865. :type '(choice
  866. (const :tag "Always interpret" t)
  867. (const :tag "Only with braces" {})
  868. (const :tag "Never interpret" nil)))
  869. (defcustom org-startup-with-beamer-mode nil
  870. "Non-nil means turn on `org-beamer-mode' on startup.
  871. This can also be configured on a per-file basis by adding one of
  872. the following lines anywhere in the buffer:
  873. #+STARTUP: beamer"
  874. :group 'org-startup
  875. :version "24.1"
  876. :type 'boolean)
  877. (defcustom org-startup-align-all-tables nil
  878. "Non-nil means align all tables when visiting a file.
  879. This is useful when the column width in tables is forced with <N> cookies
  880. in table fields. Such tables will look correct only after the first re-align.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: align
  884. #+STARTUP: noalign"
  885. :group 'org-startup
  886. :type 'boolean)
  887. (defcustom org-startup-with-inline-images nil
  888. "Non-nil means show inline images when loading a new Org file.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: inlineimages
  892. #+STARTUP: noinlineimages"
  893. :group 'org-startup
  894. :version "24.1"
  895. :type 'boolean)
  896. (defcustom org-startup-with-latex-preview nil
  897. "Non-nil means preview LaTeX fragments when loading a new Org file.
  898. This can also be configured on a per-file basis by adding one of
  899. the following lines anywhere in the buffer:
  900. #+STARTUP: latexpreview
  901. #+STARTUP: nolatexpreview"
  902. :group 'org-startup
  903. :version "24.4"
  904. :package-version '(Org . "8.0")
  905. :type 'boolean)
  906. (defcustom org-insert-mode-line-in-empty-file nil
  907. "Non-nil means insert the first line setting Org mode in empty files.
  908. When the function `org-mode' is called interactively in an empty file, this
  909. normally means that the file name does not automatically trigger Org mode.
  910. To ensure that the file will always be in Org mode in the future, a
  911. line enforcing Org mode will be inserted into the buffer, if this option
  912. has been set."
  913. :group 'org-startup
  914. :type 'boolean)
  915. (defcustom org-replace-disputed-keys nil
  916. "Non-nil means use alternative key bindings for some keys.
  917. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  918. These keys are also used by other packages like shift-selection-mode'
  919. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  920. If you want to use Org mode together with one of these other modes,
  921. or more generally if you would like to move some Org mode commands to
  922. other keys, set this variable and configure the keys with the variable
  923. `org-disputed-keys'.
  924. This option is only relevant at load-time of Org mode, and must be set
  925. *before* org.el is loaded. Changing it requires a restart of Emacs to
  926. become effective."
  927. :group 'org-startup
  928. :type 'boolean)
  929. (defcustom org-use-extra-keys nil
  930. "Non-nil means use extra key sequence definitions for certain commands.
  931. This happens automatically if `window-system' is nil. This
  932. variable lets you do the same manually. You must set it before
  933. loading Org."
  934. :group 'org-startup
  935. :type 'boolean)
  936. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  937. (defcustom org-disputed-keys
  938. '(([(shift up)] . [(meta p)])
  939. ([(shift down)] . [(meta n)])
  940. ([(shift left)] . [(meta -)])
  941. ([(shift right)] . [(meta +)])
  942. ([(control shift right)] . [(meta shift +)])
  943. ([(control shift left)] . [(meta shift -)]))
  944. "Keys for which Org mode and other modes compete.
  945. This is an alist, cars are the default keys, second element specifies
  946. the alternative to use when `org-replace-disputed-keys' is t.
  947. Keys can be specified in any syntax supported by `define-key'.
  948. The value of this option takes effect only at Org mode startup,
  949. therefore you'll have to restart Emacs to apply it after changing."
  950. :group 'org-startup
  951. :type 'alist)
  952. (defun org-key (key)
  953. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  954. Or return the original if not disputed."
  955. (when org-replace-disputed-keys
  956. (let* ((nkey (key-description key))
  957. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  958. org-disputed-keys)))
  959. (setq key (if x (cdr x) key))))
  960. key)
  961. (defun org-defkey (keymap key def)
  962. "Define a key, possibly translated, as returned by `org-key'."
  963. (define-key keymap (org-key key) def))
  964. (defcustom org-ellipsis nil
  965. "The ellipsis to use in the Org mode outline.
  966. When nil, just use the standard three dots.
  967. When a string, use that string instead.
  968. The change affects only Org mode (which will then use its own display table).
  969. Changing this requires executing `\\[org-mode]' in a buffer to become
  970. effective."
  971. :group 'org-startup
  972. :type '(choice (const :tag "Default" nil)
  973. (string :tag "String" :value "...#"))
  974. :safe #'string-or-null-p)
  975. (defvar org-display-table nil
  976. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  977. (defgroup org-keywords nil
  978. "Keywords in Org mode."
  979. :tag "Org Keywords"
  980. :group 'org)
  981. (defcustom org-closed-keep-when-no-todo nil
  982. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  983. :group 'org-todo
  984. :group 'org-keywords
  985. :version "24.4"
  986. :package-version '(Org . "8.0")
  987. :type 'boolean)
  988. (defgroup org-structure nil
  989. "Options concerning the general structure of Org files."
  990. :tag "Org Structure"
  991. :group 'org)
  992. (defgroup org-reveal-location nil
  993. "Options about how to make context of a location visible."
  994. :tag "Org Reveal Location"
  995. :group 'org-structure)
  996. (defcustom org-show-context-detail '((agenda . local)
  997. (bookmark-jump . lineage)
  998. (isearch . lineage)
  999. (default . ancestors))
  1000. "Alist between context and visibility span when revealing a location.
  1001. \\<org-mode-map>Some actions may move point into invisible
  1002. locations. As a consequence, Org always expose a neighborhood
  1003. around point. How much is shown depends on the initial action,
  1004. or context. Valid contexts are
  1005. agenda when exposing an entry from the agenda
  1006. org-goto when using the command `org-goto' (`\\[org-goto]')
  1007. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1008. tags-tree when constructing a sparse tree based on tags matches
  1009. link-search when exposing search matches associated with a link
  1010. mark-goto when exposing the jump goal of a mark
  1011. bookmark-jump when exposing a bookmark location
  1012. isearch when exiting from an incremental search
  1013. default default for all contexts not set explicitly
  1014. Allowed visibility spans are
  1015. minimal show current headline; if point is not on headline,
  1016. also show entry
  1017. local show current headline, entry and next headline
  1018. ancestors show current headline and its direct ancestors; if
  1019. point is not on headline, also show entry
  1020. lineage show current headline, its direct ancestors and all
  1021. their children; if point is not on headline, also show
  1022. entry and first child
  1023. tree show current headline, its direct ancestors and all
  1024. their children; if point is not on headline, also show
  1025. entry and all children
  1026. canonical show current headline, its direct ancestors along with
  1027. their entries and children; if point is not located on
  1028. the headline, also show current entry and all children
  1029. As special cases, a nil or t value means show all contexts in
  1030. `minimal' or `canonical' view, respectively.
  1031. Some views can make displayed information very compact, but also
  1032. make it harder to edit the location of the match. In such
  1033. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1034. more context."
  1035. :group 'org-reveal-location
  1036. :version "26.1"
  1037. :package-version '(Org . "9.0")
  1038. :type '(choice
  1039. (const :tag "Canonical" t)
  1040. (const :tag "Minimal" nil)
  1041. (repeat :greedy t :tag "Individual contexts"
  1042. (cons
  1043. (choice :tag "Context"
  1044. (const agenda)
  1045. (const org-goto)
  1046. (const occur-tree)
  1047. (const tags-tree)
  1048. (const link-search)
  1049. (const mark-goto)
  1050. (const bookmark-jump)
  1051. (const isearch)
  1052. (const default))
  1053. (choice :tag "Detail level"
  1054. (const minimal)
  1055. (const local)
  1056. (const ancestors)
  1057. (const lineage)
  1058. (const tree)
  1059. (const canonical))))))
  1060. (defcustom org-indirect-buffer-display 'other-window
  1061. "How should indirect tree buffers be displayed?
  1062. This applies to indirect buffers created with the commands
  1063. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1064. Valid values are:
  1065. current-window Display in the current window
  1066. other-window Just display in another window.
  1067. dedicated-frame Create one new frame, and re-use it each time.
  1068. new-frame Make a new frame each time. Note that in this case
  1069. previously-made indirect buffers are kept, and you need to
  1070. kill these buffers yourself."
  1071. :group 'org-structure
  1072. :group 'org-agenda-windows
  1073. :type '(choice
  1074. (const :tag "In current window" current-window)
  1075. (const :tag "In current frame, other window" other-window)
  1076. (const :tag "Each time a new frame" new-frame)
  1077. (const :tag "One dedicated frame" dedicated-frame)))
  1078. (defcustom org-use-speed-commands nil
  1079. "Non-nil means activate single letter commands at beginning of a headline.
  1080. This may also be a function to test for appropriate locations where speed
  1081. commands should be active.
  1082. For example, to activate speed commands when the point is on any
  1083. star at the beginning of the headline, you can do this:
  1084. (setq org-use-speed-commands
  1085. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1086. :group 'org-structure
  1087. :type '(choice
  1088. (const :tag "Never" nil)
  1089. (const :tag "At beginning of headline stars" t)
  1090. (function)))
  1091. (defcustom org-speed-commands-user nil
  1092. "Alist of additional speed commands.
  1093. This list will be checked before `org-speed-commands-default'
  1094. when the variable `org-use-speed-commands' is non-nil
  1095. and when the cursor is at the beginning of a headline.
  1096. The car if each entry is a string with a single letter, which must
  1097. be assigned to `self-insert-command' in the global map.
  1098. The cdr is either a command to be called interactively, a function
  1099. to be called, or a form to be evaluated.
  1100. An entry that is just a list with a single string will be interpreted
  1101. as a descriptive headline that will be added when listing the speed
  1102. commands in the Help buffer using the `?' speed command."
  1103. :group 'org-structure
  1104. :type '(repeat :value ("k" . ignore)
  1105. (choice :value ("k" . ignore)
  1106. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1107. (cons :tag "Letter and Command"
  1108. (string :tag "Command letter")
  1109. (choice
  1110. (function)
  1111. (sexp))))))
  1112. (defcustom org-bookmark-names-plist
  1113. '(:last-capture "org-capture-last-stored"
  1114. :last-refile "org-refile-last-stored"
  1115. :last-capture-marker "org-capture-last-stored-marker")
  1116. "Names for bookmarks automatically set by some Org commands.
  1117. This can provide strings as names for a number of bookmarks Org sets
  1118. automatically. The following keys are currently implemented:
  1119. :last-capture
  1120. :last-capture-marker
  1121. :last-refile
  1122. When a key does not show up in the property list, the corresponding bookmark
  1123. is not set."
  1124. :group 'org-structure
  1125. :type 'plist)
  1126. (defgroup org-cycle nil
  1127. "Options concerning visibility cycling in Org mode."
  1128. :tag "Org Cycle"
  1129. :group 'org-structure)
  1130. (defcustom org-cycle-skip-children-state-if-no-children t
  1131. "Non-nil means skip CHILDREN state in entries that don't have any."
  1132. :group 'org-cycle
  1133. :type 'boolean)
  1134. (defcustom org-cycle-max-level nil
  1135. "Maximum level which should still be subject to visibility cycling.
  1136. Levels higher than this will, for cycling, be treated as text, not a headline.
  1137. When `org-odd-levels-only' is set, a value of N in this variable actually
  1138. means 2N-1 stars as the limiting headline.
  1139. When nil, cycle all levels.
  1140. Note that the limiting level of cycling is also influenced by
  1141. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1142. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1143. than its value."
  1144. :group 'org-cycle
  1145. :type '(choice
  1146. (const :tag "No limit" nil)
  1147. (integer :tag "Maximum level")))
  1148. (defcustom org-hide-block-startup nil
  1149. "Non-nil means entering Org mode will fold all blocks.
  1150. This can also be set in on a per-file basis with
  1151. #+STARTUP: hideblocks
  1152. #+STARTUP: showblocks"
  1153. :group 'org-startup
  1154. :group 'org-cycle
  1155. :type 'boolean)
  1156. (defcustom org-cycle-global-at-bob nil
  1157. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1158. This makes it possible to do global cycling without having to use `S-TAB'
  1159. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1160. line of the buffer
  1161. must not be a headline -- it may be empty or some other text.
  1162. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1163. sure the cursor stays at the beginning of the buffer.
  1164. When this option is nil, don't do anything special at the beginning of
  1165. the buffer."
  1166. :group 'org-cycle
  1167. :type 'boolean)
  1168. (defcustom org-cycle-level-after-item/entry-creation t
  1169. "Non-nil means cycle entry level or item indentation in new empty entries.
  1170. When the cursor is at the end of an empty headline, i.e., with only stars
  1171. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1172. and then all possible ancestor states, before returning to the original state.
  1173. This makes data entry extremely fast: M-RET to create a new headline,
  1174. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1175. When the cursor is at the end of an empty plain list item, one TAB will
  1176. make it a subitem, two or more tabs will back up to make this an item
  1177. higher up in the item hierarchy."
  1178. :group 'org-cycle
  1179. :type 'boolean)
  1180. (defcustom org-cycle-emulate-tab t
  1181. "Where should `org-cycle' emulate TAB.
  1182. nil Never
  1183. white Only in completely white lines
  1184. whitestart Only at the beginning of lines, before the first non-white char
  1185. t Everywhere except in headlines
  1186. exc-hl-bol Everywhere except at the start of a headline
  1187. If TAB is used in a place where it does not emulate TAB, the current subtree
  1188. visibility is cycled."
  1189. :group 'org-cycle
  1190. :type '(choice (const :tag "Never" nil)
  1191. (const :tag "Only in completely white lines" white)
  1192. (const :tag "Before first char in a line" whitestart)
  1193. (const :tag "Everywhere except in headlines" t)
  1194. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1195. (defcustom org-cycle-separator-lines 2
  1196. "Number of empty lines needed to keep an empty line between collapsed trees.
  1197. If you leave an empty line between the end of a subtree and the following
  1198. headline, this empty line is hidden when the subtree is folded.
  1199. Org mode will leave (exactly) one empty line visible if the number of
  1200. empty lines is equal or larger to the number given in this variable.
  1201. So the default 2 means at least 2 empty lines after the end of a subtree
  1202. are needed to produce free space between a collapsed subtree and the
  1203. following headline.
  1204. If the number is negative, and the number of empty lines is at least -N,
  1205. all empty lines are shown.
  1206. Special case: when 0, never leave empty lines in collapsed view."
  1207. :group 'org-cycle
  1208. :type 'integer)
  1209. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1210. (defcustom org-pre-cycle-hook nil
  1211. "Hook that is run before visibility cycling is happening.
  1212. The function(s) in this hook must accept a single argument which indicates
  1213. the new state that will be set right after running this hook. The
  1214. argument is a symbol. Before a global state change, it can have the values
  1215. `overview', `content', or `all'. Before a local state change, it can have
  1216. the values `folded', `children', or `subtree'."
  1217. :group 'org-cycle
  1218. :type 'hook)
  1219. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1220. org-cycle-hide-drawers
  1221. org-cycle-show-empty-lines
  1222. org-optimize-window-after-visibility-change)
  1223. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1224. The function(s) in this hook must accept a single argument which indicates
  1225. the new state that was set by the most recent `org-cycle' command. The
  1226. argument is a symbol. After a global state change, it can have the values
  1227. `overview', `contents', or `all'. After a local state change, it can have
  1228. the values `folded', `children', or `subtree'."
  1229. :group 'org-cycle
  1230. :type 'hook
  1231. :version "26.1"
  1232. :package-version '(Org . "8.3"))
  1233. (defgroup org-edit-structure nil
  1234. "Options concerning structure editing in Org mode."
  1235. :tag "Org Edit Structure"
  1236. :group 'org-structure)
  1237. (defcustom org-odd-levels-only nil
  1238. "Non-nil means skip even levels and only use odd levels for the outline.
  1239. This has the effect that two stars are being added/taken away in
  1240. promotion/demotion commands. It also influences how levels are
  1241. handled by the exporters.
  1242. Changing it requires restart of `font-lock-mode' to become effective
  1243. for fontification also in regions already fontified.
  1244. You may also set this on a per-file basis by adding one of the following
  1245. lines to the buffer:
  1246. #+STARTUP: odd
  1247. #+STARTUP: oddeven"
  1248. :group 'org-edit-structure
  1249. :group 'org-appearance
  1250. :type 'boolean)
  1251. (defcustom org-adapt-indentation t
  1252. "Non-nil means adapt indentation to outline node level.
  1253. When this variable is set, Org assumes that you write outlines by
  1254. indenting text in each node to align with the headline (after the
  1255. stars). The following issues are influenced by this variable:
  1256. - The indentation is increased by one space in a demotion
  1257. command, and decreased by one in a promotion command. However,
  1258. in the latter case, if shifting some line in the entry body
  1259. would alter document structure (e.g., insert a new headline),
  1260. indentation is not changed at all.
  1261. - Property drawers and planning information is inserted indented
  1262. when this variable is set. When nil, they will not be indented.
  1263. - TAB indents a line relative to current level. The lines below
  1264. a headline will be indented when this variable is set.
  1265. Note that this is all about true indentation, by adding and
  1266. removing space characters. See also `org-indent.el' which does
  1267. level-dependent indentation in a virtual way, i.e. at display
  1268. time in Emacs."
  1269. :group 'org-edit-structure
  1270. :type 'boolean)
  1271. (defcustom org-special-ctrl-a/e nil
  1272. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1273. When t, `C-a' will bring back the cursor to the beginning of the
  1274. headline text, i.e. after the stars and after a possible TODO
  1275. keyword. In an item, this will be the position after bullet and
  1276. check-box, if any. When the cursor is already at that position,
  1277. another `C-a' will bring it to the beginning of the line.
  1278. `C-e' will jump to the end of the headline, ignoring the presence
  1279. of tags in the headline. A second `C-e' will then jump to the
  1280. true end of the line, after any tags. This also means that, when
  1281. this variable is non-nil, `C-e' also will never jump beyond the
  1282. end of the heading of a folded section, i.e. not after the
  1283. ellipses.
  1284. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1285. normally, going to the true line boundary first. Only a directly
  1286. following, identical keypress will bring the cursor to the
  1287. special positions.
  1288. This may also be a cons cell where the behavior for `C-a' and
  1289. `C-e' is set separately."
  1290. :group 'org-edit-structure
  1291. :type '(choice
  1292. (const :tag "off" nil)
  1293. (const :tag "on: after stars/bullet and before tags first" t)
  1294. (const :tag "reversed: true line boundary first" reversed)
  1295. (cons :tag "Set C-a and C-e separately"
  1296. (choice :tag "Special C-a"
  1297. (const :tag "off" nil)
  1298. (const :tag "on: after stars/bullet first" t)
  1299. (const :tag "reversed: before stars/bullet first" reversed))
  1300. (choice :tag "Special C-e"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: before tags first" t)
  1303. (const :tag "reversed: after tags first" reversed)))))
  1304. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1305. (defcustom org-special-ctrl-k nil
  1306. "Non-nil means `C-k' will behave specially in headlines.
  1307. When nil, `C-k' will call the default `kill-line' command.
  1308. When t, the following will happen while the cursor is in the headline:
  1309. - When the cursor is at the beginning of a headline, kill the entire
  1310. line and possible the folded subtree below the line.
  1311. - When in the middle of the headline text, kill the headline up to the tags.
  1312. - When after the headline text, kill the tags."
  1313. :group 'org-edit-structure
  1314. :type 'boolean)
  1315. (defcustom org-ctrl-k-protect-subtree nil
  1316. "Non-nil means, do not delete a hidden subtree with C-k.
  1317. When set to the symbol `error', simply throw an error when C-k is
  1318. used to kill (part-of) a headline that has hidden text behind it.
  1319. Any other non-nil value will result in a query to the user, if it is
  1320. OK to kill that hidden subtree. When nil, kill without remorse."
  1321. :group 'org-edit-structure
  1322. :version "24.1"
  1323. :type '(choice
  1324. (const :tag "Do not protect hidden subtrees" nil)
  1325. (const :tag "Protect hidden subtrees with a security query" t)
  1326. (const :tag "Never kill a hidden subtree with C-k" error)))
  1327. (defcustom org-special-ctrl-o t
  1328. "Non-nil means, make `C-o' insert a row in tables."
  1329. :group 'org-edit-structure
  1330. :type 'boolean)
  1331. (defcustom org-catch-invisible-edits nil
  1332. "Check if in invisible region before inserting or deleting a character.
  1333. Valid values are:
  1334. nil Do not check, so just do invisible edits.
  1335. error Throw an error and do nothing.
  1336. show Make point visible, and do the requested edit.
  1337. show-and-error Make point visible, then throw an error and abort the edit.
  1338. smart Make point visible, and do insertion/deletion if it is
  1339. adjacent to visible text and the change feels predictable.
  1340. Never delete a previously invisible character or add in the
  1341. middle or right after an invisible region. Basically, this
  1342. allows insertion and backward-delete right before ellipses.
  1343. FIXME: maybe in this case we should not even show?"
  1344. :group 'org-edit-structure
  1345. :version "24.1"
  1346. :type '(choice
  1347. (const :tag "Do not check" nil)
  1348. (const :tag "Throw error when trying to edit" error)
  1349. (const :tag "Unhide, but do not do the edit" show-and-error)
  1350. (const :tag "Show invisible part and do the edit" show)
  1351. (const :tag "Be smart and do the right thing" smart)))
  1352. (defcustom org-yank-folded-subtrees t
  1353. "Non-nil means when yanking subtrees, fold them.
  1354. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1355. it starts with a heading and all other headings in it are either children
  1356. or siblings, then fold all the subtrees. However, do this only if no
  1357. text after the yank would be swallowed into a folded tree by this action."
  1358. :group 'org-edit-structure
  1359. :type 'boolean)
  1360. (defcustom org-yank-adjusted-subtrees nil
  1361. "Non-nil means when yanking subtrees, adjust the level.
  1362. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1363. this function for details."
  1364. :group 'org-edit-structure
  1365. :type 'boolean)
  1366. (defcustom org-M-RET-may-split-line '((default . t))
  1367. "Non-nil means M-RET will split the line at the cursor position.
  1368. When nil, it will go to the end of the line before making a
  1369. new line.
  1370. You may also set this option in a different way for different
  1371. contexts. Valid contexts are:
  1372. headline when creating a new headline
  1373. item when creating a new item
  1374. table in a table field
  1375. default the value to be used for all contexts not explicitly
  1376. customized"
  1377. :group 'org-structure
  1378. :group 'org-table
  1379. :type '(choice
  1380. (const :tag "Always" t)
  1381. (const :tag "Never" nil)
  1382. (repeat :greedy t :tag "Individual contexts"
  1383. (cons
  1384. (choice :tag "Context"
  1385. (const headline)
  1386. (const item)
  1387. (const table)
  1388. (const default))
  1389. (boolean)))))
  1390. (defcustom org-insert-heading-respect-content nil
  1391. "Non-nil means insert new headings after the current subtree.
  1392. \\<org-mode-map>
  1393. When nil, the new heading is created directly after the current line.
  1394. The commands `\\[org-insert-heading-respect-content]' and \
  1395. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1396. for the duration of the command."
  1397. :group 'org-structure
  1398. :type 'boolean)
  1399. (defcustom org-blank-before-new-entry '((heading . auto)
  1400. (plain-list-item . auto))
  1401. "Should `org-insert-heading' leave a blank line before new heading/item?
  1402. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1403. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1404. which case Org will look at the surrounding headings/items and try to
  1405. make an intelligent decision whether to insert a blank line or not."
  1406. :group 'org-edit-structure
  1407. :type '(list
  1408. (cons (const heading)
  1409. (choice (const :tag "Never" nil)
  1410. (const :tag "Always" t)
  1411. (const :tag "Auto" auto)))
  1412. (cons (const plain-list-item)
  1413. (choice (const :tag "Never" nil)
  1414. (const :tag "Always" t)
  1415. (const :tag "Auto" auto)))))
  1416. (defcustom org-insert-heading-hook nil
  1417. "Hook being run after inserting a new heading."
  1418. :group 'org-edit-structure
  1419. :type 'hook)
  1420. (defcustom org-enable-fixed-width-editor t
  1421. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1422. This currently only means they are never auto-wrapped.
  1423. When nil, such lines will be treated like ordinary lines."
  1424. :group 'org-edit-structure
  1425. :type 'boolean)
  1426. (defcustom org-goto-auto-isearch t
  1427. "Non-nil means typing characters in `org-goto' starts incremental search.
  1428. When nil, you can use these keybindings to navigate the buffer:
  1429. q Quit the org-goto interface
  1430. n Go to the next visible heading
  1431. p Go to the previous visible heading
  1432. f Go one heading forward on same level
  1433. b Go one heading backward on same level
  1434. u Go one heading up"
  1435. :group 'org-edit-structure
  1436. :type 'boolean)
  1437. (defgroup org-sparse-trees nil
  1438. "Options concerning sparse trees in Org mode."
  1439. :tag "Org Sparse Trees"
  1440. :group 'org-structure)
  1441. (defcustom org-highlight-sparse-tree-matches t
  1442. "Non-nil means highlight all matches that define a sparse tree.
  1443. The highlights will automatically disappear the next time the buffer is
  1444. changed by an edit command."
  1445. :group 'org-sparse-trees
  1446. :type 'boolean)
  1447. (defcustom org-remove-highlights-with-change t
  1448. "Non-nil means any change to the buffer will remove temporary highlights.
  1449. \\<org-mode-map>\
  1450. Such highlights are created by `org-occur' and `org-clock-display'.
  1451. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1452. to get rid of the highlights.
  1453. The highlights created by `org-toggle-latex-fragment' always need
  1454. `\\[org-toggle-latex-fragment]' to be removed."
  1455. :group 'org-sparse-trees
  1456. :group 'org-time
  1457. :type 'boolean)
  1458. (defcustom org-occur-case-fold-search t
  1459. "Non-nil means `org-occur' should be case-insensitive.
  1460. If set to `smart' the search will be case-insensitive only if it
  1461. doesn't specify any upper case character."
  1462. :group 'org-sparse-trees
  1463. :version "26.1"
  1464. :type '(choice
  1465. (const :tag "Case-sensitive" nil)
  1466. (const :tag "Case-insensitive" t)
  1467. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1468. (defcustom org-occur-hook '(org-first-headline-recenter)
  1469. "Hook that is run after `org-occur' has constructed a sparse tree.
  1470. This can be used to recenter the window to show as much of the structure
  1471. as possible."
  1472. :group 'org-sparse-trees
  1473. :type 'hook)
  1474. (defgroup org-imenu-and-speedbar nil
  1475. "Options concerning imenu and speedbar in Org mode."
  1476. :tag "Org Imenu and Speedbar"
  1477. :group 'org-structure)
  1478. (defcustom org-imenu-depth 2
  1479. "The maximum level for Imenu access to Org headlines.
  1480. This also applied for speedbar access."
  1481. :group 'org-imenu-and-speedbar
  1482. :type 'integer)
  1483. (defgroup org-table nil
  1484. "Options concerning tables in Org mode."
  1485. :tag "Org Table"
  1486. :group 'org)
  1487. (defcustom org-enable-table-editor 'optimized
  1488. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1489. When nil, such lines will be treated like ordinary lines.
  1490. When equal to the symbol `optimized', the table editor will be optimized to
  1491. do the following:
  1492. - Automatic overwrite mode in front of whitespace in table fields.
  1493. This makes the structure of the table stay in tact as long as the edited
  1494. field does not exceed the column width.
  1495. - Minimize the number of realigns. Normally, the table is aligned each time
  1496. TAB or RET are pressed to move to another field. With optimization this
  1497. happens only if changes to a field might have changed the column width.
  1498. Optimization requires replacing the functions `self-insert-command',
  1499. `delete-char', and `backward-delete-char' in Org buffers, with a
  1500. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1501. good at guessing when a re-align will be necessary, but you can always
  1502. force one with `\\[org-ctrl-c-ctrl-c]'.
  1503. If you would like to use the optimized version in Org mode, but the
  1504. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1505. This variable can be used to turn on and off the table editor during a session,
  1506. but in order to toggle optimization, a restart is required.
  1507. See also the variable `org-table-auto-blank-field'."
  1508. :group 'org-table
  1509. :type '(choice
  1510. (const :tag "off" nil)
  1511. (const :tag "on" t)
  1512. (const :tag "on, optimized" optimized)))
  1513. (defcustom org-self-insert-cluster-for-undo nil
  1514. "Non-nil means cluster self-insert commands for undo when possible.
  1515. If this is set, then, like in the Emacs command loop, 20 consecutive
  1516. characters will be undone together.
  1517. This is configurable, because there is some impact on typing performance."
  1518. :group 'org-table
  1519. :type 'boolean)
  1520. (defcustom org-table-tab-recognizes-table.el t
  1521. "Non-nil means TAB will automatically notice a table.el table.
  1522. When it sees such a table, it moves point into it and - if necessary -
  1523. calls `table-recognize-table'."
  1524. :group 'org-table-editing
  1525. :type 'boolean)
  1526. (defgroup org-link nil
  1527. "Options concerning links in Org mode."
  1528. :tag "Org Link"
  1529. :group 'org)
  1530. (defvar-local org-link-abbrev-alist-local nil
  1531. "Buffer-local version of `org-link-abbrev-alist', which see.
  1532. The value of this is taken from the #+LINK lines.")
  1533. (defcustom org-link-parameters
  1534. '(("doi" :follow org--open-doi-link)
  1535. ("elisp" :follow org--open-elisp-link)
  1536. ("file" :complete org-file-complete-link)
  1537. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1538. ("help" :follow org--open-help-link)
  1539. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1540. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1541. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1542. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1543. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1544. ("shell" :follow org--open-shell-link))
  1545. "An alist of properties that defines all the links in Org mode.
  1546. The key in each association is a string of the link type.
  1547. Subsequent optional elements make up a p-list of link properties.
  1548. :follow - A function that takes the link path as an argument.
  1549. :export - A function that takes the link path, description and
  1550. export-backend as arguments.
  1551. :store - A function responsible for storing the link. See the
  1552. function `org-store-link-functions'.
  1553. :complete - A function that inserts a link with completion. The
  1554. function takes one optional prefix arg.
  1555. :face - A face for the link, or a function that returns a face.
  1556. The function takes one argument which is the link path. The
  1557. default face is `org-link'.
  1558. :mouse-face - The mouse-face. The default is `highlight'.
  1559. :display - `full' will not fold the link in descriptive
  1560. display. Default is `org-link'.
  1561. :help-echo - A string or function that takes (window object position)
  1562. as arguments and returns a string.
  1563. :keymap - A keymap that is active on the link. The default is
  1564. `org-mouse-map'.
  1565. :htmlize-link - A function for the htmlize-link. Defaults
  1566. to (list :uri \"type:path\")
  1567. :activate-func - A function to run at the end of font-lock
  1568. activation. The function must accept (link-start link-end path bracketp)
  1569. as arguments."
  1570. :group 'org-link
  1571. :type '(alist :tag "Link display parameters"
  1572. :value-type plist))
  1573. (defun org-link-get-parameter (type key)
  1574. "Get TYPE link property for KEY.
  1575. TYPE is a string and KEY is a plist keyword."
  1576. (plist-get
  1577. (cdr (assoc type org-link-parameters))
  1578. key))
  1579. (defun org-link-set-parameters (type &rest parameters)
  1580. "Set link TYPE properties to PARAMETERS.
  1581. PARAMETERS should be :key val pairs."
  1582. (let ((data (assoc type org-link-parameters)))
  1583. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1584. (push (cons type parameters) org-link-parameters)
  1585. (org-make-link-regexps)
  1586. (org-element-update-syntax))))
  1587. (defun org-link-types ()
  1588. "Return a list of known link types."
  1589. (mapcar #'car org-link-parameters))
  1590. (defcustom org-link-abbrev-alist nil
  1591. "Alist of link abbreviations.
  1592. The car of each element is a string, to be replaced at the start of a link.
  1593. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1594. links in Org buffers can have an optional tag after a double colon, e.g.,
  1595. [[linkkey:tag][description]]
  1596. The `linkkey' must be a single word, starting with a letter, followed
  1597. by letters, numbers, `-' or `_'.
  1598. If REPLACE is a string, the tag will simply be appended to create the link.
  1599. If the string contains \"%s\", the tag will be inserted there. If the string
  1600. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1601. at that point (see the function `url-hexify-string'). If the string contains
  1602. the specifier \"%(my-function)\", then the custom function `my-function' will
  1603. be invoked: this function takes the tag as its only argument and must return
  1604. a string.
  1605. REPLACE may also be a function that will be called with the tag as the
  1606. only argument to create the link, which should be returned as a string.
  1607. See the manual for examples."
  1608. :group 'org-link
  1609. :type '(repeat
  1610. (cons
  1611. (string :tag "Protocol")
  1612. (choice
  1613. (string :tag "Format")
  1614. (function)))))
  1615. (defcustom org-descriptive-links t
  1616. "Non-nil means Org will display descriptive links.
  1617. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1618. \"Org Website\", hiding the link itself and just displaying its
  1619. description. When set to nil, Org will display the full links
  1620. literally.
  1621. You can interactively set the value of this variable by calling
  1622. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1623. :group 'org-link
  1624. :type 'boolean)
  1625. (defcustom org-link-file-path-type 'adaptive
  1626. "How the path name in file links should be stored.
  1627. Valid values are:
  1628. relative Relative to the current directory, i.e. the directory of the file
  1629. into which the link is being inserted.
  1630. absolute Absolute path, if possible with ~ for home directory.
  1631. noabbrev Absolute path, no abbreviation of home directory.
  1632. adaptive Use relative path for files in the current directory and sub-
  1633. directories of it. For other files, use an absolute path."
  1634. :group 'org-link
  1635. :type '(choice
  1636. (const relative)
  1637. (const absolute)
  1638. (const noabbrev)
  1639. (const adaptive)))
  1640. (defvaralias 'org-activate-links 'org-highlight-links)
  1641. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1642. "Types of links that should be highlighted in Org files.
  1643. This is a list of symbols, each one of them leading to the
  1644. highlighting of a certain link type.
  1645. You can still open links that are not highlighted.
  1646. In principle, it does not hurt to turn on highlighting for all
  1647. link types. There may be a small gain when turning off unused
  1648. link types. The types are:
  1649. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1650. angle Links in angular brackets that may contain whitespace like
  1651. <bbdb:Carsten Dominik>.
  1652. plain Plain links in normal text, no whitespace, like http://google.com.
  1653. radio Text that is matched by a radio target, see manual for details.
  1654. tag Tag settings in a headline (link to tag search).
  1655. date Time stamps (link to calendar).
  1656. footnote Footnote labels.
  1657. If you set this variable during an Emacs session, use `org-mode-restart'
  1658. in the Org buffer so that the change takes effect."
  1659. :group 'org-link
  1660. :group 'org-appearance
  1661. :type '(set :greedy t
  1662. (const :tag "Double bracket links" bracket)
  1663. (const :tag "Angular bracket links" angle)
  1664. (const :tag "Plain text links" plain)
  1665. (const :tag "Radio target matches" radio)
  1666. (const :tag "Tags" tag)
  1667. (const :tag "Timestamps" date)
  1668. (const :tag "Footnotes" footnote)))
  1669. (defcustom org-make-link-description-function nil
  1670. "Function to use for generating link descriptions from links.
  1671. When nil, the link location will be used. This function must take
  1672. two parameters: the first one is the link, the second one is the
  1673. description generated by `org-insert-link'. The function should
  1674. return the description to use."
  1675. :group 'org-link
  1676. :type '(choice (const nil) (function)))
  1677. (defgroup org-link-store nil
  1678. "Options concerning storing links in Org mode."
  1679. :tag "Org Store Link"
  1680. :group 'org-link)
  1681. (defcustom org-url-hexify-p t
  1682. "When non-nil, hexify URL when creating a link."
  1683. :type 'boolean
  1684. :version "24.3"
  1685. :group 'org-link-store)
  1686. (defcustom org-email-link-description-format "Email %c: %.30s"
  1687. "Format of the description part of a link to an email or usenet message.
  1688. The following %-escapes will be replaced by corresponding information:
  1689. %F full \"From\" field
  1690. %f name, taken from \"From\" field, address if no name
  1691. %T full \"To\" field
  1692. %t first name in \"To\" field, address if no name
  1693. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1694. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1695. %s subject
  1696. %d date
  1697. %m message-id.
  1698. You may use normal field width specification between the % and the letter.
  1699. This is for example useful to limit the length of the subject.
  1700. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1701. :group 'org-link-store
  1702. :type 'string)
  1703. (defcustom org-from-is-user-regexp
  1704. (let (r1 r2)
  1705. (when (and user-mail-address (not (string= user-mail-address "")))
  1706. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1707. (when (and user-full-name (not (string= user-full-name "")))
  1708. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1709. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1710. "Regexp matched against the \"From:\" header of an email or usenet message.
  1711. It should match if the message is from the user him/herself."
  1712. :group 'org-link-store
  1713. :type 'regexp)
  1714. (defcustom org-context-in-file-links t
  1715. "Non-nil means file links from `org-store-link' contain context.
  1716. \\<org-mode-map>
  1717. A search string will be added to the file name with :: as separator
  1718. and used to find the context when the link is activated by the command
  1719. `org-open-at-point'. When this option is t, the entire active region
  1720. will be placed in the search string of the file link. If set to a
  1721. positive integer, only the first n lines of context will be stored.
  1722. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1723. \\[org-store-link]')
  1724. negates this setting for the duration of the command."
  1725. :group 'org-link-store
  1726. :type '(choice boolean integer))
  1727. (defcustom org-keep-stored-link-after-insertion nil
  1728. "Non-nil means keep link in list for entire session.
  1729. \\<org-mode-map>
  1730. The command `org-store-link' adds a link pointing to the current
  1731. location to an internal list. These links accumulate during a session.
  1732. The command `org-insert-link' can be used to insert links into any
  1733. Org file (offering completion for all stored links).
  1734. When this option is nil, every link which has been inserted once using
  1735. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1736. unused
  1737. links more efficient."
  1738. :group 'org-link-store
  1739. :type 'boolean)
  1740. (defgroup org-link-follow nil
  1741. "Options concerning following links in Org mode."
  1742. :tag "Org Follow Link"
  1743. :group 'org-link)
  1744. (defcustom org-link-translation-function nil
  1745. "Function to translate links with different syntax to Org syntax.
  1746. This can be used to translate links created for example by the Planner
  1747. or emacs-wiki packages to Org syntax.
  1748. The function must accept two parameters, a TYPE containing the link
  1749. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1750. which is everything after the link protocol. It should return a cons
  1751. with possibly modified values of type and path.
  1752. Org contains a function for this, so if you set this variable to
  1753. `org-translate-link-from-planner', you should be able follow many
  1754. links created by planner."
  1755. :group 'org-link-follow
  1756. :type '(choice (const nil) (function)))
  1757. (defcustom org-follow-link-hook nil
  1758. "Hook that is run after a link has been followed."
  1759. :group 'org-link-follow
  1760. :type 'hook)
  1761. (defcustom org-tab-follows-link nil
  1762. "Non-nil means on links TAB will follow the link.
  1763. Needs to be set before org.el is loaded.
  1764. This really should not be used, it does not make sense, and the
  1765. implementation is bad."
  1766. :group 'org-link-follow
  1767. :type 'boolean)
  1768. (defcustom org-return-follows-link nil
  1769. "Non-nil means on links RET will follow the link.
  1770. In tables, the special behavior of RET has precedence."
  1771. :group 'org-link-follow
  1772. :type 'boolean)
  1773. (defcustom org-mouse-1-follows-link
  1774. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1775. "Non-nil means mouse-1 on a link will follow the link.
  1776. A longer mouse click will still set point. Needs to be set
  1777. before org.el is loaded."
  1778. :group 'org-link-follow
  1779. :version "24.4"
  1780. :package-version '(Org . "8.3")
  1781. :type '(choice
  1782. (const :tag "A double click follows the link" double)
  1783. (const :tag "Unconditionally follow the link with mouse-1" t)
  1784. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1785. (defcustom org-mark-ring-length 4
  1786. "Number of different positions to be recorded in the ring.
  1787. Changing this requires a restart of Emacs to work correctly."
  1788. :group 'org-link-follow
  1789. :type 'integer)
  1790. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1791. "Non-nil means internal fuzzy links can only match headlines.
  1792. When nil, the a fuzzy link may point to a target or a named
  1793. construct in the document. When set to the special value
  1794. `query-to-create', offer to create a new headline when none
  1795. matched.
  1796. Spaces and statistics cookies are ignored during heading searches."
  1797. :group 'org-link-follow
  1798. :version "24.1"
  1799. :type '(choice
  1800. (const :tag "Use fuzzy text search" nil)
  1801. (const :tag "Match only exact headline" t)
  1802. (const :tag "Match exact headline or query to create it"
  1803. query-to-create))
  1804. :safe #'symbolp)
  1805. (defcustom org-link-frame-setup
  1806. '((vm . vm-visit-folder-other-frame)
  1807. (vm-imap . vm-visit-imap-folder-other-frame)
  1808. (gnus . org-gnus-no-new-news)
  1809. (file . find-file-other-window)
  1810. (wl . wl-other-frame))
  1811. "Setup the frame configuration for following links.
  1812. When following a link with Emacs, it may often be useful to display
  1813. this link in another window or frame. This variable can be used to
  1814. set this up for the different types of links.
  1815. For VM, use any of
  1816. `vm-visit-folder'
  1817. `vm-visit-folder-other-window'
  1818. `vm-visit-folder-other-frame'
  1819. For Gnus, use any of
  1820. `gnus'
  1821. `gnus-other-frame'
  1822. `org-gnus-no-new-news'
  1823. For FILE, use any of
  1824. `find-file'
  1825. `find-file-other-window'
  1826. `find-file-other-frame'
  1827. For Wanderlust use any of
  1828. `wl'
  1829. `wl-other-frame'
  1830. For the calendar, use the variable `calendar-setup'.
  1831. For BBDB, it is currently only possible to display the matches in
  1832. another window."
  1833. :group 'org-link-follow
  1834. :type '(list
  1835. (cons (const vm)
  1836. (choice
  1837. (const vm-visit-folder)
  1838. (const vm-visit-folder-other-window)
  1839. (const vm-visit-folder-other-frame)))
  1840. (cons (const vm-imap)
  1841. (choice
  1842. (const vm-visit-imap-folder)
  1843. (const vm-visit-imap-folder-other-window)
  1844. (const vm-visit-imap-folder-other-frame)))
  1845. (cons (const gnus)
  1846. (choice
  1847. (const gnus)
  1848. (const gnus-other-frame)
  1849. (const org-gnus-no-new-news)))
  1850. (cons (const file)
  1851. (choice
  1852. (const find-file)
  1853. (const find-file-other-window)
  1854. (const find-file-other-frame)))
  1855. (cons (const wl)
  1856. (choice
  1857. (const wl)
  1858. (const wl-other-frame)))))
  1859. (defcustom org-display-internal-link-with-indirect-buffer nil
  1860. "Non-nil means use indirect buffer to display infile links.
  1861. Activating internal links (from one location in a file to another location
  1862. in the same file) normally just jumps to the location. When the link is
  1863. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1864. is displayed in
  1865. another window. When this option is set, the other window actually displays
  1866. an indirect buffer clone of the current buffer, to avoid any visibility
  1867. changes to the current buffer."
  1868. :group 'org-link-follow
  1869. :type 'boolean)
  1870. (defcustom org-open-non-existing-files nil
  1871. "Non-nil means `org-open-file' will open non-existing files.
  1872. When nil, an error will be generated.
  1873. This variable applies only to external applications because they
  1874. might choke on non-existing files. If the link is to a file that
  1875. will be opened in Emacs, the variable is ignored."
  1876. :group 'org-link-follow
  1877. :type 'boolean)
  1878. (defcustom org-open-directory-means-index-dot-org nil
  1879. "Non-nil means a link to a directory really means to index.org.
  1880. When nil, following a directory link will run dired or open a finder/explorer
  1881. window on that directory."
  1882. :group 'org-link-follow
  1883. :type 'boolean)
  1884. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1885. "Non-nil means ask for confirmation before executing shell links.
  1886. Shell links can be dangerous: just think about a link
  1887. [[shell:rm -rf ~/*][Google Search]]
  1888. This link would show up in your Org document as \"Google Search\",
  1889. but really it would remove your entire home directory.
  1890. Therefore we advise against setting this variable to nil.
  1891. Just change it to `y-or-n-p' if you want to confirm with a
  1892. single keystroke rather than having to type \"yes\"."
  1893. :group 'org-link-follow
  1894. :type '(choice
  1895. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1896. (const :tag "with y-or-n (faster)" y-or-n-p)
  1897. (const :tag "no confirmation (dangerous)" nil)))
  1898. (put 'org-confirm-shell-link-function
  1899. 'safe-local-variable
  1900. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1901. (defcustom org-confirm-shell-link-not-regexp ""
  1902. "A regexp to skip confirmation for shell links."
  1903. :group 'org-link-follow
  1904. :version "24.1"
  1905. :type 'regexp)
  1906. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1907. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1908. Elisp links can be dangerous: just think about a link
  1909. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1910. This link would show up in your Org document as \"Google Search\",
  1911. but really it would remove your entire home directory.
  1912. Therefore we advise against setting this variable to nil.
  1913. Just change it to `y-or-n-p' if you want to confirm with a
  1914. single keystroke rather than having to type \"yes\"."
  1915. :group 'org-link-follow
  1916. :type '(choice
  1917. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1918. (const :tag "with y-or-n (faster)" y-or-n-p)
  1919. (const :tag "no confirmation (dangerous)" nil)))
  1920. (put 'org-confirm-shell-link-function
  1921. 'safe-local-variable
  1922. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1923. (defcustom org-confirm-elisp-link-not-regexp ""
  1924. "A regexp to skip confirmation for Elisp links."
  1925. :group 'org-link-follow
  1926. :version "24.1"
  1927. :type 'regexp)
  1928. (defconst org-file-apps-defaults-gnu
  1929. '((remote . emacs)
  1930. (system . mailcap)
  1931. (t . mailcap))
  1932. "Default file applications on a UNIX or GNU/Linux system.
  1933. See `org-file-apps'.")
  1934. (defconst org-file-apps-defaults-macosx
  1935. '((remote . emacs)
  1936. (system . "open %s")
  1937. ("ps.gz" . "gv %s")
  1938. ("eps.gz" . "gv %s")
  1939. ("dvi" . "xdvi %s")
  1940. ("fig" . "xfig %s")
  1941. (t . "open %s"))
  1942. "Default file applications on a macOS system.
  1943. The system \"open\" is known as a default, but we use X11 applications
  1944. for some files for which the OS does not have a good default.
  1945. See `org-file-apps'.")
  1946. (defconst org-file-apps-defaults-windowsnt
  1947. (list '(remote . emacs)
  1948. (cons 'system (lambda (file _path)
  1949. (with-no-warnings (w32-shell-execute "open" file))))
  1950. (cons t (lambda (file _path)
  1951. (with-no-warnings (w32-shell-execute "open" file)))))
  1952. "Default file applications on a Windows NT system.
  1953. The system \"open\" is used for most files.
  1954. See `org-file-apps'.")
  1955. (defcustom org-file-apps
  1956. '((auto-mode . emacs)
  1957. ("\\.mm\\'" . default)
  1958. ("\\.x?html?\\'" . default)
  1959. ("\\.pdf\\'" . default))
  1960. "External applications for opening `file:path' items in a document.
  1961. \\<org-mode-map>\
  1962. Org mode uses system defaults for different file types, but
  1963. you can use this variable to set the application for a given file
  1964. extension. The entries in this list are cons cells where the car identifies
  1965. files and the cdr the corresponding command.
  1966. Possible values for the file identifier are:
  1967. \"string\" A string as a file identifier can be interpreted in different
  1968. ways, depending on its contents:
  1969. - Alphanumeric characters only:
  1970. Match links with this file extension.
  1971. Example: (\"pdf\" . \"evince %s\")
  1972. to open PDFs with evince.
  1973. - Regular expression: Match links where the
  1974. filename matches the regexp. If you want to
  1975. use groups here, use shy groups.
  1976. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1977. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1978. to open *.html and *.xhtml with firefox.
  1979. - Regular expression which contains (non-shy) groups:
  1980. Match links where the whole link, including \"::\", and
  1981. anything after that, matches the regexp.
  1982. In a custom command string, %1, %2, etc. are replaced with
  1983. the parts of the link that were matched by the groups.
  1984. For backwards compatibility, if a command string is given
  1985. that does not use any of the group matches, this case is
  1986. handled identically to the second one (i.e. match against
  1987. file name only).
  1988. In a custom function, you can access the group matches with
  1989. (match-string n link).
  1990. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1991. \"evince -p %1 %s\")
  1992. to open [[file:document.pdf::5]] with evince at page 5.
  1993. `directory' Matches a directory
  1994. `remote' Matches a remote file, accessible through tramp or efs.
  1995. Remote files most likely should be visited through Emacs
  1996. because external applications cannot handle such paths.
  1997. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1998. so all files Emacs knows how to handle. Using this with
  1999. command `emacs' will open most files in Emacs. Beware that this
  2000. will also open html files inside Emacs, unless you add
  2001. (\"html\" . default) to the list as well.
  2002. `system' The system command to open files, like `open' on Windows
  2003. and macOS, and mailcap under GNU/Linux. This is the command
  2004. that will be selected if you call `org-open-at-point' with a
  2005. double prefix argument (`\\[universal-argument] \
  2006. \\[universal-argument] \\[org-open-at-point]').
  2007. t Default for files not matched by any of the other options.
  2008. Possible values for the command are:
  2009. `emacs' The file will be visited by the current Emacs process.
  2010. `default' Use the default application for this file type, which is the
  2011. association for t in the list, most likely in the system-specific
  2012. part. This can be used to overrule an unwanted setting in the
  2013. system-specific variable.
  2014. `system' Use the system command for opening files, like \"open\".
  2015. This command is specified by the entry whose car is `system'.
  2016. Most likely, the system-specific version of this variable
  2017. does define this command, but you can overrule/replace it
  2018. here.
  2019. `mailcap' Use command specified in the mailcaps.
  2020. string A command to be executed by a shell; %s will be replaced
  2021. by the path to the file.
  2022. function A Lisp function, which will be called with two arguments:
  2023. the file path and the original link string, without the
  2024. \"file:\" prefix.
  2025. For more examples, see the system specific constants
  2026. `org-file-apps-defaults-macosx'
  2027. `org-file-apps-defaults-windowsnt'
  2028. `org-file-apps-defaults-gnu'."
  2029. :group 'org-link-follow
  2030. :type '(repeat
  2031. (cons (choice :value ""
  2032. (string :tag "Extension")
  2033. (const :tag "System command to open files" system)
  2034. (const :tag "Default for unrecognized files" t)
  2035. (const :tag "Remote file" remote)
  2036. (const :tag "Links to a directory" directory)
  2037. (const :tag "Any files that have Emacs modes"
  2038. auto-mode))
  2039. (choice :value ""
  2040. (const :tag "Visit with Emacs" emacs)
  2041. (const :tag "Use default" default)
  2042. (const :tag "Use the system command" system)
  2043. (string :tag "Command")
  2044. (function :tag "Function")))))
  2045. (defcustom org-doi-server-url "http://dx.doi.org/"
  2046. "The URL of the DOI server."
  2047. :type 'string
  2048. :version "24.3"
  2049. :group 'org-link-follow)
  2050. (defgroup org-refile nil
  2051. "Options concerning refiling entries in Org mode."
  2052. :tag "Org Refile"
  2053. :group 'org)
  2054. (defcustom org-directory "~/org"
  2055. "Directory with Org files.
  2056. This is just a default location to look for Org files. There is no need
  2057. at all to put your files into this directory. It is used in the
  2058. following situations:
  2059. 1. When a capture template specifies a target file that is not an
  2060. absolute path. The path will then be interpreted relative to
  2061. `org-directory'
  2062. 2. When the value of variable `org-agenda-files' is a single file, any
  2063. relative paths in this file will be taken as relative to
  2064. `org-directory'."
  2065. :group 'org-refile
  2066. :group 'org-capture
  2067. :type 'directory)
  2068. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2069. "Default target for storing notes.
  2070. Used as a fall back file for org-capture.el, for templates that
  2071. do not specify a target file."
  2072. :group 'org-refile
  2073. :group 'org-capture
  2074. :type 'file)
  2075. (defcustom org-goto-interface 'outline
  2076. "The default interface to be used for `org-goto'.
  2077. Allowed values are:
  2078. outline The interface shows an outline of the relevant file
  2079. and the correct heading is found by moving through
  2080. the outline or by searching with incremental search.
  2081. outline-path-completion Headlines in the current buffer are offered via
  2082. completion. This is the interface also used by
  2083. the refile command."
  2084. :group 'org-refile
  2085. :type '(choice
  2086. (const :tag "Outline" outline)
  2087. (const :tag "Outline-path-completion" outline-path-completion)))
  2088. (defcustom org-goto-max-level 5
  2089. "Maximum target level when running `org-goto' with refile interface."
  2090. :group 'org-refile
  2091. :type 'integer)
  2092. (defcustom org-reverse-note-order nil
  2093. "Non-nil means store new notes at the beginning of a file or entry.
  2094. When nil, new notes will be filed to the end of a file or entry.
  2095. This can also be a list with cons cells of regular expressions that
  2096. are matched against file names, and values."
  2097. :group 'org-capture
  2098. :group 'org-refile
  2099. :type '(choice
  2100. (const :tag "Reverse always" t)
  2101. (const :tag "Reverse never" nil)
  2102. (repeat :tag "By file name regexp"
  2103. (cons regexp boolean))))
  2104. (defcustom org-log-refile nil
  2105. "Information to record when a task is refiled.
  2106. Possible values are:
  2107. nil Don't add anything
  2108. time Add a time stamp to the task
  2109. note Prompt for a note and add it with template `org-log-note-headings'
  2110. This option can also be set with on a per-file-basis with
  2111. #+STARTUP: nologrefile
  2112. #+STARTUP: logrefile
  2113. #+STARTUP: lognoterefile
  2114. You can have local logging settings for a subtree by setting the LOGGING
  2115. property to one or more of these keywords.
  2116. When bulk-refiling from the agenda, the value `note' is forbidden and
  2117. will temporarily be changed to `time'."
  2118. :group 'org-refile
  2119. :group 'org-progress
  2120. :version "24.1"
  2121. :type '(choice
  2122. (const :tag "No logging" nil)
  2123. (const :tag "Record timestamp" time)
  2124. (const :tag "Record timestamp with note." note)))
  2125. (defcustom org-refile-targets nil
  2126. "Targets for refiling entries with `\\[org-refile]'.
  2127. This is a list of cons cells. Each cell contains:
  2128. - a specification of the files to be considered, either a list of files,
  2129. or a symbol whose function or variable value will be used to retrieve
  2130. a file name or a list of file names. If you use `org-agenda-files' for
  2131. that, all agenda files will be scanned for targets. Nil means consider
  2132. headings in the current buffer.
  2133. - A specification of how to find candidate refile targets. This may be
  2134. any of:
  2135. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2136. This tag has to be present in all target headlines, inheritance will
  2137. not be considered.
  2138. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2139. todo keyword.
  2140. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2141. headlines that are refiling targets.
  2142. - a cons cell (:level . N). Any headline of level N is considered a target.
  2143. Note that, when `org-odd-levels-only' is set, level corresponds to
  2144. order in hierarchy, not to the number of stars.
  2145. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2146. Note that, when `org-odd-levels-only' is set, level corresponds to
  2147. order in hierarchy, not to the number of stars.
  2148. Each element of this list generates a set of possible targets.
  2149. The union of these sets is presented (with completion) to
  2150. the user by `org-refile'.
  2151. You can set the variable `org-refile-target-verify-function' to a function
  2152. to verify each headline found by the simple criteria above.
  2153. When this variable is nil, all top-level headlines in the current buffer
  2154. are used, equivalent to the value `((nil . (:level . 1))'."
  2155. :group 'org-refile
  2156. :type '(repeat
  2157. (cons
  2158. (choice :value org-agenda-files
  2159. (const :tag "All agenda files" org-agenda-files)
  2160. (const :tag "Current buffer" nil)
  2161. (function) (variable) (file))
  2162. (choice :tag "Identify target headline by"
  2163. (cons :tag "Specific tag" (const :value :tag) (string))
  2164. (cons :tag "TODO keyword" (const :value :todo) (string))
  2165. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2166. (cons :tag "Level number" (const :value :level) (integer))
  2167. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2168. (defcustom org-refile-target-verify-function nil
  2169. "Function to verify if the headline at point should be a refile target.
  2170. The function will be called without arguments, with point at the
  2171. beginning of the headline. It should return t and leave point
  2172. where it is if the headline is a valid target for refiling.
  2173. If the target should not be selected, the function must return nil.
  2174. In addition to this, it may move point to a place from where the search
  2175. should be continued. For example, the function may decide that the entire
  2176. subtree of the current entry should be excluded and move point to the end
  2177. of the subtree."
  2178. :group 'org-refile
  2179. :type '(choice
  2180. (const nil)
  2181. (function)))
  2182. (defcustom org-refile-use-cache nil
  2183. "Non-nil means cache refile targets to speed up the process.
  2184. \\<org-mode-map>\
  2185. The cache for a particular file will be updated automatically when
  2186. the buffer has been killed, or when any of the marker used for flagging
  2187. refile targets no longer points at a live buffer.
  2188. If you have added new entries to a buffer that might themselves be targets,
  2189. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2190. if you find that easier, \
  2191. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2192. \\[org-refile]'."
  2193. :group 'org-refile
  2194. :version "24.1"
  2195. :type 'boolean)
  2196. (defcustom org-refile-use-outline-path nil
  2197. "Non-nil means provide refile targets as paths.
  2198. So a level 3 headline will be available as level1/level2/level3.
  2199. When the value is `file', also include the file name (without directory)
  2200. into the path. In this case, you can also stop the completion after
  2201. the file name, to get entries inserted as top level in the file.
  2202. When `full-file-path', include the full file path."
  2203. :group 'org-refile
  2204. :type '(choice
  2205. (const :tag "Not" nil)
  2206. (const :tag "Yes" t)
  2207. (const :tag "Start with file name" file)
  2208. (const :tag "Start with full file path" full-file-path)))
  2209. (defcustom org-outline-path-complete-in-steps t
  2210. "Non-nil means complete the outline path in hierarchical steps.
  2211. When Org uses the refile interface to select an outline path (see
  2212. `org-refile-use-outline-path'), the completion of the path can be
  2213. done in a single go, or it can be done in steps down the headline
  2214. hierarchy. Going in steps is probably the best if you do not use
  2215. a special completion package like `ido' or `icicles'. However,
  2216. when using these packages, going in one step can be very fast,
  2217. while still showing the whole path to the entry."
  2218. :group 'org-refile
  2219. :type 'boolean)
  2220. (defcustom org-refile-allow-creating-parent-nodes nil
  2221. "Non-nil means allow the creation of new nodes as refile targets.
  2222. New nodes are then created by adding \"/new node name\" to the completion
  2223. of an existing node. When the value of this variable is `confirm',
  2224. new node creation must be confirmed by the user (recommended).
  2225. When nil, the completion must match an existing entry.
  2226. Note that, if the new heading is not seen by the criteria
  2227. listed in `org-refile-targets', multiple instances of the same
  2228. heading would be created by trying again to file under the new
  2229. heading."
  2230. :group 'org-refile
  2231. :type '(choice
  2232. (const :tag "Never" nil)
  2233. (const :tag "Always" t)
  2234. (const :tag "Prompt for confirmation" confirm)))
  2235. (defcustom org-refile-active-region-within-subtree nil
  2236. "Non-nil means also refile active region within a subtree.
  2237. By default `org-refile' doesn't allow refiling regions if they
  2238. don't contain a set of subtrees, but it might be convenient to
  2239. do so sometimes: in that case, the first line of the region is
  2240. converted to a headline before refiling."
  2241. :group 'org-refile
  2242. :version "24.1"
  2243. :type 'boolean)
  2244. (defgroup org-todo nil
  2245. "Options concerning TODO items in Org mode."
  2246. :tag "Org TODO"
  2247. :group 'org)
  2248. (defgroup org-progress nil
  2249. "Options concerning Progress logging in Org mode."
  2250. :tag "Org Progress"
  2251. :group 'org-time)
  2252. (defvar org-todo-interpretation-widgets
  2253. '((:tag "Sequence (cycling hits every state)" sequence)
  2254. (:tag "Type (cycling directly to DONE)" type))
  2255. "The available interpretation symbols for customizing `org-todo-keywords'.
  2256. Interested libraries should add to this list.")
  2257. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2258. "List of TODO entry keyword sequences and their interpretation.
  2259. \\<org-mode-map>This is a list of sequences.
  2260. Each sequence starts with a symbol, either `sequence' or `type',
  2261. indicating if the keywords should be interpreted as a sequence of
  2262. action steps, or as different types of TODO items. The first
  2263. keywords are states requiring action - these states will select a headline
  2264. for inclusion into the global TODO list Org produces. If one of the
  2265. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2266. signify that no further action is necessary. If \"|\" is not found,
  2267. the last keyword is treated as the only DONE state of the sequence.
  2268. The command `\\[org-todo]' cycles an entry through these states, and one
  2269. additional state where no keyword is present. For details about this
  2270. cycling, see the manual.
  2271. TODO keywords and interpretation can also be set on a per-file basis with
  2272. the special #+SEQ_TODO and #+TYP_TODO lines.
  2273. Each keyword can optionally specify a character for fast state selection
  2274. \(in combination with the variable `org-use-fast-todo-selection')
  2275. and specifiers for state change logging, using the same syntax that
  2276. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2277. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2278. indicates to record a time stamp each time this state is selected.
  2279. Each keyword may also specify if a timestamp or a note should be
  2280. recorded when entering or leaving the state, by adding additional
  2281. characters in the parenthesis after the keyword. This looks like this:
  2282. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2283. record only the time of the state change. With X and Y being either
  2284. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2285. Y when leaving the state if and only if the *target* state does not
  2286. define X. You may omit any of the fast-selection key or X or /Y,
  2287. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2288. For backward compatibility, this variable may also be just a list
  2289. of keywords. In this case the interpretation (sequence or type) will be
  2290. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2291. :group 'org-todo
  2292. :group 'org-keywords
  2293. :type '(choice
  2294. (repeat :tag "Old syntax, just keywords"
  2295. (string :tag "Keyword"))
  2296. (repeat :tag "New syntax"
  2297. (cons
  2298. (choice
  2299. :tag "Interpretation"
  2300. ;;Quick and dirty way to see
  2301. ;;`org-todo-interpretations'. This takes the
  2302. ;;place of item arguments
  2303. :convert-widget
  2304. (lambda (widget)
  2305. (widget-put widget
  2306. :args (mapcar
  2307. (lambda (x)
  2308. (widget-convert
  2309. (cons 'const x)))
  2310. org-todo-interpretation-widgets))
  2311. widget))
  2312. (repeat
  2313. (string :tag "Keyword"))))))
  2314. (defvar-local org-todo-keywords-1 nil
  2315. "All TODO and DONE keywords active in a buffer.")
  2316. (defvar org-todo-keywords-for-agenda nil)
  2317. (defvar org-done-keywords-for-agenda nil)
  2318. (defvar org-todo-keyword-alist-for-agenda nil)
  2319. (defvar org-tag-alist-for-agenda nil
  2320. "Alist of all tags from all agenda files.")
  2321. (defvar org-tag-groups-alist-for-agenda nil
  2322. "Alist of all groups tags from all current agenda files.")
  2323. (defvar-local org-tag-groups-alist nil)
  2324. (defvar org-agenda-contributing-files nil)
  2325. (defvar-local org-current-tag-alist nil
  2326. "Alist of all tag groups in current buffer.
  2327. This variable takes into consideration `org-tag-alist',
  2328. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2329. (defvar-local org-not-done-keywords nil)
  2330. (defvar-local org-done-keywords nil)
  2331. (defvar-local org-todo-heads nil)
  2332. (defvar-local org-todo-sets nil)
  2333. (defvar-local org-todo-log-states nil)
  2334. (defvar-local org-todo-kwd-alist nil)
  2335. (defvar-local org-todo-key-alist nil)
  2336. (defvar-local org-todo-key-trigger nil)
  2337. (defcustom org-todo-interpretation 'sequence
  2338. "Controls how TODO keywords are interpreted.
  2339. This variable is in principle obsolete and is only used for
  2340. backward compatibility, if the interpretation of todo keywords is
  2341. not given already in `org-todo-keywords'. See that variable for
  2342. more information."
  2343. :group 'org-todo
  2344. :group 'org-keywords
  2345. :type '(choice (const sequence)
  2346. (const type)))
  2347. (defcustom org-use-fast-todo-selection t
  2348. "\\<org-mode-map>\
  2349. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2350. This variable describes if and under what circumstances the cycling
  2351. mechanism for TODO keywords will be replaced by a single-key, direct
  2352. selection scheme.
  2353. When nil, fast selection is never used.
  2354. When the symbol `prefix', it will be used when `org-todo' is called
  2355. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2356. in an Org buffer, and
  2357. `\\[universal-argument] t' in an agenda buffer.
  2358. When t, fast selection is used by default. In this case, the prefix
  2359. argument forces cycling instead.
  2360. In all cases, the special interface is only used if access keys have
  2361. actually been assigned by the user, i.e. if keywords in the configuration
  2362. are followed by a letter in parenthesis, like TODO(t)."
  2363. :group 'org-todo
  2364. :type '(choice
  2365. (const :tag "Never" nil)
  2366. (const :tag "By default" t)
  2367. (const :tag "Only with C-u C-c C-t" prefix)))
  2368. (defcustom org-provide-todo-statistics t
  2369. "Non-nil means update todo statistics after insert and toggle.
  2370. ALL-HEADLINES means update todo statistics by including headlines
  2371. with no TODO keyword as well, counting them as not done.
  2372. A list of TODO keywords means the same, but skip keywords that are
  2373. not in this list.
  2374. When set to a list of two lists, the first list contains keywords
  2375. to consider as TODO keywords, the second list contains keywords
  2376. to consider as DONE keywords.
  2377. When this is set, todo statistics is updated in the parent of the
  2378. current entry each time a todo state is changed."
  2379. :group 'org-todo
  2380. :type '(choice
  2381. (const :tag "Yes, only for TODO entries" t)
  2382. (const :tag "Yes, including all entries" all-headlines)
  2383. (repeat :tag "Yes, for TODOs in this list"
  2384. (string :tag "TODO keyword"))
  2385. (list :tag "Yes, for TODOs and DONEs in these lists"
  2386. (repeat (string :tag "TODO keyword"))
  2387. (repeat (string :tag "DONE keyword")))
  2388. (other :tag "No TODO statistics" nil)))
  2389. (defcustom org-hierarchical-todo-statistics t
  2390. "Non-nil means TODO statistics covers just direct children.
  2391. When nil, all entries in the subtree are considered.
  2392. This has only an effect if `org-provide-todo-statistics' is set.
  2393. To set this to nil for only a single subtree, use a COOKIE_DATA
  2394. property and include the word \"recursive\" into the value."
  2395. :group 'org-todo
  2396. :type 'boolean)
  2397. (defcustom org-after-todo-state-change-hook nil
  2398. "Hook which is run after the state of a TODO item was changed.
  2399. The new state (a string with a TODO keyword, or nil) is available in the
  2400. Lisp variable `org-state'."
  2401. :group 'org-todo
  2402. :type 'hook)
  2403. (defvar org-blocker-hook nil
  2404. "Hook for functions that are allowed to block a state change.
  2405. Functions in this hook should not modify the buffer.
  2406. Each function gets as its single argument a property list,
  2407. see `org-trigger-hook' for more information about this list.
  2408. If any of the functions in this hook returns nil, the state change
  2409. is blocked.")
  2410. (defvar org-trigger-hook nil
  2411. "Hook for functions that are triggered by a state change.
  2412. Each function gets as its single argument a property list with at
  2413. least the following elements:
  2414. (:type type-of-change :position pos-at-entry-start
  2415. :from old-state :to new-state)
  2416. Depending on the type, more properties may be present.
  2417. This mechanism is currently implemented for:
  2418. TODO state changes
  2419. ------------------
  2420. :type todo-state-change
  2421. :from previous state (keyword as a string), or nil, or a symbol
  2422. `todo' or `done', to indicate the general type of state.
  2423. :to new state, like in :from")
  2424. (defcustom org-enforce-todo-dependencies nil
  2425. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2426. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2427. be blocked if any prior sibling is not yet done.
  2428. Finally, if the parent is blocked because of ordered siblings of its own,
  2429. the child will also be blocked."
  2430. :set (lambda (var val)
  2431. (set var val)
  2432. (if val
  2433. (add-hook 'org-blocker-hook
  2434. 'org-block-todo-from-children-or-siblings-or-parent)
  2435. (remove-hook 'org-blocker-hook
  2436. 'org-block-todo-from-children-or-siblings-or-parent)))
  2437. :group 'org-todo
  2438. :type 'boolean)
  2439. (defcustom org-enforce-todo-checkbox-dependencies nil
  2440. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2441. When this is nil, checkboxes have no influence on switching TODO states.
  2442. When non-nil, you first need to check off all check boxes before the TODO
  2443. entry can be switched to DONE.
  2444. This variable needs to be set before org.el is loaded, and you need to
  2445. restart Emacs after a change to make the change effective. The only way
  2446. to change is while Emacs is running is through the customize interface."
  2447. :set (lambda (var val)
  2448. (set var val)
  2449. (if val
  2450. (add-hook 'org-blocker-hook
  2451. 'org-block-todo-from-checkboxes)
  2452. (remove-hook 'org-blocker-hook
  2453. 'org-block-todo-from-checkboxes)))
  2454. :group 'org-todo
  2455. :type 'boolean)
  2456. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2457. "Non-nil means inserting a TODO heading is treated as state change.
  2458. So when the command `\\[org-insert-todo-heading]' is used, state change
  2459. logging will apply if appropriate. When nil, the new TODO item will
  2460. be inserted directly, and no logging will take place."
  2461. :group 'org-todo
  2462. :type 'boolean)
  2463. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2464. "Non-nil means switching TODO states with S-cursor counts as state change.
  2465. This is the default behavior. However, setting this to nil allows a
  2466. convenient way to select a TODO state and bypass any logging associated
  2467. with that."
  2468. :group 'org-todo
  2469. :type 'boolean)
  2470. (defcustom org-todo-state-tags-triggers nil
  2471. "Tag changes that should be triggered by TODO state changes.
  2472. This is a list. Each entry is
  2473. (state-change (tag . flag) .......)
  2474. State-change can be a string with a state, and empty string to indicate the
  2475. state that has no TODO keyword, or it can be one of the symbols `todo'
  2476. or `done', meaning any not-done or done state, respectively."
  2477. :group 'org-todo
  2478. :group 'org-tags
  2479. :type '(repeat
  2480. (cons (choice :tag "When changing to"
  2481. (const :tag "Not-done state" todo)
  2482. (const :tag "Done state" done)
  2483. (string :tag "State"))
  2484. (repeat
  2485. (cons :tag "Tag action"
  2486. (string :tag "Tag")
  2487. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2488. (defcustom org-log-done nil
  2489. "Information to record when a task moves to the DONE state.
  2490. Possible values are:
  2491. nil Don't add anything, just change the keyword
  2492. time Add a time stamp to the task
  2493. note Prompt for a note and add it with template `org-log-note-headings'
  2494. This option can also be set with on a per-file-basis with
  2495. #+STARTUP: nologdone
  2496. #+STARTUP: logdone
  2497. #+STARTUP: lognotedone
  2498. You can have local logging settings for a subtree by setting the LOGGING
  2499. property to one or more of these keywords."
  2500. :group 'org-todo
  2501. :group 'org-progress
  2502. :type '(choice
  2503. (const :tag "No logging" nil)
  2504. (const :tag "Record CLOSED timestamp" time)
  2505. (const :tag "Record CLOSED timestamp with note." note)))
  2506. ;; Normalize old uses of org-log-done.
  2507. (cond
  2508. ((eq org-log-done t) (setq org-log-done 'time))
  2509. ((and (listp org-log-done) (memq 'done org-log-done))
  2510. (setq org-log-done 'note)))
  2511. (defcustom org-log-reschedule nil
  2512. "Information to record when the scheduling date of a tasks is modified.
  2513. Possible values are:
  2514. nil Don't add anything, just change the date
  2515. time Add a time stamp to the task
  2516. note Prompt for a note and add it with template `org-log-note-headings'
  2517. This option can also be set with on a per-file-basis with
  2518. #+STARTUP: nologreschedule
  2519. #+STARTUP: logreschedule
  2520. #+STARTUP: lognotereschedule"
  2521. :group 'org-todo
  2522. :group 'org-progress
  2523. :type '(choice
  2524. (const :tag "No logging" nil)
  2525. (const :tag "Record timestamp" time)
  2526. (const :tag "Record timestamp with note." note)))
  2527. (defcustom org-log-redeadline nil
  2528. "Information to record when the deadline date of a tasks is modified.
  2529. Possible values are:
  2530. nil Don't add anything, just change the date
  2531. time Add a time stamp to the task
  2532. note Prompt for a note and add it with template `org-log-note-headings'
  2533. This option can also be set with on a per-file-basis with
  2534. #+STARTUP: nologredeadline
  2535. #+STARTUP: logredeadline
  2536. #+STARTUP: lognoteredeadline
  2537. You can have local logging settings for a subtree by setting the LOGGING
  2538. property to one or more of these keywords."
  2539. :group 'org-todo
  2540. :group 'org-progress
  2541. :type '(choice
  2542. (const :tag "No logging" nil)
  2543. (const :tag "Record timestamp" time)
  2544. (const :tag "Record timestamp with note." note)))
  2545. (defcustom org-log-note-clock-out nil
  2546. "Non-nil means record a note when clocking out of an item.
  2547. This can also be configured on a per-file basis by adding one of
  2548. the following lines anywhere in the buffer:
  2549. #+STARTUP: lognoteclock-out
  2550. #+STARTUP: nolognoteclock-out"
  2551. :group 'org-todo
  2552. :group 'org-progress
  2553. :type 'boolean)
  2554. (defcustom org-log-done-with-time t
  2555. "Non-nil means the CLOSED time stamp will contain date and time.
  2556. When nil, only the date will be recorded."
  2557. :group 'org-progress
  2558. :type 'boolean)
  2559. (defcustom org-log-note-headings
  2560. '((done . "CLOSING NOTE %t")
  2561. (state . "State %-12s from %-12S %t")
  2562. (note . "Note taken on %t")
  2563. (reschedule . "Rescheduled from %S on %t")
  2564. (delschedule . "Not scheduled, was %S on %t")
  2565. (redeadline . "New deadline from %S on %t")
  2566. (deldeadline . "Removed deadline, was %S on %t")
  2567. (refile . "Refiled on %t")
  2568. (clock-out . ""))
  2569. "Headings for notes added to entries.
  2570. The value is an alist, with the car being a symbol indicating the
  2571. note context, and the cdr is the heading to be used. The heading
  2572. may also be the empty string. The following placeholders can be
  2573. used:
  2574. %t a time stamp.
  2575. %T an active time stamp instead the default inactive one
  2576. %d a short-format time stamp.
  2577. %D an active short-format time stamp.
  2578. %s the new TODO state or time stamp (inactive), in double quotes.
  2579. %S the old TODO state or time stamp (inactive), in double quotes.
  2580. %u the user name.
  2581. %U full user name.
  2582. In fact, it is not a good idea to change the `state' entry,
  2583. because Agenda Log mode depends on the format of these entries."
  2584. :group 'org-todo
  2585. :group 'org-progress
  2586. :type '(list :greedy t
  2587. (cons (const :tag "Heading when closing an item" done) string)
  2588. (cons (const :tag
  2589. "Heading when changing todo state (todo sequence only)"
  2590. state) string)
  2591. (cons (const :tag "Heading when just taking a note" note) string)
  2592. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2593. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2594. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2595. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2596. (cons (const :tag "Heading when refiling" refile) string)
  2597. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2598. (unless (assq 'note org-log-note-headings)
  2599. (push '(note . "%t") org-log-note-headings))
  2600. (defcustom org-log-into-drawer nil
  2601. "Non-nil means insert state change notes and time stamps into a drawer.
  2602. When nil, state changes notes will be inserted after the headline and
  2603. any scheduling and clock lines, but not inside a drawer.
  2604. The value of this variable should be the name of the drawer to use.
  2605. LOGBOOK is proposed as the default drawer for this purpose, you can
  2606. also set this to a string to define the drawer of your choice.
  2607. A value of t is also allowed, representing \"LOGBOOK\".
  2608. A value of t or nil can also be set with on a per-file-basis with
  2609. #+STARTUP: logdrawer
  2610. #+STARTUP: nologdrawer
  2611. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2612. will be ignored.
  2613. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2614. a subtree.
  2615. Do not check directly this variable in a Lisp program. Call
  2616. function `org-log-into-drawer' instead."
  2617. :group 'org-todo
  2618. :group 'org-progress
  2619. :type '(choice
  2620. (const :tag "Not into a drawer" nil)
  2621. (const :tag "LOGBOOK" t)
  2622. (string :tag "Other")))
  2623. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2624. (defun org-log-into-drawer ()
  2625. "Name of the log drawer, as a string, or nil.
  2626. This is the value of `org-log-into-drawer'. However, if the
  2627. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2628. be used instead of the default value."
  2629. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2630. (cond ((equal p "nil") nil)
  2631. ((equal p "t") "LOGBOOK")
  2632. ((stringp p) p)
  2633. (p "LOGBOOK")
  2634. ((stringp org-log-into-drawer) org-log-into-drawer)
  2635. (org-log-into-drawer "LOGBOOK"))))
  2636. (defcustom org-log-state-notes-insert-after-drawers nil
  2637. "Non-nil means insert state change notes after any drawers in entry.
  2638. Only the drawers that *immediately* follow the headline and the
  2639. deadline/scheduled line are skipped.
  2640. When nil, insert notes right after the heading and perhaps the line
  2641. with deadline/scheduling if present.
  2642. This variable will have no effect if `org-log-into-drawer' is
  2643. set."
  2644. :group 'org-todo
  2645. :group 'org-progress
  2646. :type 'boolean)
  2647. (defcustom org-log-states-order-reversed t
  2648. "Non-nil means the latest state note will be directly after heading.
  2649. When nil, the state change notes will be ordered according to time.
  2650. This option can also be set with on a per-file-basis with
  2651. #+STARTUP: logstatesreversed
  2652. #+STARTUP: nologstatesreversed"
  2653. :group 'org-todo
  2654. :group 'org-progress
  2655. :type 'boolean)
  2656. (defcustom org-todo-repeat-to-state nil
  2657. "The TODO state to which a repeater should return the repeating task.
  2658. By default this is the first task in a TODO sequence, or the previous state
  2659. in a TODO_TYP set. But you can specify another task here.
  2660. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2661. :group 'org-todo
  2662. :version "24.1"
  2663. :type '(choice (const :tag "Head of sequence" nil)
  2664. (string :tag "Specific state")))
  2665. (defcustom org-log-repeat 'time
  2666. "Non-nil means record moving through the DONE state when triggering repeat.
  2667. An auto-repeating task is immediately switched back to TODO when
  2668. marked DONE. If you are not logging state changes (by adding \"@\"
  2669. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2670. record a closing note, there will be no record of the task moving
  2671. through DONE. This variable forces taking a note anyway.
  2672. nil Don't force a record
  2673. time Record a time stamp
  2674. note Prompt for a note and add it with template `org-log-note-headings'
  2675. This option can also be set with on a per-file-basis with
  2676. #+STARTUP: nologrepeat
  2677. #+STARTUP: logrepeat
  2678. #+STARTUP: lognoterepeat
  2679. You can have local logging settings for a subtree by setting the LOGGING
  2680. property to one or more of these keywords."
  2681. :group 'org-todo
  2682. :group 'org-progress
  2683. :type '(choice
  2684. (const :tag "Don't force a record" nil)
  2685. (const :tag "Force recording the DONE state" time)
  2686. (const :tag "Force recording a note with the DONE state" note)))
  2687. (defgroup org-priorities nil
  2688. "Priorities in Org mode."
  2689. :tag "Org Priorities"
  2690. :group 'org-todo)
  2691. (defcustom org-enable-priority-commands t
  2692. "Non-nil means priority commands are active.
  2693. When nil, these commands will be disabled, so that you never accidentally
  2694. set a priority."
  2695. :group 'org-priorities
  2696. :type 'boolean)
  2697. (defcustom org-highest-priority ?A
  2698. "The highest priority of TODO items. A character like ?A, ?B etc.
  2699. Must have a smaller ASCII number than `org-lowest-priority'."
  2700. :group 'org-priorities
  2701. :type 'character)
  2702. (defcustom org-lowest-priority ?C
  2703. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2704. Must have a larger ASCII number than `org-highest-priority'."
  2705. :group 'org-priorities
  2706. :type 'character)
  2707. (defcustom org-default-priority ?B
  2708. "The default priority of TODO items.
  2709. This is the priority an item gets if no explicit priority is given.
  2710. When starting to cycle on an empty priority the first step in the cycle
  2711. depends on `org-priority-start-cycle-with-default'. The resulting first
  2712. step priority must not exceed the range from `org-highest-priority' to
  2713. `org-lowest-priority' which means that `org-default-priority' has to be
  2714. in this range exclusive or inclusive the range boundaries. Else the
  2715. first step refuses to set the default and the second will fall back
  2716. to (depending on the command used) the highest or lowest priority."
  2717. :group 'org-priorities
  2718. :type 'character)
  2719. (defcustom org-priority-start-cycle-with-default t
  2720. "Non-nil means start with default priority when starting to cycle.
  2721. When this is nil, the first step in the cycle will be (depending on the
  2722. command used) one higher or lower than the default priority.
  2723. See also `org-default-priority'."
  2724. :group 'org-priorities
  2725. :type 'boolean)
  2726. (defcustom org-get-priority-function nil
  2727. "Function to extract the priority from a string.
  2728. The string is normally the headline. If this is nil Org computes the
  2729. priority from the priority cookie like [#A] in the headline. It returns
  2730. an integer, increasing by 1000 for each priority level.
  2731. The user can set a different function here, which should take a string
  2732. as an argument and return the numeric priority."
  2733. :group 'org-priorities
  2734. :version "24.1"
  2735. :type '(choice
  2736. (const nil)
  2737. (function)))
  2738. (defgroup org-time nil
  2739. "Options concerning time stamps and deadlines in Org mode."
  2740. :tag "Org Time"
  2741. :group 'org)
  2742. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2743. "Number of minutes to round time stamps to.
  2744. \\<org-mode-map>\
  2745. These are two values, the first applies when first creating a time stamp.
  2746. The second applies when changing it with the commands `S-up' and `S-down'.
  2747. When changing the time stamp, this means that it will change in steps
  2748. of N minutes, as given by the second value.
  2749. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2750. numbers should be factors of 60, so for example 5, 10, 15.
  2751. When this is larger than 1, you can still force an exact time stamp by using
  2752. a double prefix argument to a time stamp command like \
  2753. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2754. and by using a prefix arg to `S-up/down' to specify the exact number
  2755. of minutes to shift."
  2756. :group 'org-time
  2757. :get (lambda (var) ; Make sure both elements are there
  2758. (if (integerp (default-value var))
  2759. (list (default-value var) 5)
  2760. (default-value var)))
  2761. :type '(list
  2762. (integer :tag "when inserting times")
  2763. (integer :tag "when modifying times")))
  2764. ;; Normalize old customizations of this variable.
  2765. (when (integerp org-time-stamp-rounding-minutes)
  2766. (setq org-time-stamp-rounding-minutes
  2767. (list org-time-stamp-rounding-minutes
  2768. org-time-stamp-rounding-minutes)))
  2769. (defcustom org-display-custom-times nil
  2770. "Non-nil means overlay custom formats over all time stamps.
  2771. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2772. To turn this on on a per-file basis, insert anywhere in the file:
  2773. #+STARTUP: customtime"
  2774. :group 'org-time
  2775. :set 'set-default
  2776. :type 'sexp)
  2777. (make-variable-buffer-local 'org-display-custom-times)
  2778. (defcustom org-time-stamp-custom-formats
  2779. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2780. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2781. These are overlaid over the default ISO format if the variable
  2782. `org-display-custom-times' is set. Time like %H:%M should be at the
  2783. end of the second format. The custom formats are also honored by export
  2784. commands, if custom time display is turned on at the time of export."
  2785. :group 'org-time
  2786. :type 'sexp)
  2787. (defun org-time-stamp-format (&optional long inactive)
  2788. "Get the right format for a time string."
  2789. (let ((f (if long (cdr org-time-stamp-formats)
  2790. (car org-time-stamp-formats))))
  2791. (if inactive
  2792. (concat "[" (substring f 1 -1) "]")
  2793. f)))
  2794. (defcustom org-time-clocksum-format
  2795. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2796. "The format string used when creating CLOCKSUM lines.
  2797. This is also used when Org mode generates a time duration.
  2798. The value can be a single format string containing two
  2799. %-sequences, which will be filled with the number of hours and
  2800. minutes in that order.
  2801. Alternatively, the value can be a plist associating any of the
  2802. keys :years, :months, :weeks, :days, :hours or :minutes with
  2803. format strings. The time duration is formatted using only the
  2804. time components that are needed and concatenating the results.
  2805. If a time unit in absent, it falls back to the next smallest
  2806. unit.
  2807. The keys :require-years, :require-months, :require-days,
  2808. :require-weeks, :require-hours, :require-minutes are also
  2809. meaningful. A non-nil value for these keys indicates that the
  2810. corresponding time component should always be included, even if
  2811. its value is 0.
  2812. For example,
  2813. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2814. :require-minutes t)
  2815. means durations longer than a day will be expressed in days,
  2816. hours and minutes, and durations less than a day will always be
  2817. expressed in hours and minutes (even for durations less than an
  2818. hour).
  2819. The value
  2820. (:days \"%dd\" :minutes \"%dm\")
  2821. means durations longer than a day will be expressed in days and
  2822. minutes, and durations less than a day will be expressed entirely
  2823. in minutes (even for durations longer than an hour)."
  2824. :group 'org-time
  2825. :group 'org-clock
  2826. :version "24.4"
  2827. :package-version '(Org . "8.0")
  2828. :type '(choice (string :tag "Format string")
  2829. (set :tag "Plist"
  2830. (group :inline t (const :tag "Years" :years)
  2831. (string :tag "Format string"))
  2832. (group :inline t
  2833. (const :tag "Always show years" :require-years)
  2834. (const t))
  2835. (group :inline t (const :tag "Months" :months)
  2836. (string :tag "Format string"))
  2837. (group :inline t
  2838. (const :tag "Always show months" :require-months)
  2839. (const t))
  2840. (group :inline t (const :tag "Weeks" :weeks)
  2841. (string :tag "Format string"))
  2842. (group :inline t
  2843. (const :tag "Always show weeks" :require-weeks)
  2844. (const t))
  2845. (group :inline t (const :tag "Days" :days)
  2846. (string :tag "Format string"))
  2847. (group :inline t
  2848. (const :tag "Always show days" :require-days)
  2849. (const t))
  2850. (group :inline t (const :tag "Hours" :hours)
  2851. (string :tag "Format string"))
  2852. (group :inline t
  2853. (const :tag "Always show hours" :require-hours)
  2854. (const t))
  2855. (group :inline t (const :tag "Minutes" :minutes)
  2856. (string :tag "Format string"))
  2857. (group :inline t
  2858. (const :tag "Always show minutes" :require-minutes)
  2859. (const t)))))
  2860. (defcustom org-time-clocksum-use-fractional nil
  2861. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2862. See `org-time-clocksum-format' for more on time clock formats."
  2863. :group 'org-time
  2864. :group 'org-clock
  2865. :version "24.3"
  2866. :type 'boolean)
  2867. (defcustom org-time-clocksum-use-effort-durations nil
  2868. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2869. E.g. by default, one day is considered to be a 8 hours effort,
  2870. so a task that has been clocked for 16 hours will be displayed
  2871. as during 2 days in the clock display or in the clocktable.
  2872. See `org-effort-durations' on how to set effort durations
  2873. and `org-time-clocksum-format' for more on time clock formats."
  2874. :group 'org-time
  2875. :group 'org-clock
  2876. :version "24.4"
  2877. :package-version '(Org . "8.0")
  2878. :type 'boolean)
  2879. (defcustom org-time-clocksum-fractional-format "%.2f"
  2880. "The format string used when creating CLOCKSUM lines,
  2881. or when Org mode generates a time duration, if
  2882. `org-time-clocksum-use-fractional' is enabled.
  2883. The value can be a single format string containing one
  2884. %-sequence, which will be filled with the number of hours as
  2885. a float.
  2886. Alternatively, the value can be a plist associating any of the
  2887. keys :years, :months, :weeks, :days, :hours or :minutes with
  2888. a format string. The time duration is formatted using the
  2889. largest time unit which gives a non-zero integer part. If all
  2890. specified formats have zero integer part, the smallest time unit
  2891. is used."
  2892. :group 'org-time
  2893. :type '(choice (string :tag "Format string")
  2894. (set (group :inline t (const :tag "Years" :years)
  2895. (string :tag "Format string"))
  2896. (group :inline t (const :tag "Months" :months)
  2897. (string :tag "Format string"))
  2898. (group :inline t (const :tag "Weeks" :weeks)
  2899. (string :tag "Format string"))
  2900. (group :inline t (const :tag "Days" :days)
  2901. (string :tag "Format string"))
  2902. (group :inline t (const :tag "Hours" :hours)
  2903. (string :tag "Format string"))
  2904. (group :inline t (const :tag "Minutes" :minutes)
  2905. (string :tag "Format string")))))
  2906. (defcustom org-deadline-warning-days 14
  2907. "Number of days before expiration during which a deadline becomes active.
  2908. This variable governs the display in sparse trees and in the agenda.
  2909. When 0 or negative, it means use this number (the absolute value of it)
  2910. even if a deadline has a different individual lead time specified.
  2911. Custom commands can set this variable in the options section."
  2912. :group 'org-time
  2913. :group 'org-agenda-daily/weekly
  2914. :type 'integer)
  2915. (defcustom org-scheduled-delay-days 0
  2916. "Number of days before a scheduled item becomes active.
  2917. This variable governs the display in sparse trees and in the agenda.
  2918. The default value (i.e. 0) means: don't delay scheduled item.
  2919. When negative, it means use this number (the absolute value of it)
  2920. even if a scheduled item has a different individual delay time
  2921. specified.
  2922. Custom commands can set this variable in the options section."
  2923. :group 'org-time
  2924. :group 'org-agenda-daily/weekly
  2925. :version "24.4"
  2926. :package-version '(Org . "8.0")
  2927. :type 'integer)
  2928. (defcustom org-read-date-prefer-future t
  2929. "Non-nil means assume future for incomplete date input from user.
  2930. This affects the following situations:
  2931. 1. The user gives a month but not a year.
  2932. For example, if it is April and you enter \"feb 2\", this will be read
  2933. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2934. 2. The user gives a day, but no month.
  2935. For example, if today is the 15th, and you enter \"3\", Org will read
  2936. this as the third of *next* month. However, if you enter \"17\",
  2937. it will be considered as *this* month.
  2938. If you set this variable to the symbol `time', then also the following
  2939. will work:
  2940. 3. If the user gives a time.
  2941. If the time is before now, it will be interpreted as tomorrow.
  2942. Currently none of this works for ISO week specifications.
  2943. When this option is nil, the current day, month and year will always be
  2944. used as defaults.
  2945. See also `org-agenda-jump-prefer-future'."
  2946. :group 'org-time
  2947. :type '(choice
  2948. (const :tag "Never" nil)
  2949. (const :tag "Check month and day" t)
  2950. (const :tag "Check month, day, and time" time)))
  2951. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2952. "Should the agenda jump command prefer the future for incomplete dates?
  2953. The default is to do the same as configured in `org-read-date-prefer-future'.
  2954. But you can also set a deviating value here.
  2955. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2956. :group 'org-agenda
  2957. :group 'org-time
  2958. :version "24.1"
  2959. :type '(choice
  2960. (const :tag "Use org-read-date-prefer-future"
  2961. org-read-date-prefer-future)
  2962. (const :tag "Never" nil)
  2963. (const :tag "Always" t)))
  2964. (defcustom org-read-date-force-compatible-dates t
  2965. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2966. Depending on the system Emacs is running on, certain dates cannot
  2967. be represented with the type used internally to represent time.
  2968. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2969. correctly. Some systems allow for earlier dates, some for later,
  2970. some for both. One way to find out it to insert any date into an
  2971. Org buffer, putting the cursor on the year and hitting S-up and
  2972. S-down to test the range.
  2973. When this variable is set to t, the date/time prompt will not let
  2974. you specify dates outside the 1970-2037 range, so it is certain that
  2975. these dates will work in whatever version of Emacs you are
  2976. running, and also that you can move a file from one Emacs implementation
  2977. to another. WHenever Org is forcing the year for you, it will display
  2978. a message and beep.
  2979. When this variable is nil, Org will check if the date is
  2980. representable in the specific Emacs implementation you are using.
  2981. If not, it will force a year, usually the current year, and beep
  2982. to remind you. Currently this setting is not recommended because
  2983. the likelihood that you will open your Org files in an Emacs that
  2984. has limited date range is not negligible.
  2985. A workaround for this problem is to use diary sexp dates for time
  2986. stamps outside of this range."
  2987. :group 'org-time
  2988. :version "24.1"
  2989. :type 'boolean)
  2990. (defcustom org-read-date-display-live t
  2991. "Non-nil means display current interpretation of date prompt live.
  2992. This display will be in an overlay, in the minibuffer."
  2993. :group 'org-time
  2994. :type 'boolean)
  2995. (defcustom org-read-date-popup-calendar t
  2996. "Non-nil means pop up a calendar when prompting for a date.
  2997. In the calendar, the date can be selected with mouse-1. However, the
  2998. minibuffer will also be active, and you can simply enter the date as well.
  2999. When nil, only the minibuffer will be available."
  3000. :group 'org-time
  3001. :type 'boolean)
  3002. (defvaralias 'org-popup-calendar-for-date-prompt
  3003. 'org-read-date-popup-calendar)
  3004. (defcustom org-extend-today-until 0
  3005. "The hour when your day really ends. Must be an integer.
  3006. This has influence for the following applications:
  3007. - When switching the agenda to \"today\". It it is still earlier than
  3008. the time given here, the day recognized as TODAY is actually yesterday.
  3009. - When a date is read from the user and it is still before the time given
  3010. here, the current date and time will be assumed to be yesterday, 23:59.
  3011. Also, timestamps inserted in capture templates follow this rule.
  3012. IMPORTANT: This is a feature whose implementation is and likely will
  3013. remain incomplete. Really, it is only here because past midnight seems to
  3014. be the favorite working time of John Wiegley :-)"
  3015. :group 'org-time
  3016. :type 'integer)
  3017. (defcustom org-use-effective-time nil
  3018. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3019. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3020. \"effective time\" of any timestamps between midnight and 8am will be
  3021. 23:59 of the previous day."
  3022. :group 'org-time
  3023. :version "24.1"
  3024. :type 'boolean)
  3025. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3026. "When non-nil, use the last clock out time for `org-todo'.
  3027. Note that this option has precedence over the combined use of
  3028. `org-use-effective-time' and `org-extend-today-until'."
  3029. :group 'org-time
  3030. :version "24.4"
  3031. :package-version '(Org . "8.0")
  3032. :type 'boolean)
  3033. (defcustom org-edit-timestamp-down-means-later nil
  3034. "Non-nil means S-down will increase the time in a time stamp.
  3035. When nil, S-up will increase."
  3036. :group 'org-time
  3037. :type 'boolean)
  3038. (defcustom org-calendar-follow-timestamp-change t
  3039. "Non-nil means make the calendar window follow timestamp changes.
  3040. When a timestamp is modified and the calendar window is visible, it will be
  3041. moved to the new date."
  3042. :group 'org-time
  3043. :type 'boolean)
  3044. (defgroup org-tags nil
  3045. "Options concerning tags in Org mode."
  3046. :tag "Org Tags"
  3047. :group 'org)
  3048. (defcustom org-tag-alist nil
  3049. "Default tags available in Org files.
  3050. The value of this variable is an alist. Associations either:
  3051. (TAG)
  3052. (TAG . SELECT)
  3053. (SPECIAL)
  3054. where TAG is a tag as a string, SELECT is character, used to
  3055. select that tag through the fast tag selection interface, and
  3056. SPECIAL is one of the following keywords: `:startgroup',
  3057. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3058. `:newline'. These keywords are used to define a hierarchy of
  3059. tags. See manual for details.
  3060. When this variable is nil, Org mode bases tag input on what is
  3061. already in the buffer. The value can be overridden locally by
  3062. using a TAGS keyword, e.g.,
  3063. #+TAGS: tag1 tag2
  3064. See also `org-tag-persistent-alist' to sidestep this behavior."
  3065. :group 'org-tags
  3066. :type '(repeat
  3067. (choice
  3068. (cons (string :tag "Tag name")
  3069. (character :tag "Access char"))
  3070. (const :tag "Start radio group" (:startgroup))
  3071. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3072. (const :tag "Group tags delimiter" (:grouptags))
  3073. (const :tag "End radio group" (:endgroup))
  3074. (const :tag "End tag group, non distinct" (:endgrouptag))
  3075. (const :tag "New line" (:newline)))))
  3076. (defcustom org-tag-persistent-alist nil
  3077. "Tags always available in Org files.
  3078. The value of this variable is an alist. Associations either:
  3079. (TAG)
  3080. (TAG . SELECT)
  3081. (SPECIAL)
  3082. where TAG is a tag as a string, SELECT is a character, used to
  3083. select that tag through the fast tag selection interface, and
  3084. SPECIAL is one of the following keywords: `:startgroup',
  3085. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3086. `:newline'. These keywords are used to define a hierarchy of
  3087. tags. See manual for details.
  3088. Unlike to `org-tag-alist', tags defined in this variable do not
  3089. depend on a local TAGS keyword. Instead, to disable these tags
  3090. on a per-file basis, insert anywhere in the file:
  3091. #+STARTUP: noptag"
  3092. :group 'org-tags
  3093. :type '(repeat
  3094. (choice
  3095. (cons (string :tag "Tag name")
  3096. (character :tag "Access char"))
  3097. (const :tag "Start radio group" (:startgroup))
  3098. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3099. (const :tag "Group tags delimiter" (:grouptags))
  3100. (const :tag "End radio group" (:endgroup))
  3101. (const :tag "End tag group, non distinct" (:endgrouptag))
  3102. (const :tag "New line" (:newline)))))
  3103. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3104. "If non-nil, always offer completion for all tags of all agenda files.
  3105. Instead of customizing this variable directly, you might want to
  3106. set it locally for capture buffers, because there no list of
  3107. tags in that file can be created dynamically (there are none).
  3108. (add-hook \\='org-capture-mode-hook
  3109. (lambda ()
  3110. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3111. :group 'org-tags
  3112. :version "24.1"
  3113. :type 'boolean)
  3114. (defvar org-file-tags nil
  3115. "List of tags that can be inherited by all entries in the file.
  3116. The tags will be inherited if the variable `org-use-tag-inheritance'
  3117. says they should be.
  3118. This variable is populated from #+FILETAGS lines.")
  3119. (defcustom org-use-fast-tag-selection 'auto
  3120. "Non-nil means use fast tag selection scheme.
  3121. This is a special interface to select and deselect tags with single keys.
  3122. When nil, fast selection is never used.
  3123. When the symbol `auto', fast selection is used if and only if selection
  3124. characters for tags have been configured, either through the variable
  3125. `org-tag-alist' or through a #+TAGS line in the buffer.
  3126. When t, fast selection is always used and selection keys are assigned
  3127. automatically if necessary."
  3128. :group 'org-tags
  3129. :type '(choice
  3130. (const :tag "Always" t)
  3131. (const :tag "Never" nil)
  3132. (const :tag "When selection characters are configured" auto)))
  3133. (defcustom org-fast-tag-selection-single-key nil
  3134. "Non-nil means fast tag selection exits after first change.
  3135. When nil, you have to press RET to exit it.
  3136. During fast tag selection, you can toggle this flag with `C-c'.
  3137. This variable can also have the value `expert'. In this case, the window
  3138. displaying the tags menu is not even shown, until you press C-c again."
  3139. :group 'org-tags
  3140. :type '(choice
  3141. (const :tag "No" nil)
  3142. (const :tag "Yes" t)
  3143. (const :tag "Expert" expert)))
  3144. (defvar org-fast-tag-selection-include-todo nil
  3145. "Non-nil means fast tags selection interface will also offer TODO states.
  3146. This is an undocumented feature, you should not rely on it.")
  3147. (defcustom org-tags-column -77
  3148. "The column to which tags should be indented in a headline.
  3149. If this number is positive, it specifies the column. If it is negative,
  3150. it means that the tags should be flushright to that column. For example,
  3151. -80 works well for a normal 80 character screen.
  3152. When 0, place tags directly after headline text, with only one space in
  3153. between."
  3154. :group 'org-tags
  3155. :type 'integer)
  3156. (defcustom org-auto-align-tags t
  3157. "Non-nil keeps tags aligned when modifying headlines.
  3158. Some operations (i.e. demoting) change the length of a headline and
  3159. therefore shift the tags around. With this option turned on, after
  3160. each such operation the tags are again aligned to `org-tags-column'."
  3161. :group 'org-tags
  3162. :type 'boolean)
  3163. (defcustom org-use-tag-inheritance t
  3164. "Non-nil means tags in levels apply also for sublevels.
  3165. When nil, only the tags directly given in a specific line apply there.
  3166. This may also be a list of tags that should be inherited, or a regexp that
  3167. matches tags that should be inherited. Additional control is possible
  3168. with the variable `org-tags-exclude-from-inheritance' which gives an
  3169. explicit list of tags to be excluded from inheritance, even if the value of
  3170. `org-use-tag-inheritance' would select it for inheritance.
  3171. If this option is t, a match early-on in a tree can lead to a large
  3172. number of matches in the subtree when constructing the agenda or creating
  3173. a sparse tree. If you only want to see the first match in a tree during
  3174. a search, check out the variable `org-tags-match-list-sublevels'."
  3175. :group 'org-tags
  3176. :type '(choice
  3177. (const :tag "Not" nil)
  3178. (const :tag "Always" t)
  3179. (repeat :tag "Specific tags" (string :tag "Tag"))
  3180. (regexp :tag "Tags matched by regexp")))
  3181. (defcustom org-tags-exclude-from-inheritance nil
  3182. "List of tags that should never be inherited.
  3183. This is a way to exclude a few tags from inheritance. For way to do
  3184. the opposite, to actively allow inheritance for selected tags,
  3185. see the variable `org-use-tag-inheritance'."
  3186. :group 'org-tags
  3187. :type '(repeat (string :tag "Tag")))
  3188. (defun org-tag-inherit-p (tag)
  3189. "Check if TAG is one that should be inherited."
  3190. (cond
  3191. ((member tag org-tags-exclude-from-inheritance) nil)
  3192. ((eq org-use-tag-inheritance t) t)
  3193. ((not org-use-tag-inheritance) nil)
  3194. ((stringp org-use-tag-inheritance)
  3195. (string-match org-use-tag-inheritance tag))
  3196. ((listp org-use-tag-inheritance)
  3197. (member tag org-use-tag-inheritance))
  3198. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3199. (defcustom org-tags-match-list-sublevels t
  3200. "Non-nil means list also sublevels of headlines matching a search.
  3201. This variable applies to tags/property searches, and also to stuck
  3202. projects because this search is based on a tags match as well.
  3203. When set to the symbol `indented', sublevels are indented with
  3204. leading dots.
  3205. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3206. the sublevels of a headline matching a tag search often also match
  3207. the same search. Listing all of them can create very long lists.
  3208. Setting this variable to nil causes subtrees of a match to be skipped.
  3209. This variable is semi-obsolete and probably should always be true. It
  3210. is better to limit inheritance to certain tags using the variables
  3211. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3212. :group 'org-tags
  3213. :type '(choice
  3214. (const :tag "No, don't list them" nil)
  3215. (const :tag "Yes, do list them" t)
  3216. (const :tag "List them, indented with leading dots" indented)))
  3217. (defcustom org-tags-sort-function nil
  3218. "When set, tags are sorted using this function as a comparator."
  3219. :group 'org-tags
  3220. :type '(choice
  3221. (const :tag "No sorting" nil)
  3222. (const :tag "Alphabetical" string<)
  3223. (const :tag "Reverse alphabetical" string>)
  3224. (function :tag "Custom function" nil)))
  3225. (defvar org-tags-history nil
  3226. "History of minibuffer reads for tags.")
  3227. (defvar org-last-tags-completion-table nil
  3228. "The last used completion table for tags.")
  3229. (defvar org-after-tags-change-hook nil
  3230. "Hook that is run after the tags in a line have changed.")
  3231. (defgroup org-properties nil
  3232. "Options concerning properties in Org mode."
  3233. :tag "Org Properties"
  3234. :group 'org)
  3235. (defcustom org-property-format "%-10s %s"
  3236. "How property key/value pairs should be formatted by `indent-line'.
  3237. When `indent-line' hits a property definition, it will format the line
  3238. according to this format, mainly to make sure that the values are
  3239. lined-up with respect to each other."
  3240. :group 'org-properties
  3241. :type 'string)
  3242. (defcustom org-properties-postprocess-alist nil
  3243. "Alist of properties and functions to adjust inserted values.
  3244. Elements of this alist must be of the form
  3245. ([string] [function])
  3246. where [string] must be a property name and [function] must be a
  3247. lambda expression: this lambda expression must take one argument,
  3248. the value to adjust, and return the new value as a string.
  3249. For example, this element will allow the property \"Remaining\"
  3250. to be updated wrt the relation between the \"Effort\" property
  3251. and the clock summary:
  3252. ((\"Remaining\" (lambda(value)
  3253. (let ((clocksum (org-clock-sum-current-item))
  3254. (effort (org-duration-string-to-minutes
  3255. (org-entry-get (point) \"Effort\"))))
  3256. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3257. :group 'org-properties
  3258. :version "24.1"
  3259. :type '(alist :key-type (string :tag "Property")
  3260. :value-type (function :tag "Function")))
  3261. (defcustom org-use-property-inheritance nil
  3262. "Non-nil means properties apply also for sublevels.
  3263. This setting is chiefly used during property searches. Turning it on can
  3264. cause significant overhead when doing a search, which is why it is not
  3265. on by default.
  3266. When nil, only the properties directly given in the current entry count.
  3267. When t, every property is inherited. The value may also be a list of
  3268. properties that should have inheritance, or a regular expression matching
  3269. properties that should be inherited.
  3270. However, note that some special properties use inheritance under special
  3271. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3272. and the properties ending in \"_ALL\" when they are used as descriptor
  3273. for valid values of a property.
  3274. Note for programmers:
  3275. When querying an entry with `org-entry-get', you can control if inheritance
  3276. should be used. By default, `org-entry-get' looks only at the local
  3277. properties. You can request inheritance by setting the inherit argument
  3278. to t (to force inheritance) or to `selective' (to respect the setting
  3279. in this variable)."
  3280. :group 'org-properties
  3281. :type '(choice
  3282. (const :tag "Not" nil)
  3283. (const :tag "Always" t)
  3284. (repeat :tag "Specific properties" (string :tag "Property"))
  3285. (regexp :tag "Properties matched by regexp")))
  3286. (defun org-property-inherit-p (property)
  3287. "Return a non-nil value if PROPERTY should be inherited."
  3288. (cond
  3289. ((eq org-use-property-inheritance t) t)
  3290. ((not org-use-property-inheritance) nil)
  3291. ((stringp org-use-property-inheritance)
  3292. (string-match org-use-property-inheritance property))
  3293. ((listp org-use-property-inheritance)
  3294. (member-ignore-case property org-use-property-inheritance))
  3295. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3296. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3297. "The default column format, if no other format has been defined.
  3298. This variable can be set on the per-file basis by inserting a line
  3299. #+COLUMNS: %25ITEM ....."
  3300. :group 'org-properties
  3301. :type 'string)
  3302. (defcustom org-columns-ellipses ".."
  3303. "The ellipses to be used when a field in column view is truncated.
  3304. When this is the empty string, as many characters as possible are shown,
  3305. but then there will be no visual indication that the field has been truncated.
  3306. When this is a string of length N, the last N characters of a truncated
  3307. field are replaced by this string. If the column is narrower than the
  3308. ellipses string, only part of the ellipses string will be shown."
  3309. :group 'org-properties
  3310. :type 'string)
  3311. (defconst org-global-properties-fixed
  3312. '(("VISIBILITY_ALL" . "folded children content all")
  3313. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3314. "List of property/value pairs that can be inherited by any entry.
  3315. These are fixed values, for the preset properties. The user variable
  3316. that can be used to add to this list is `org-global-properties'.
  3317. The entries in this list are cons cells where the car is a property
  3318. name and cdr is a string with the value. If the value represents
  3319. multiple items like an \"_ALL\" property, separate the items by
  3320. spaces.")
  3321. (defcustom org-global-properties nil
  3322. "List of property/value pairs that can be inherited by any entry.
  3323. This list will be combined with the constant `org-global-properties-fixed'.
  3324. The entries in this list are cons cells where the car is a property
  3325. name and cdr is a string with the value.
  3326. You can set buffer-local values for the same purpose in the variable
  3327. `org-file-properties' this by adding lines like
  3328. #+PROPERTY: NAME VALUE"
  3329. :group 'org-properties
  3330. :type '(repeat
  3331. (cons (string :tag "Property")
  3332. (string :tag "Value"))))
  3333. (defvar-local org-file-properties nil
  3334. "List of property/value pairs that can be inherited by any entry.
  3335. Valid for the current buffer.
  3336. This variable is populated from #+PROPERTY lines.")
  3337. (defgroup org-agenda nil
  3338. "Options concerning agenda views in Org mode."
  3339. :tag "Org Agenda"
  3340. :group 'org)
  3341. (defvar-local org-category nil
  3342. "Variable used by org files to set a category for agenda display.
  3343. Such files should use a file variable to set it, for example
  3344. # -*- mode: org; org-category: \"ELisp\"
  3345. or contain a special line
  3346. #+CATEGORY: ELisp
  3347. If the file does not specify a category, then file's base name
  3348. is used instead.")
  3349. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3350. (defcustom org-agenda-files nil
  3351. "The files to be used for agenda display.
  3352. If an entry is a directory, all files in that directory that are matched
  3353. by `org-agenda-file-regexp' will be part of the file list.
  3354. If the value of the variable is not a list but a single file name, then
  3355. the list of agenda files is actually stored and maintained in that file,
  3356. one agenda file per line. In this file paths can be given relative to
  3357. `org-directory'. Tilde expansion and environment variable substitution
  3358. are also made.
  3359. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3360. and removed with `\\[org-remove-file]'."
  3361. :group 'org-agenda
  3362. :type '(choice
  3363. (repeat :tag "List of files and directories" file)
  3364. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3365. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3366. "Regular expression to match files for `org-agenda-files'.
  3367. If any element in the list in that variable contains a directory instead
  3368. of a normal file, all files in that directory that are matched by this
  3369. regular expression will be included."
  3370. :group 'org-agenda
  3371. :type 'regexp)
  3372. (defcustom org-agenda-text-search-extra-files nil
  3373. "List of extra files to be searched by text search commands.
  3374. These files will be searched in addition to the agenda files by the
  3375. commands `org-search-view' (`\\[org-agenda] s') \
  3376. and `org-occur-in-agenda-files'.
  3377. Note that these files will only be searched for text search commands,
  3378. not for the other agenda views like todo lists, tag searches or the weekly
  3379. agenda. This variable is intended to list notes and possibly archive files
  3380. that should also be searched by these two commands.
  3381. In fact, if the first element in the list is the symbol `agenda-archives',
  3382. then all archive files of all agenda files will be added to the search
  3383. scope."
  3384. :group 'org-agenda
  3385. :type '(set :greedy t
  3386. (const :tag "Agenda Archives" agenda-archives)
  3387. (repeat :inline t (file))))
  3388. (defvaralias 'org-agenda-multi-occur-extra-files
  3389. 'org-agenda-text-search-extra-files)
  3390. (defcustom org-agenda-skip-unavailable-files nil
  3391. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3392. A nil value means to remove them, after a query, from the list."
  3393. :group 'org-agenda
  3394. :type 'boolean)
  3395. (defcustom org-calendar-to-agenda-key [?c]
  3396. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3397. The command `org-calendar-goto-agenda' will be bound to this key. The
  3398. default is the character `c' because then `c' can be used to switch back and
  3399. forth between agenda and calendar."
  3400. :group 'org-agenda
  3401. :type 'sexp)
  3402. (defcustom org-calendar-insert-diary-entry-key [?i]
  3403. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3404. This option is irrelevant until `org-agenda-diary-file' has been configured
  3405. to point to an Org file. When that is the case, the command
  3406. `org-agenda-diary-entry' will be bound to the key given here, by default
  3407. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3408. if you want to continue doing this, you need to change this to a different
  3409. key."
  3410. :group 'org-agenda
  3411. :type 'sexp)
  3412. (defcustom org-agenda-diary-file 'diary-file
  3413. "File to which to add new entries with the `i' key in agenda and calendar.
  3414. When this is the symbol `diary-file', the functionality in the Emacs
  3415. calendar will be used to add entries to the `diary-file'. But when this
  3416. points to a file, `org-agenda-diary-entry' will be used instead."
  3417. :group 'org-agenda
  3418. :type '(choice
  3419. (const :tag "The standard Emacs diary file" diary-file)
  3420. (file :tag "Special Org file diary entries")))
  3421. (eval-after-load "calendar"
  3422. '(progn
  3423. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3424. 'org-calendar-goto-agenda)
  3425. (add-hook 'calendar-mode-hook
  3426. (lambda ()
  3427. (unless (eq org-agenda-diary-file 'diary-file)
  3428. (define-key calendar-mode-map
  3429. org-calendar-insert-diary-entry-key
  3430. 'org-agenda-diary-entry))))))
  3431. (defgroup org-latex nil
  3432. "Options for embedding LaTeX code into Org mode."
  3433. :tag "Org LaTeX"
  3434. :group 'org)
  3435. (defcustom org-format-latex-options
  3436. '(:foreground default :background default :scale 1.0
  3437. :html-foreground "Black" :html-background "Transparent"
  3438. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3439. "Options for creating images from LaTeX fragments.
  3440. This is a property list with the following properties:
  3441. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3442. `default' means use the foreground of the default face.
  3443. `auto' means use the foreground from the text face.
  3444. :background the background color, or \"Transparent\".
  3445. `default' means use the background of the default face.
  3446. `auto' means use the background from the text face.
  3447. :scale a scaling factor for the size of the images, to get more pixels
  3448. :html-foreground, :html-background, :html-scale
  3449. the same numbers for HTML export.
  3450. :matchers a list indicating which matchers should be used to
  3451. find LaTeX fragments. Valid members of this list are:
  3452. \"begin\" find environments
  3453. \"$1\" find single characters surrounded by $.$
  3454. \"$\" find math expressions surrounded by $...$
  3455. \"$$\" find math expressions surrounded by $$....$$
  3456. \"\\(\" find math expressions surrounded by \\(...\\)
  3457. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3458. :group 'org-latex
  3459. :type 'plist)
  3460. (defcustom org-format-latex-signal-error t
  3461. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3462. When nil, just push out a message."
  3463. :group 'org-latex
  3464. :version "24.1"
  3465. :type 'boolean)
  3466. (defcustom org-latex-to-mathml-jar-file nil
  3467. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3468. Use this to specify additional executable file say a jar file.
  3469. When using MathToWeb as the converter, specify the full-path to
  3470. your mathtoweb.jar file."
  3471. :group 'org-latex
  3472. :version "24.1"
  3473. :type '(choice
  3474. (const :tag "None" nil)
  3475. (file :tag "JAR file" :must-match t)))
  3476. (defcustom org-latex-to-mathml-convert-command nil
  3477. "Command to convert LaTeX fragments to MathML.
  3478. Replace format-specifiers in the command as noted below and use
  3479. `shell-command' to convert LaTeX to MathML.
  3480. %j: Executable file in fully expanded form as specified by
  3481. `org-latex-to-mathml-jar-file'.
  3482. %I: Input LaTeX file in fully expanded form.
  3483. %i: The latex fragment to be converted.
  3484. %o: Output MathML file.
  3485. This command is used by `org-create-math-formula'.
  3486. When using MathToWeb as the converter, set this option to
  3487. \"java -jar %j -unicode -force -df %o %I\".
  3488. When using LaTeXML set this option to
  3489. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3490. :group 'org-latex
  3491. :version "24.1"
  3492. :type '(choice
  3493. (const :tag "None" nil)
  3494. (string :tag "\nShell command")))
  3495. (defcustom org-preview-latex-default-process 'dvipng
  3496. "The default process to convert LaTeX fragments to image files.
  3497. All available processes and theirs documents can be found in
  3498. `org-preview-latex-process-alist', which see."
  3499. :group 'org-latex
  3500. :version "26.1"
  3501. :package-version '(Org . "9.0")
  3502. :type 'symbol)
  3503. (defcustom org-preview-latex-process-alist
  3504. '((dvipng
  3505. :programs ("latex" "dvipng")
  3506. :description "dvi > png"
  3507. :message "you need to install the programs: latex and dvipng."
  3508. :image-input-type "dvi"
  3509. :image-output-type "png"
  3510. :image-size-adjust (1.0 . 1.0)
  3511. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3512. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3513. (dvisvgm
  3514. :programs ("latex" "dvisvgm")
  3515. :description "dvi > svg"
  3516. :message "you need to install the programs: latex and dvisvgm."
  3517. :use-xcolor t
  3518. :image-input-type "dvi"
  3519. :image-output-type "svg"
  3520. :image-size-adjust (1.7 . 1.5)
  3521. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3522. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3523. (imagemagick
  3524. :programs ("latex" "convert")
  3525. :description "pdf > png"
  3526. :message "you need to install the programs: latex and imagemagick."
  3527. :use-xcolor t
  3528. :image-input-type "pdf"
  3529. :image-output-type "png"
  3530. :image-size-adjust (1.0 . 1.0)
  3531. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3532. :image-converter
  3533. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3534. "Definitions of external processes for LaTeX previewing.
  3535. Org mode can use some external commands to generate TeX snippet's images for
  3536. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3537. `org-create-formula-image' how to call them.
  3538. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3539. PROPERTIES accepts the following attributes:
  3540. :programs list of strings, required programs.
  3541. :description string, describe the process.
  3542. :message string, message it when required programs cannot be found.
  3543. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3544. :image-output-type string, output file type of image converter (e.g., \"png\").
  3545. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3546. deal with background and foreground color of image.
  3547. Otherwise, dvipng style background and foregroud color
  3548. format are generated. You may then refer to them in
  3549. command options with \"%F\" and \"%B\".
  3550. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3551. image size showed in buffer and the cdr element is for
  3552. HTML file. This option is only useful for process
  3553. developers, users should use variable
  3554. `org-format-latex-options' instead.
  3555. :post-clean list of strings, files matched are to be cleaned up once
  3556. the image is generated. When nil, the files with \".dvi\",
  3557. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3558. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3559. be cleaned up.
  3560. :latex-header list of strings, the LaTeX header of the snippet file.
  3561. When nil, the fallback value is used instead, which is
  3562. controlled by `org-format-latex-header',
  3563. `org-latex-default-packages-alist' and
  3564. `org-latex-packages-alist', which see.
  3565. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3566. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3567. replaced with values defined below.
  3568. :image-converter list of image converter commands strings. Each of them is
  3569. given to the shell and supports any of the following
  3570. place-holders defined below.
  3571. Place-holders used by `:image-converter' and `:latex-compiler':
  3572. %f input file name
  3573. %b base name of input file
  3574. %o base directory of input file
  3575. %O absolute output file name
  3576. Place-holders only used by `:image-converter':
  3577. %F foreground of image
  3578. %B background of image
  3579. %D dpi, which is used to adjust image size by some processing commands.
  3580. %S the image size scale ratio, which is used to adjust image size by some
  3581. processing commands."
  3582. :group 'org-latex
  3583. :version "26.1"
  3584. :package-version '(Org . "9.0")
  3585. :type '(alist :tag "LaTeX to image backends"
  3586. :value-type (plist)))
  3587. (defcustom org-preview-latex-image-directory "ltximg/"
  3588. "Path to store latex preview images.
  3589. A relative path here creates many directories relative to the
  3590. processed org files paths. An absolute path puts all preview
  3591. images at the same place."
  3592. :group 'org-latex
  3593. :version "26.1"
  3594. :package-version '(Org . "9.0")
  3595. :type 'string)
  3596. (defun org-format-latex-mathml-available-p ()
  3597. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3598. (save-match-data
  3599. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3600. org-latex-to-mathml-convert-command)
  3601. (let ((executable (car (split-string
  3602. org-latex-to-mathml-convert-command))))
  3603. (when (executable-find executable)
  3604. (if (string-match
  3605. "%j" org-latex-to-mathml-convert-command)
  3606. (file-readable-p org-latex-to-mathml-jar-file)
  3607. t))))))
  3608. (defcustom org-format-latex-header "\\documentclass{article}
  3609. \\usepackage[usenames]{color}
  3610. \[PACKAGES]
  3611. \[DEFAULT-PACKAGES]
  3612. \\pagestyle{empty} % do not remove
  3613. % The settings below are copied from fullpage.sty
  3614. \\setlength{\\textwidth}{\\paperwidth}
  3615. \\addtolength{\\textwidth}{-3cm}
  3616. \\setlength{\\oddsidemargin}{1.5cm}
  3617. \\addtolength{\\oddsidemargin}{-2.54cm}
  3618. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3619. \\setlength{\\textheight}{\\paperheight}
  3620. \\addtolength{\\textheight}{-\\headheight}
  3621. \\addtolength{\\textheight}{-\\headsep}
  3622. \\addtolength{\\textheight}{-\\footskip}
  3623. \\addtolength{\\textheight}{-3cm}
  3624. \\setlength{\\topmargin}{1.5cm}
  3625. \\addtolength{\\topmargin}{-2.54cm}"
  3626. "The document header used for processing LaTeX fragments.
  3627. It is imperative that this header make sure that no page number
  3628. appears on the page. The package defined in the variables
  3629. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3630. will either replace the placeholder \"[PACKAGES]\" in this
  3631. header, or they will be appended."
  3632. :group 'org-latex
  3633. :type 'string)
  3634. (defun org-set-packages-alist (var val)
  3635. "Set the packages alist and make sure it has 3 elements per entry."
  3636. (set var (mapcar (lambda (x)
  3637. (if (and (consp x) (= (length x) 2))
  3638. (list (car x) (nth 1 x) t)
  3639. x))
  3640. val)))
  3641. (defun org-get-packages-alist (var)
  3642. "Get the packages alist and make sure it has 3 elements per entry."
  3643. (mapcar (lambda (x)
  3644. (if (and (consp x) (= (length x) 2))
  3645. (list (car x) (nth 1 x) t)
  3646. x))
  3647. (default-value var)))
  3648. (defcustom org-latex-default-packages-alist
  3649. '(("AUTO" "inputenc" t ("pdflatex"))
  3650. ("T1" "fontenc" t ("pdflatex"))
  3651. ("" "graphicx" t)
  3652. ("" "grffile" t)
  3653. ("" "longtable" nil)
  3654. ("" "wrapfig" nil)
  3655. ("" "rotating" nil)
  3656. ("normalem" "ulem" t)
  3657. ("" "amsmath" t)
  3658. ("" "textcomp" t)
  3659. ("" "amssymb" t)
  3660. ("" "capt-of" nil)
  3661. ("" "hyperref" nil))
  3662. "Alist of default packages to be inserted in the header.
  3663. Change this only if one of the packages here causes an
  3664. incompatibility with another package you are using.
  3665. The packages in this list are needed by one part or another of
  3666. Org mode to function properly:
  3667. - inputenc, fontenc: for basic font and character selection
  3668. - graphicx: for including images
  3669. - grffile: allow periods and spaces in graphics file names
  3670. - longtable: For multipage tables
  3671. - wrapfig: for figure placement
  3672. - rotating: for sideways figures and tables
  3673. - ulem: for underline and strike-through
  3674. - amsmath: for subscript and superscript and math environments
  3675. - textcomp, amssymb: for various symbols used
  3676. for interpreting the entities in `org-entities'. You can skip
  3677. some of these packages if you don't use any of their symbols.
  3678. - capt-of: for captions outside of floats
  3679. - hyperref: for cross references
  3680. Therefore you should not modify this variable unless you know
  3681. what you are doing. The one reason to change it anyway is that
  3682. you might be loading some other package that conflicts with one
  3683. of the default packages. Each element is either a cell or
  3684. a string.
  3685. A cell is of the format
  3686. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3687. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3688. when compiling LaTeX snippets into images for inclusion into
  3689. non-LaTeX output. COMPILERS is a list of compilers that should
  3690. include the package, see `org-latex-compiler'. If the document
  3691. compiler is not in the list, and the list is non-nil, the package
  3692. will not be inserted in the final document.
  3693. A string will be inserted as-is in the header of the document."
  3694. :group 'org-latex
  3695. :group 'org-export-latex
  3696. :set 'org-set-packages-alist
  3697. :get 'org-get-packages-alist
  3698. :version "26.1"
  3699. :package-version '(Org . "8.3")
  3700. :type '(repeat
  3701. (choice
  3702. (list :tag "options/package pair"
  3703. (string :tag "options")
  3704. (string :tag "package")
  3705. (boolean :tag "Snippet"))
  3706. (string :tag "A line of LaTeX"))))
  3707. (defcustom org-latex-packages-alist nil
  3708. "Alist of packages to be inserted in every LaTeX header.
  3709. These will be inserted after `org-latex-default-packages-alist'.
  3710. Each element is either a cell or a string.
  3711. A cell is of the format:
  3712. (\"options\" \"package\" SNIPPET-FLAG)
  3713. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3714. needed when turning LaTeX snippets into images for inclusion into
  3715. non-LaTeX output.
  3716. A string will be inserted as-is in the header of the document.
  3717. Make sure that you only list packages here which:
  3718. - you want in every file;
  3719. - do not conflict with the setup in `org-format-latex-header';
  3720. - do not conflict with the default packages in
  3721. `org-latex-default-packages-alist'."
  3722. :group 'org-latex
  3723. :group 'org-export-latex
  3724. :set 'org-set-packages-alist
  3725. :get 'org-get-packages-alist
  3726. :type '(repeat
  3727. (choice
  3728. (list :tag "options/package pair"
  3729. (string :tag "options")
  3730. (string :tag "package")
  3731. (boolean :tag "Snippet"))
  3732. (string :tag "A line of LaTeX"))))
  3733. (defgroup org-appearance nil
  3734. "Settings for Org mode appearance."
  3735. :tag "Org Appearance"
  3736. :group 'org)
  3737. (defcustom org-level-color-stars-only nil
  3738. "Non-nil means fontify only the stars in each headline.
  3739. When nil, the entire headline is fontified.
  3740. Changing it requires restart of `font-lock-mode' to become effective
  3741. also in regions already fontified."
  3742. :group 'org-appearance
  3743. :type 'boolean)
  3744. (defcustom org-hide-leading-stars nil
  3745. "Non-nil means hide the first N-1 stars in a headline.
  3746. This works by using the face `org-hide' for these stars. This
  3747. face is white for a light background, and black for a dark
  3748. background. You may have to customize the face `org-hide' to
  3749. make this work.
  3750. Changing it requires restart of `font-lock-mode' to become effective
  3751. also in regions already fontified.
  3752. You may also set this on a per-file basis by adding one of the following
  3753. lines to the buffer:
  3754. #+STARTUP: hidestars
  3755. #+STARTUP: showstars"
  3756. :group 'org-appearance
  3757. :type 'boolean)
  3758. (defcustom org-hidden-keywords nil
  3759. "List of symbols corresponding to keywords to be hidden the org buffer.
  3760. For example, a value \\='(title) for this list will make the document's title
  3761. appear in the buffer without the initial #+TITLE: keyword."
  3762. :group 'org-appearance
  3763. :version "24.1"
  3764. :type '(set (const :tag "#+AUTHOR" author)
  3765. (const :tag "#+DATE" date)
  3766. (const :tag "#+EMAIL" email)
  3767. (const :tag "#+TITLE" title)))
  3768. (defcustom org-custom-properties nil
  3769. "List of properties (as strings) with a special meaning.
  3770. The default use of these custom properties is to let the user
  3771. hide them with `org-toggle-custom-properties-visibility'."
  3772. :group 'org-properties
  3773. :group 'org-appearance
  3774. :version "24.3"
  3775. :type '(repeat (string :tag "Property Name")))
  3776. (defcustom org-fontify-done-headline nil
  3777. "Non-nil means change the face of a headline if it is marked DONE.
  3778. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3779. When this is non-nil, the headline after the keyword is set to the
  3780. `org-headline-done' as an additional indication."
  3781. :group 'org-appearance
  3782. :type 'boolean)
  3783. (defcustom org-fontify-emphasized-text t
  3784. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3785. Changing this variable requires a restart of Emacs to take effect."
  3786. :group 'org-appearance
  3787. :type 'boolean)
  3788. (defcustom org-fontify-whole-heading-line nil
  3789. "Non-nil means fontify the whole line for headings.
  3790. This is useful when setting a background color for the
  3791. org-level-* faces."
  3792. :group 'org-appearance
  3793. :type 'boolean)
  3794. (defcustom org-highlight-latex-and-related nil
  3795. "Non-nil means highlight LaTeX related syntax in the buffer.
  3796. When non nil, the value should be a list containing any of the
  3797. following symbols:
  3798. `latex' Highlight LaTeX snippets and environments.
  3799. `script' Highlight subscript and superscript.
  3800. `entities' Highlight entities."
  3801. :group 'org-appearance
  3802. :version "24.4"
  3803. :package-version '(Org . "8.0")
  3804. :type '(choice
  3805. (const :tag "No highlighting" nil)
  3806. (set :greedy t :tag "Highlight"
  3807. (const :tag "LaTeX snippets and environments" latex)
  3808. (const :tag "Subscript and superscript" script)
  3809. (const :tag "Entities" entities))))
  3810. (defcustom org-hide-emphasis-markers nil
  3811. "Non-nil mean font-lock should hide the emphasis marker characters."
  3812. :group 'org-appearance
  3813. :type 'boolean)
  3814. (defcustom org-hide-macro-markers nil
  3815. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3816. :group 'org-appearance
  3817. :type 'boolean)
  3818. (defcustom org-pretty-entities nil
  3819. "Non-nil means show entities as UTF8 characters.
  3820. When nil, the \\name form remains in the buffer."
  3821. :group 'org-appearance
  3822. :version "24.1"
  3823. :type 'boolean)
  3824. (defcustom org-pretty-entities-include-sub-superscripts t
  3825. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3826. :group 'org-appearance
  3827. :version "24.1"
  3828. :type 'boolean)
  3829. (defvar org-emph-re nil
  3830. "Regular expression for matching emphasis.
  3831. After a match, the match groups contain these elements:
  3832. 0 The match of the full regular expression, including the characters
  3833. before and after the proper match
  3834. 1 The character before the proper match, or empty at beginning of line
  3835. 2 The proper match, including the leading and trailing markers
  3836. 3 The leading marker like * or /, indicating the type of highlighting
  3837. 4 The text between the emphasis markers, not including the markers
  3838. 5 The character after the match, empty at the end of a line")
  3839. (defvar org-verbatim-re nil
  3840. "Regular expression for matching verbatim text.")
  3841. (defvar org-emphasis-regexp-components) ; defined just below
  3842. (defvar org-emphasis-alist) ; defined just below
  3843. (defun org-set-emph-re (var val)
  3844. "Set variable and compute the emphasis regular expression."
  3845. (set var val)
  3846. (when (and (boundp 'org-emphasis-alist)
  3847. (boundp 'org-emphasis-regexp-components)
  3848. org-emphasis-alist org-emphasis-regexp-components)
  3849. (let* ((e org-emphasis-regexp-components)
  3850. (pre (car e))
  3851. (post (nth 1 e))
  3852. (border (nth 2 e))
  3853. (body (nth 3 e))
  3854. (nl (nth 4 e))
  3855. (body1 (concat body "*?"))
  3856. (markers (mapconcat 'car org-emphasis-alist ""))
  3857. (vmarkers (mapconcat
  3858. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3859. org-emphasis-alist "")))
  3860. ;; make sure special characters appear at the right position in the class
  3861. (if (string-match "\\^" markers)
  3862. (setq markers (concat (replace-match "" t t markers) "^")))
  3863. (if (string-match "-" markers)
  3864. (setq markers (concat (replace-match "" t t markers) "-")))
  3865. (if (string-match "\\^" vmarkers)
  3866. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3867. (if (string-match "-" vmarkers)
  3868. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3869. (if (> nl 0)
  3870. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3871. (int-to-string nl) "\\}")))
  3872. ;; Make the regexp
  3873. (setq org-emph-re
  3874. (concat "\\([" pre "]\\|^\\)"
  3875. "\\("
  3876. "\\([" markers "]\\)"
  3877. "\\("
  3878. "[^" border "]\\|"
  3879. "[^" border "]"
  3880. body1
  3881. "[^" border "]"
  3882. "\\)"
  3883. "\\3\\)"
  3884. "\\([" post "]\\|$\\)"))
  3885. (setq org-verbatim-re
  3886. (concat "\\([" pre "]\\|^\\)"
  3887. "\\("
  3888. "\\([" vmarkers "]\\)"
  3889. "\\("
  3890. "[^" border "]\\|"
  3891. "[^" border "]"
  3892. body1
  3893. "[^" border "]"
  3894. "\\)"
  3895. "\\3\\)"
  3896. "\\([" post "]\\|$\\)")))))
  3897. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3898. ;; set this option proved cumbersome. See this message/thread:
  3899. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3900. (defvar org-emphasis-regexp-components
  3901. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3902. "Components used to build the regular expression for emphasis.
  3903. This is a list with five entries. Terminology: In an emphasis string
  3904. like \" *strong word* \", we call the initial space PREMATCH, the final
  3905. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3906. and \"trong wor\" is the body. The different components in this variable
  3907. specify what is allowed/forbidden in each part:
  3908. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3909. post Chars allowed as postmatch. End of line will be allowed too.
  3910. border The chars *forbidden* as border characters.
  3911. body-regexp A regexp like \".\" to match a body character. Don't use
  3912. non-shy groups here, and don't allow newline here.
  3913. newline The maximum number of newlines allowed in an emphasis exp.
  3914. You need to reload Org or to restart Emacs after customizing this.")
  3915. (defcustom org-emphasis-alist
  3916. '(("*" bold)
  3917. ("/" italic)
  3918. ("_" underline)
  3919. ("=" org-verbatim verbatim)
  3920. ("~" org-code verbatim)
  3921. ("+" (:strike-through t)))
  3922. "Alist of characters and faces to emphasize text.
  3923. Text starting and ending with a special character will be emphasized,
  3924. for example *bold*, _underlined_ and /italic/. This variable sets the
  3925. marker characters and the face to be used by font-lock for highlighting
  3926. in Org buffers.
  3927. You need to reload Org or to restart Emacs after customizing this."
  3928. :group 'org-appearance
  3929. :set 'org-set-emph-re
  3930. :version "24.4"
  3931. :package-version '(Org . "8.0")
  3932. :type '(repeat
  3933. (list
  3934. (string :tag "Marker character")
  3935. (choice
  3936. (face :tag "Font-lock-face")
  3937. (plist :tag "Face property list"))
  3938. (option (const verbatim)))))
  3939. (defvar org-protecting-blocks '("src" "example" "export")
  3940. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3941. This is needed for font-lock setup.")
  3942. ;;; Functions and variables from their packages
  3943. ;; Declared here to avoid compiler warnings
  3944. (defvar mark-active)
  3945. ;; Various packages
  3946. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3947. (declare-function calendar-forward-day "cal-move" (arg))
  3948. (declare-function calendar-goto-date "cal-move" (date))
  3949. (declare-function calendar-goto-today "cal-move" ())
  3950. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3951. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3952. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3953. (declare-function cdlatex-tab "ext:cdlatex" ())
  3954. (declare-function dired-get-filename
  3955. "dired"
  3956. (&optional localp no-error-if-not-filep))
  3957. (declare-function iswitchb-read-buffer
  3958. "iswitchb"
  3959. (prompt &optional
  3960. default require-match _predicate start matches-set))
  3961. (declare-function org-agenda-change-all-lines
  3962. "org-agenda"
  3963. (newhead hdmarker &optional fixface just-this))
  3964. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3965. "org-agenda"
  3966. (&optional end))
  3967. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3968. (declare-function org-agenda-format-item
  3969. "org-agenda"
  3970. (extra txt &optional level category tags dotime
  3971. remove-re habitp))
  3972. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3973. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3974. (declare-function org-agenda-save-markers-for-cut-and-paste
  3975. "org-agenda"
  3976. (beg end))
  3977. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3978. (declare-function org-agenda-skip "org-agenda" ())
  3979. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3980. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3981. (declare-function org-indent-mode "org-indent" (&optional arg))
  3982. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3983. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3984. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3985. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3986. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3987. (declare-function parse-time-string "parse-time" (string))
  3988. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3989. (defvar align-mode-rules-list)
  3990. (defvar calc-embedded-close-formula)
  3991. (defvar calc-embedded-open-formula)
  3992. (defvar calc-embedded-open-mode)
  3993. (defvar font-lock-unfontify-region-function)
  3994. (defvar iswitchb-temp-buflist)
  3995. (defvar org-agenda-tags-todo-honor-ignore-options)
  3996. (defvar remember-data-file)
  3997. (defvar texmathp-why)
  3998. ;;;###autoload
  3999. (defun turn-on-orgtbl ()
  4000. "Unconditionally turn on `orgtbl-mode'."
  4001. (require 'org-table)
  4002. (orgtbl-mode 1))
  4003. (defun org-at-table-p (&optional table-type)
  4004. "Non-nil if the cursor is inside an Org table.
  4005. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  4006. If `org-enable-table-editor' is nil, return nil unconditionally."
  4007. (and
  4008. org-enable-table-editor
  4009. (save-excursion
  4010. (beginning-of-line)
  4011. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  4012. (or (not (derived-mode-p 'org-mode))
  4013. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  4014. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  4015. (defun org-at-table.el-p ()
  4016. "Non-nil when point is at a table.el table."
  4017. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4018. (let ((element (org-element-at-point)))
  4019. (and (eq (org-element-type element) 'table)
  4020. (eq (org-element-property :type element) 'table.el)))))
  4021. (defun org-at-table-hline-p ()
  4022. "Non-nil when point is inside a hline in a table.
  4023. Assume point is already in a table. If `org-enable-table-editor'
  4024. is nil, return nil unconditionally."
  4025. (and org-enable-table-editor
  4026. (save-excursion
  4027. (beginning-of-line)
  4028. (looking-at org-table-hline-regexp))))
  4029. (defun org-table-map-tables (function &optional quietly)
  4030. "Apply FUNCTION to the start of all tables in the buffer."
  4031. (org-with-wide-buffer
  4032. (goto-char (point-min))
  4033. (while (re-search-forward org-table-any-line-regexp nil t)
  4034. (unless quietly
  4035. (message "Mapping tables: %d%%"
  4036. (floor (* 100.0 (point)) (buffer-size))))
  4037. (beginning-of-line 1)
  4038. (when (and (looking-at org-table-line-regexp)
  4039. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4040. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4041. (save-excursion (funcall function))
  4042. (or (looking-at org-table-line-regexp)
  4043. (forward-char 1)))
  4044. (re-search-forward org-table-any-border-regexp nil 1)))
  4045. (unless quietly (message "Mapping tables: done")))
  4046. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4047. (declare-function org-clock-update-mode-line "org-clock" ())
  4048. (declare-function org-resolve-clocks "org-clock"
  4049. (&optional also-non-dangling-p prompt last-valid))
  4050. (defun org-at-TBLFM-p (&optional pos)
  4051. "Non-nil when point (or POS) is in #+TBLFM line."
  4052. (save-excursion
  4053. (goto-char (or pos (point)))
  4054. (beginning-of-line)
  4055. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4056. (eq (org-element-type (org-element-at-point)) 'table))))
  4057. (defvar org-clock-start-time)
  4058. (defvar org-clock-marker (make-marker)
  4059. "Marker recording the last clock-in.")
  4060. (defvar org-clock-hd-marker (make-marker)
  4061. "Marker recording the last clock-in, but the headline position.")
  4062. (defvar org-clock-heading ""
  4063. "The heading of the current clock entry.")
  4064. (defun org-clock-is-active ()
  4065. "Return the buffer where the clock is currently running.
  4066. Return nil if no clock is running."
  4067. (marker-buffer org-clock-marker))
  4068. (defun org-check-running-clock ()
  4069. "Check if the current buffer contains the running clock.
  4070. If yes, offer to stop it and to save the buffer with the changes."
  4071. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4072. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4073. (buffer-name))))
  4074. (org-clock-out)
  4075. (when (y-or-n-p "Save changed buffer?")
  4076. (save-buffer))))
  4077. (defun org-clocktable-try-shift (dir n)
  4078. "Check if this line starts a clock table, if yes, shift the time block."
  4079. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4080. (org-clocktable-shift dir n)))
  4081. ;;;###autoload
  4082. (defun org-clock-persistence-insinuate ()
  4083. "Set up hooks for clock persistence."
  4084. (require 'org-clock)
  4085. (add-hook 'org-mode-hook 'org-clock-load)
  4086. (add-hook 'kill-emacs-hook 'org-clock-save))
  4087. (defgroup org-archive nil
  4088. "Options concerning archiving in Org mode."
  4089. :tag "Org Archive"
  4090. :group 'org-structure)
  4091. (defcustom org-archive-location "%s_archive::"
  4092. "The location where subtrees should be archived.
  4093. The value of this variable is a string, consisting of two parts,
  4094. separated by a double-colon. The first part is a filename and
  4095. the second part is a headline.
  4096. When the filename is omitted, archiving happens in the same file.
  4097. %s in the filename will be replaced by the current file
  4098. name (without the directory part). Archiving to a different file
  4099. is useful to keep archived entries from contributing to the
  4100. Org Agenda.
  4101. The archived entries will be filed as subtrees of the specified
  4102. headline. When the headline is omitted, the subtrees are simply
  4103. filed away at the end of the file, as top-level entries. Also in
  4104. the heading you can use %s to represent the file name, this can be
  4105. useful when using the same archive for a number of different files.
  4106. Here are a few examples:
  4107. \"%s_archive::\"
  4108. If the current file is Projects.org, archive in file
  4109. Projects.org_archive, as top-level trees. This is the default.
  4110. \"::* Archived Tasks\"
  4111. Archive in the current file, under the top-level headline
  4112. \"* Archived Tasks\".
  4113. \"~/org/archive.org::\"
  4114. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4115. \"~/org/archive.org::* From %s\"
  4116. Archive in file ~/org/archive.org (absolute path), under headlines
  4117. \"From FILENAME\" where file name is the current file name.
  4118. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4119. The \"datetree/\" string is special, signifying to archive
  4120. items to the datetree. Items are placed in either the CLOSED
  4121. date of the item, or the current date if there is no CLOSED date.
  4122. The heading will be a subentry to the current date. There doesn't
  4123. need to be a heading, but there always needs to be a slash after
  4124. datetree. For example, to store archived items directly in the
  4125. datetree, use \"~/org/datetree.org::datetree/\".
  4126. \"basement::** Finished Tasks\"
  4127. Archive in file ./basement (relative path), as level 3 trees
  4128. below the level 2 heading \"** Finished Tasks\".
  4129. You may set this option on a per-file basis by adding to the buffer a
  4130. line like
  4131. #+ARCHIVE: basement::** Finished Tasks
  4132. You may also define it locally for a subtree by setting an ARCHIVE property
  4133. in the entry. If such a property is found in an entry, or anywhere up
  4134. the hierarchy, it will be used."
  4135. :group 'org-archive
  4136. :type 'string)
  4137. (defcustom org-agenda-skip-archived-trees t
  4138. "Non-nil means the agenda will skip any items located in archived trees.
  4139. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4140. variable is no longer recommended, you should leave it at the value t.
  4141. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4142. :group 'org-archive
  4143. :group 'org-agenda-skip
  4144. :type 'boolean)
  4145. (defcustom org-columns-skip-archived-trees t
  4146. "Non-nil means ignore archived trees when creating column view."
  4147. :group 'org-archive
  4148. :group 'org-properties
  4149. :type 'boolean)
  4150. (defcustom org-cycle-open-archived-trees nil
  4151. "Non-nil means `org-cycle' will open archived trees.
  4152. An archived tree is a tree marked with the tag ARCHIVE.
  4153. When nil, archived trees will stay folded. You can still open them with
  4154. normal outline commands like `show-all', but not with the cycling commands."
  4155. :group 'org-archive
  4156. :group 'org-cycle
  4157. :type 'boolean)
  4158. (defcustom org-sparse-tree-open-archived-trees nil
  4159. "Non-nil means sparse tree construction shows matches in archived trees.
  4160. When nil, matches in these trees are highlighted, but the trees are kept in
  4161. collapsed state."
  4162. :group 'org-archive
  4163. :group 'org-sparse-trees
  4164. :type 'boolean)
  4165. (defcustom org-sparse-tree-default-date-type nil
  4166. "The default date type when building a sparse tree.
  4167. When this is nil, a date is a scheduled or a deadline timestamp.
  4168. Otherwise, these types are allowed:
  4169. all: all timestamps
  4170. active: only active timestamps (<...>)
  4171. inactive: only inactive timestamps ([...])
  4172. scheduled: only scheduled timestamps
  4173. deadline: only deadline timestamps"
  4174. :type '(choice (const :tag "Scheduled or deadline" nil)
  4175. (const :tag "All timestamps" all)
  4176. (const :tag "Only active timestamps" active)
  4177. (const :tag "Only inactive timestamps" inactive)
  4178. (const :tag "Only scheduled timestamps" scheduled)
  4179. (const :tag "Only deadline timestamps" deadline)
  4180. (const :tag "Only closed timestamps" closed))
  4181. :version "26.1"
  4182. :package-version '(Org . "8.3")
  4183. :group 'org-sparse-trees)
  4184. (defun org-cycle-hide-archived-subtrees (state)
  4185. "Re-hide all archived subtrees after a visibility state change."
  4186. (when (and (not org-cycle-open-archived-trees)
  4187. (not (memq state '(overview folded))))
  4188. (save-excursion
  4189. (let* ((globalp (memq state '(contents all)))
  4190. (beg (if globalp (point-min) (point)))
  4191. (end (if globalp (point-max) (org-end-of-subtree t))))
  4192. (org-hide-archived-subtrees beg end)
  4193. (goto-char beg)
  4194. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4195. (message "%s" (substitute-command-keys
  4196. "Subtree is archived and stays closed. Use \
  4197. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4198. (defun org-force-cycle-archived ()
  4199. "Cycle subtree even if it is archived."
  4200. (interactive)
  4201. (setq this-command 'org-cycle)
  4202. (let ((org-cycle-open-archived-trees t))
  4203. (call-interactively 'org-cycle)))
  4204. (defun org-hide-archived-subtrees (beg end)
  4205. "Re-hide all archived subtrees after a visibility state change."
  4206. (org-with-wide-buffer
  4207. (let ((case-fold-search nil)
  4208. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4209. (goto-char beg)
  4210. ;; Include headline point is currently on.
  4211. (beginning-of-line)
  4212. (while (and (< (point) end) (re-search-forward re end t))
  4213. (when (member org-archive-tag (org-get-tags))
  4214. (org-flag-subtree t)
  4215. (org-end-of-subtree t))))))
  4216. (declare-function outline-end-of-heading "outline" ())
  4217. (declare-function outline-flag-region "outline" (from to flag))
  4218. (defun org-flag-subtree (flag)
  4219. (save-excursion
  4220. (org-back-to-heading t)
  4221. (outline-end-of-heading)
  4222. (outline-flag-region (point)
  4223. (progn (org-end-of-subtree t) (point))
  4224. flag)))
  4225. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4226. ;; Declare Column View Code
  4227. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4228. (declare-function org-columns-compute "org-colview" (property))
  4229. ;; Declare ID code
  4230. (declare-function org-id-store-link "org-id")
  4231. (declare-function org-id-locations-load "org-id")
  4232. (declare-function org-id-locations-save "org-id")
  4233. (defvar org-id-track-globally)
  4234. ;;; Variables for pre-computed regular expressions, all buffer local
  4235. (defvar-local org-todo-regexp nil
  4236. "Matches any of the TODO state keywords.
  4237. Since TODO keywords are case-sensitive, `case-fold-search' is
  4238. expected to be bound to nil when matching against this regexp.")
  4239. (defvar-local org-not-done-regexp nil
  4240. "Matches any of the TODO state keywords except the last one.
  4241. Since TODO keywords are case-sensitive, `case-fold-search' is
  4242. expected to be bound to nil when matching against this regexp.")
  4243. (defvar-local org-not-done-heading-regexp nil
  4244. "Matches a TODO headline that is not done.
  4245. Since TODO keywords are case-sensitive, `case-fold-search' is
  4246. expected to be bound to nil when matching against this regexp.")
  4247. (defvar-local org-todo-line-regexp nil
  4248. "Matches a headline and puts TODO state into group 2 if present.
  4249. Since TODO keywords are case-sensitive, `case-fold-search' is
  4250. expected to be bound to nil when matching against this regexp.")
  4251. (defvar-local org-complex-heading-regexp nil
  4252. "Matches a headline and puts everything into groups:
  4253. group 1: Stars
  4254. group 2: The TODO keyword, maybe
  4255. group 3: Priority cookie
  4256. group 4: True headline
  4257. group 5: Tags
  4258. Since TODO keywords are case-sensitive, `case-fold-search' is
  4259. expected to be bound to nil when matching against this regexp.")
  4260. (defvar-local org-complex-heading-regexp-format nil
  4261. "Printf format to make regexp to match an exact headline.
  4262. This regexp will match the headline of any node which has the
  4263. exact headline text that is put into the format, but may have any
  4264. TODO state, priority and tags.")
  4265. (defvar-local org-todo-line-tags-regexp nil
  4266. "Matches a headline and puts TODO state into group 2 if present.
  4267. Also put tags into group 4 if tags are present.")
  4268. (defconst org-plain-time-of-day-regexp
  4269. (concat
  4270. "\\(\\<[012]?[0-9]"
  4271. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4272. "\\(--?"
  4273. "\\(\\<[012]?[0-9]"
  4274. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4275. "\\)?")
  4276. "Regular expression to match a plain time or time range.
  4277. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4278. groups carry important information:
  4279. 0 the full match
  4280. 1 the first time, range or not
  4281. 8 the second time, if it is a range.")
  4282. (defconst org-plain-time-extension-regexp
  4283. (concat
  4284. "\\(\\<[012]?[0-9]"
  4285. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4286. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4287. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4288. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4289. groups carry important information:
  4290. 0 the full match
  4291. 7 hours of duration
  4292. 9 minutes of duration")
  4293. (defconst org-stamp-time-of-day-regexp
  4294. (concat
  4295. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4296. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4297. "\\(--?"
  4298. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4299. "Regular expression to match a timestamp time or time range.
  4300. After a match, the following groups carry important information:
  4301. 0 the full match
  4302. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4303. 2 the first time, range or not
  4304. 4 the second time, if it is a range.")
  4305. (defconst org-startup-options
  4306. '(("fold" org-startup-folded t)
  4307. ("overview" org-startup-folded t)
  4308. ("nofold" org-startup-folded nil)
  4309. ("showall" org-startup-folded nil)
  4310. ("showeverything" org-startup-folded showeverything)
  4311. ("content" org-startup-folded content)
  4312. ("indent" org-startup-indented t)
  4313. ("noindent" org-startup-indented nil)
  4314. ("hidestars" org-hide-leading-stars t)
  4315. ("showstars" org-hide-leading-stars nil)
  4316. ("odd" org-odd-levels-only t)
  4317. ("oddeven" org-odd-levels-only nil)
  4318. ("align" org-startup-align-all-tables t)
  4319. ("noalign" org-startup-align-all-tables nil)
  4320. ("inlineimages" org-startup-with-inline-images t)
  4321. ("noinlineimages" org-startup-with-inline-images nil)
  4322. ("latexpreview" org-startup-with-latex-preview t)
  4323. ("nolatexpreview" org-startup-with-latex-preview nil)
  4324. ("customtime" org-display-custom-times t)
  4325. ("logdone" org-log-done time)
  4326. ("lognotedone" org-log-done note)
  4327. ("nologdone" org-log-done nil)
  4328. ("lognoteclock-out" org-log-note-clock-out t)
  4329. ("nolognoteclock-out" org-log-note-clock-out nil)
  4330. ("logrepeat" org-log-repeat state)
  4331. ("lognoterepeat" org-log-repeat note)
  4332. ("logdrawer" org-log-into-drawer t)
  4333. ("nologdrawer" org-log-into-drawer nil)
  4334. ("logstatesreversed" org-log-states-order-reversed t)
  4335. ("nologstatesreversed" org-log-states-order-reversed nil)
  4336. ("nologrepeat" org-log-repeat nil)
  4337. ("logreschedule" org-log-reschedule time)
  4338. ("lognotereschedule" org-log-reschedule note)
  4339. ("nologreschedule" org-log-reschedule nil)
  4340. ("logredeadline" org-log-redeadline time)
  4341. ("lognoteredeadline" org-log-redeadline note)
  4342. ("nologredeadline" org-log-redeadline nil)
  4343. ("logrefile" org-log-refile time)
  4344. ("lognoterefile" org-log-refile note)
  4345. ("nologrefile" org-log-refile nil)
  4346. ("fninline" org-footnote-define-inline t)
  4347. ("nofninline" org-footnote-define-inline nil)
  4348. ("fnlocal" org-footnote-section nil)
  4349. ("fnauto" org-footnote-auto-label t)
  4350. ("fnprompt" org-footnote-auto-label nil)
  4351. ("fnconfirm" org-footnote-auto-label confirm)
  4352. ("fnplain" org-footnote-auto-label plain)
  4353. ("fnadjust" org-footnote-auto-adjust t)
  4354. ("nofnadjust" org-footnote-auto-adjust nil)
  4355. ("constcgs" constants-unit-system cgs)
  4356. ("constSI" constants-unit-system SI)
  4357. ("noptag" org-tag-persistent-alist nil)
  4358. ("hideblocks" org-hide-block-startup t)
  4359. ("nohideblocks" org-hide-block-startup nil)
  4360. ("beamer" org-startup-with-beamer-mode t)
  4361. ("entitiespretty" org-pretty-entities t)
  4362. ("entitiesplain" org-pretty-entities nil))
  4363. "Variable associated with STARTUP options for org-mode.
  4364. Each element is a list of three items: the startup options (as written
  4365. in the #+STARTUP line), the corresponding variable, and the value to set
  4366. this variable to if the option is found. An optional forth element PUSH
  4367. means to push this value onto the list in the variable.")
  4368. (defcustom org-group-tags t
  4369. "When non-nil (the default), use group tags.
  4370. This can be turned on/off through `org-toggle-tags-groups'."
  4371. :group 'org-tags
  4372. :group 'org-startup
  4373. :type 'boolean)
  4374. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4375. (defun org-toggle-tags-groups ()
  4376. "Toggle support for group tags.
  4377. Support for group tags is controlled by the option
  4378. `org-group-tags', which is non-nil by default."
  4379. (interactive)
  4380. (setq org-group-tags (not org-group-tags))
  4381. (cond ((and (derived-mode-p 'org-agenda-mode)
  4382. org-group-tags)
  4383. (org-agenda-redo))
  4384. ((derived-mode-p 'org-mode)
  4385. (let ((org-inhibit-startup t)) (org-mode))))
  4386. (message "Groups tags support has been turned %s"
  4387. (if org-group-tags "on" "off")))
  4388. (defun org-set-regexps-and-options (&optional tags-only)
  4389. "Precompute regular expressions used in the current buffer.
  4390. When optional argument TAGS-ONLY is non-nil, only compute tags
  4391. related expressions."
  4392. (when (derived-mode-p 'org-mode)
  4393. (let ((alist (org--setup-collect-keywords
  4394. (org-make-options-regexp
  4395. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4396. (and (not tags-only)
  4397. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4398. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4399. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4400. ;; Startup options. Get this early since it does change
  4401. ;; behavior for other options (e.g., tags).
  4402. (let ((startup (cdr (assq 'startup alist))))
  4403. (dolist (option startup)
  4404. (let ((entry (assoc-string option org-startup-options t)))
  4405. (when entry
  4406. (let ((var (nth 1 entry))
  4407. (val (nth 2 entry)))
  4408. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4409. (unless (listp (symbol-value var))
  4410. (set (make-local-variable var) nil))
  4411. (add-to-list var val)))))))
  4412. (setq-local org-file-tags
  4413. (mapcar #'org-add-prop-inherited
  4414. (cdr (assq 'filetags alist))))
  4415. (setq org-current-tag-alist
  4416. (append org-tag-persistent-alist
  4417. (let ((tags (cdr (assq 'tags alist))))
  4418. (if tags (org-tag-string-to-alist tags)
  4419. org-tag-alist))))
  4420. (setq org-tag-groups-alist
  4421. (org-tag-alist-to-groups org-current-tag-alist))
  4422. (unless tags-only
  4423. ;; File properties.
  4424. (setq-local org-file-properties (cdr (assq 'property alist)))
  4425. ;; Archive location.
  4426. (let ((archive (cdr (assq 'archive alist))))
  4427. (when archive (setq-local org-archive-location archive)))
  4428. ;; Category.
  4429. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4430. (when cat
  4431. (setq-local org-category (intern cat))
  4432. (setq-local org-file-properties
  4433. (org--update-property-plist
  4434. "CATEGORY" cat org-file-properties))))
  4435. ;; Columns.
  4436. (let ((column (cdr (assq 'columns alist))))
  4437. (when column (setq-local org-columns-default-format column)))
  4438. ;; Constants.
  4439. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4440. ;; Link abbreviations.
  4441. (let ((links (cdr (assq 'link alist))))
  4442. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4443. ;; Priorities.
  4444. (let ((priorities (cdr (assq 'priorities alist))))
  4445. (when priorities
  4446. (setq-local org-highest-priority (nth 0 priorities))
  4447. (setq-local org-lowest-priority (nth 1 priorities))
  4448. (setq-local org-default-priority (nth 2 priorities))))
  4449. ;; Scripts.
  4450. (let ((scripts (assq 'scripts alist)))
  4451. (when scripts
  4452. (setq-local org-use-sub-superscripts (cdr scripts))))
  4453. ;; TODO keywords.
  4454. (setq-local org-todo-kwd-alist nil)
  4455. (setq-local org-todo-key-alist nil)
  4456. (setq-local org-todo-key-trigger nil)
  4457. (setq-local org-todo-keywords-1 nil)
  4458. (setq-local org-done-keywords nil)
  4459. (setq-local org-todo-heads nil)
  4460. (setq-local org-todo-sets nil)
  4461. (setq-local org-todo-log-states nil)
  4462. (let ((todo-sequences
  4463. (or (nreverse (cdr (assq 'todo alist)))
  4464. (let ((d (default-value 'org-todo-keywords)))
  4465. (if (not (stringp (car d))) d
  4466. ;; XXX: Backward compatibility code.
  4467. (list (cons org-todo-interpretation d)))))))
  4468. (dolist (sequence todo-sequences)
  4469. (let* ((sequence (or (run-hook-with-args-until-success
  4470. 'org-todo-setup-filter-hook sequence)
  4471. sequence))
  4472. (sequence-type (car sequence))
  4473. (keywords (cdr sequence))
  4474. (sep (member "|" keywords))
  4475. names alist)
  4476. (dolist (k (remove "|" keywords))
  4477. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4478. k)
  4479. (error "Invalid TODO keyword %s" k))
  4480. (let ((name (match-string 1 k))
  4481. (key (match-string 2 k))
  4482. (log (org-extract-log-state-settings k)))
  4483. (push name names)
  4484. (push (cons name (and key (string-to-char key))) alist)
  4485. (when log (push log org-todo-log-states))))
  4486. (let* ((names (nreverse names))
  4487. (done (if sep (org-remove-keyword-keys (cdr sep))
  4488. (last names)))
  4489. (head (car names))
  4490. (tail (list sequence-type head (car done) (org-last done))))
  4491. (add-to-list 'org-todo-heads head 'append)
  4492. (push names org-todo-sets)
  4493. (setq org-done-keywords (append org-done-keywords done nil))
  4494. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4495. (setq org-todo-key-alist
  4496. (append org-todo-key-alist
  4497. (and alist
  4498. (append '((:startgroup))
  4499. (nreverse alist)
  4500. '((:endgroup))))))
  4501. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4502. (setq org-todo-sets (nreverse org-todo-sets)
  4503. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4504. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4505. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4506. ;; Compute the regular expressions and other local variables.
  4507. ;; Using `org-outline-regexp-bol' would complicate them much,
  4508. ;; because of the fixed white space at the end of that string.
  4509. (unless org-done-keywords
  4510. (setq org-done-keywords
  4511. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4512. (setq org-not-done-keywords
  4513. (org-delete-all org-done-keywords
  4514. (copy-sequence org-todo-keywords-1))
  4515. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4516. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4517. org-not-done-heading-regexp
  4518. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4519. org-todo-line-regexp
  4520. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4521. org-complex-heading-regexp
  4522. (concat "^\\(\\*+\\)"
  4523. "\\(?: +" org-todo-regexp "\\)?"
  4524. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4525. "\\(?: +\\(.*?\\)\\)??"
  4526. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4527. "[ \t]*$")
  4528. org-complex-heading-regexp-format
  4529. (concat "^\\(\\*+\\)"
  4530. "\\(?: +" org-todo-regexp "\\)?"
  4531. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4532. "\\(?: +"
  4533. ;; Stats cookies can be stuck to body.
  4534. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4535. "\\(%s\\)"
  4536. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4537. "\\)"
  4538. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4539. "[ \t]*$")
  4540. org-todo-line-tags-regexp
  4541. (concat "^\\(\\*+\\)"
  4542. "\\(?: +" org-todo-regexp "\\)?"
  4543. "\\(?: +\\(.*?\\)\\)??"
  4544. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4545. "[ \t]*$"))
  4546. (org-compute-latex-and-related-regexp)))))
  4547. (defun org--setup-collect-keywords (regexp &optional files alist)
  4548. "Return setup keywords values as an alist.
  4549. REGEXP matches a subset of setup keywords. FILES is a list of
  4550. file names already visited. It is used to avoid circular setup
  4551. files. ALIST, when non-nil, is the alist computed so far.
  4552. Return value contains the following keys: `archive', `category',
  4553. `columns', `constants', `filetags', `link', `priorities',
  4554. `property', `scripts', `startup', `tags' and `todo'."
  4555. (org-with-wide-buffer
  4556. (goto-char (point-min))
  4557. (let ((case-fold-search t))
  4558. (while (re-search-forward regexp nil t)
  4559. (let ((element (org-element-at-point)))
  4560. (when (eq (org-element-type element) 'keyword)
  4561. (let ((key (org-element-property :key element))
  4562. (value (org-element-property :value element)))
  4563. (cond
  4564. ((equal key "ARCHIVE")
  4565. (when (org-string-nw-p value)
  4566. (push (cons 'archive value) alist)))
  4567. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4568. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4569. ((equal key "CONSTANTS")
  4570. (let* ((constants (assq 'constants alist))
  4571. (store (cdr constants)))
  4572. (dolist (pair (org-split-string value))
  4573. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4574. pair)
  4575. (let* ((name (match-string 1 pair))
  4576. (value (match-string 2 pair))
  4577. (old (assoc name store)))
  4578. (if old (setcdr old value)
  4579. (push (cons name value) store)))))
  4580. (if constants (setcdr constants store)
  4581. (push (cons 'constants store) alist))))
  4582. ((equal key "FILETAGS")
  4583. (when (org-string-nw-p value)
  4584. (let ((old (assq 'filetags alist))
  4585. (new (apply #'nconc
  4586. (mapcar (lambda (x) (org-split-string x ":"))
  4587. (org-split-string value)))))
  4588. (if old (setcdr old (append new (cdr old)))
  4589. (push (cons 'filetags new) alist)))))
  4590. ((equal key "LINK")
  4591. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4592. (let ((links (assq 'link alist))
  4593. (pair (cons (match-string-no-properties 1 value)
  4594. (match-string-no-properties 2 value))))
  4595. (if links (push pair (cdr links))
  4596. (push (list 'link pair) alist)))))
  4597. ((equal key "OPTIONS")
  4598. (when (and (org-string-nw-p value)
  4599. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4600. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4601. ((equal key "PRIORITIES")
  4602. (push (cons 'priorities
  4603. (let ((prio (org-split-string value)))
  4604. (if (< (length prio) 3) '(?A ?C ?B)
  4605. (mapcar #'string-to-char prio))))
  4606. alist))
  4607. ((equal key "PROPERTY")
  4608. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4609. (let* ((property (assq 'property alist))
  4610. (value (org--update-property-plist
  4611. (match-string-no-properties 1 value)
  4612. (match-string-no-properties 2 value)
  4613. (cdr property))))
  4614. (if property (setcdr property value)
  4615. (push (cons 'property value) alist)))))
  4616. ((equal key "STARTUP")
  4617. (let ((startup (assq 'startup alist)))
  4618. (if startup
  4619. (setcdr startup
  4620. (append (cdr startup) (org-split-string value)))
  4621. (push (cons 'startup (org-split-string value)) alist))))
  4622. ((equal key "TAGS")
  4623. (let ((tag-cell (assq 'tags alist)))
  4624. (if tag-cell
  4625. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4626. (push (cons 'tags value) alist))))
  4627. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4628. (let ((todo (assq 'todo alist))
  4629. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4630. (org-split-string value))))
  4631. (if todo (push value (cdr todo))
  4632. (push (list 'todo value) alist))))
  4633. ((equal key "SETUPFILE")
  4634. (unless buffer-read-only ; Do not check in Gnus messages.
  4635. (let ((f (and (org-string-nw-p value)
  4636. (expand-file-name
  4637. (org-unbracket-string "\"" "\"" value)))))
  4638. (when (and f (file-readable-p f) (not (member f files)))
  4639. (with-temp-buffer
  4640. (setq default-directory (file-name-directory f))
  4641. (insert-file-contents f)
  4642. (setq alist
  4643. ;; Fake Org mode to benefit from cache
  4644. ;; without recurring needlessly.
  4645. (let ((major-mode 'org-mode))
  4646. (org--setup-collect-keywords
  4647. regexp (cons f files) alist)))))))))))))))
  4648. alist)
  4649. (defun org-tag-string-to-alist (s)
  4650. "Return tag alist associated to string S.
  4651. S is a value for TAGS keyword or produced with
  4652. `org-tag-alist-to-string'. Return value is an alist suitable for
  4653. `org-tag-alist' or `org-tag-persistent-alist'."
  4654. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4655. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4656. "\\|{.+?}\\)" ; regular expression
  4657. "\\(?:(\\(.\\))\\)?\\'"))
  4658. alist group-flag)
  4659. (dolist (tokens lines (cdr (nreverse alist)))
  4660. (push '(:newline) alist)
  4661. (while tokens
  4662. (let ((token (pop tokens)))
  4663. (pcase token
  4664. ("{"
  4665. (push '(:startgroup) alist)
  4666. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4667. ("}"
  4668. (push '(:endgroup) alist)
  4669. (setq group-flag nil))
  4670. ("["
  4671. (push '(:startgrouptag) alist)
  4672. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4673. ("]"
  4674. (push '(:endgrouptag) alist)
  4675. (setq group-flag nil))
  4676. (":"
  4677. (push '(:grouptags) alist))
  4678. ((guard (string-match tag-re token))
  4679. (let ((tag (match-string 1 token))
  4680. (key (and (match-beginning 2)
  4681. (string-to-char (match-string 2 token)))))
  4682. ;; Push all tags in groups, no matter if they already
  4683. ;; appear somewhere else in the list.
  4684. (when (or group-flag (not (assoc tag alist)))
  4685. (push (cons tag key) alist))))))))))
  4686. (defun org-tag-alist-to-string (alist &optional skip-key)
  4687. "Return tag string associated to ALIST.
  4688. ALIST is an alist, as defined in `org-tag-alist' or
  4689. `org-tag-persistent-alist', or produced with
  4690. `org-tag-string-to-alist'.
  4691. Return value is a string suitable as a value for \"TAGS\"
  4692. keyword.
  4693. When optional argument SKIP-KEY is non-nil, skip selection keys
  4694. next to tags."
  4695. (mapconcat (lambda (token)
  4696. (pcase token
  4697. (`(:startgroup) "{")
  4698. (`(:endgroup) "}")
  4699. (`(:startgrouptag) "[")
  4700. (`(:endgrouptag) "]")
  4701. (`(:grouptags) ":")
  4702. (`(:newline) "\\n")
  4703. ((and
  4704. (guard (not skip-key))
  4705. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4706. (format "%s(%c)" tag key))
  4707. (`(,(and tag (pred stringp)) . ,_) tag)
  4708. (_ (user-error "Invalid tag token: %S" token))))
  4709. alist
  4710. " "))
  4711. (defun org-tag-alist-to-groups (alist)
  4712. "Return group alist from tag ALIST.
  4713. ALIST is an alist, as defined in `org-tag-alist' or
  4714. `org-tag-persistent-alist', or produced with
  4715. `org-tag-string-to-alist'. Return value is an alist following
  4716. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4717. a string, summarizing TAGS, as a list of strings."
  4718. (let (groups group-status current-group)
  4719. (dolist (token alist (nreverse groups))
  4720. (pcase token
  4721. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4722. (`(,(or :endgroup :endgrouptag))
  4723. (when (eq group-status 'append)
  4724. (push (nreverse current-group) groups))
  4725. (setq group-status nil))
  4726. (`(:grouptags) (setq group-status 'append))
  4727. ((and `(,tag . ,_) (guard group-status))
  4728. (if (eq group-status 'append) (push tag current-group)
  4729. (setq current-group (list tag))))
  4730. (_ nil)))))
  4731. (defun org-file-contents (file &optional noerror)
  4732. "Return the contents of FILE, as a string."
  4733. (if (and file (file-readable-p file))
  4734. (with-temp-buffer
  4735. (insert-file-contents file)
  4736. (buffer-string))
  4737. (funcall (if noerror 'message 'error)
  4738. "Cannot read file \"%s\"%s"
  4739. file
  4740. (let ((from (buffer-file-name (buffer-base-buffer))))
  4741. (if from (concat " (referenced in file \"" from "\")") "")))))
  4742. (defun org-extract-log-state-settings (x)
  4743. "Extract the log state setting from a TODO keyword string.
  4744. This will extract info from a string like \"WAIT(w@/!)\"."
  4745. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4746. (let ((kw (match-string 1 x))
  4747. (log1 (and (match-end 3) (match-string 3 x)))
  4748. (log2 (and (match-end 4) (match-string 4 x))))
  4749. (and (or log1 log2)
  4750. (list kw
  4751. (and log1 (if (equal log1 "!") 'time 'note))
  4752. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4753. (defun org-remove-keyword-keys (list)
  4754. "Remove a pair of parenthesis at the end of each string in LIST."
  4755. (mapcar (lambda (x)
  4756. (if (string-match "(.*)$" x)
  4757. (substring x 0 (match-beginning 0))
  4758. x))
  4759. list))
  4760. (defun org-assign-fast-keys (alist)
  4761. "Assign fast keys to a keyword-key alist.
  4762. Respect keys that are already there."
  4763. (let (new e (alt ?0))
  4764. (while (setq e (pop alist))
  4765. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4766. (cdr e)) ;; Key already assigned.
  4767. (push e new)
  4768. (let ((clist (string-to-list (downcase (car e))))
  4769. (used (append new alist)))
  4770. (when (= (car clist) ?@)
  4771. (pop clist))
  4772. (while (and clist (rassoc (car clist) used))
  4773. (pop clist))
  4774. (unless clist
  4775. (while (rassoc alt used)
  4776. (cl-incf alt)))
  4777. (push (cons (car e) (or (car clist) alt)) new))))
  4778. (nreverse new)))
  4779. ;;; Some variables used in various places
  4780. (defvar org-window-configuration nil
  4781. "Used in various places to store a window configuration.")
  4782. (defvar org-selected-window nil
  4783. "Used in various places to store a window configuration.")
  4784. (defvar org-finish-function nil
  4785. "Function to be called when `C-c C-c' is used.
  4786. This is for getting out of special buffers like capture.")
  4787. (defvar org-last-state)
  4788. ;; Defined somewhere in this file, but used before definition.
  4789. (defvar org-entities) ;; defined in org-entities.el
  4790. (defvar org-struct-menu)
  4791. (defvar org-org-menu)
  4792. (defvar org-tbl-menu)
  4793. ;;;; Define the Org mode
  4794. ;; We use a before-change function to check if a table might need
  4795. ;; an update.
  4796. (defvar org-table-may-need-update t
  4797. "Indicates that a table might need an update.
  4798. This variable is set by `org-before-change-function'.
  4799. `org-table-align' sets it back to nil.")
  4800. (defun org-before-change-function (_beg _end)
  4801. "Every change indicates that a table might need an update."
  4802. (setq org-table-may-need-update t))
  4803. (defvar org-mode-map)
  4804. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4805. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4806. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4807. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4808. (defvar org-table-buffer-is-an nil)
  4809. (defvar bidi-paragraph-direction)
  4810. (defvar buffer-face-mode-face)
  4811. (require 'outline)
  4812. ;; Other stuff we need.
  4813. (require 'time-date)
  4814. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4815. (require 'easymenu)
  4816. (autoload 'easy-menu-add "easymenu")
  4817. (require 'overlay)
  4818. ;; (require 'org-macs) moved higher up in the file before it is first used
  4819. (require 'org-entities)
  4820. ;; (require 'org-compat) moved higher up in the file before it is first used
  4821. (require 'org-faces)
  4822. (require 'org-list)
  4823. (require 'org-pcomplete)
  4824. (require 'org-src)
  4825. (require 'org-footnote)
  4826. (require 'org-macro)
  4827. ;; babel
  4828. (require 'ob)
  4829. ;;;###autoload
  4830. (define-derived-mode org-mode outline-mode "Org"
  4831. "Outline-based notes management and organizer, alias
  4832. \"Carsten's outline-mode for keeping track of everything.\"
  4833. Org mode develops organizational tasks around a NOTES file which
  4834. contains information about projects as plain text. Org mode is
  4835. implemented on top of Outline mode, which is ideal to keep the content
  4836. of large files well structured. It supports ToDo items, deadlines and
  4837. time stamps, which magically appear in the diary listing of the Emacs
  4838. calendar. Tables are easily created with a built-in table editor.
  4839. Plain text URL-like links connect to websites, emails (VM), Usenet
  4840. messages (Gnus), BBDB entries, and any files related to the project.
  4841. For printing and sharing of notes, an Org file (or a part of it)
  4842. can be exported as a structured ASCII or HTML file.
  4843. The following commands are available:
  4844. \\{org-mode-map}"
  4845. ;; Get rid of Outline menus, they are not needed
  4846. ;; Need to do this here because define-derived-mode sets up
  4847. ;; the keymap so late. Still, it is a waste to call this each time
  4848. ;; we switch another buffer into Org mode.
  4849. (define-key org-mode-map [menu-bar headings] 'undefined)
  4850. (define-key org-mode-map [menu-bar hide] 'undefined)
  4851. (define-key org-mode-map [menu-bar show] 'undefined)
  4852. (org-load-modules-maybe)
  4853. (org-install-agenda-files-menu)
  4854. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4855. (add-to-invisibility-spec '(org-cwidth))
  4856. (add-to-invisibility-spec '(org-hide-block . t))
  4857. (setq-local outline-regexp org-outline-regexp)
  4858. (setq-local outline-level 'org-outline-level)
  4859. (setq bidi-paragraph-direction 'left-to-right)
  4860. (when (and org-ellipsis
  4861. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4862. (fboundp 'make-glyph-code))
  4863. (unless org-display-table
  4864. (setq org-display-table (make-display-table)))
  4865. (set-display-table-slot
  4866. org-display-table 4
  4867. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4868. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4869. (setq buffer-display-table org-display-table))
  4870. (org-set-regexps-and-options)
  4871. (org-set-font-lock-defaults)
  4872. (when (and org-tag-faces (not org-tags-special-faces-re))
  4873. ;; tag faces set outside customize.... force initialization.
  4874. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4875. ;; Calc embedded
  4876. (setq-local calc-embedded-open-mode "# ")
  4877. ;; Modify a few syntax entries
  4878. (modify-syntax-entry ?@ "w")
  4879. (modify-syntax-entry ?\" "\"")
  4880. (modify-syntax-entry ?\\ "_")
  4881. (modify-syntax-entry ?~ "_")
  4882. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4883. ;; Activate before-change-function
  4884. (setq-local org-table-may-need-update t)
  4885. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4886. ;; Check for running clock before killing a buffer
  4887. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4888. ;; Initialize macros templates.
  4889. (org-macro-initialize-templates)
  4890. ;; Initialize radio targets.
  4891. (org-update-radio-target-regexp)
  4892. ;; Indentation.
  4893. (setq-local indent-line-function 'org-indent-line)
  4894. (setq-local indent-region-function 'org-indent-region)
  4895. ;; Filling and auto-filling.
  4896. (org-setup-filling)
  4897. ;; Comments.
  4898. (org-setup-comments-handling)
  4899. ;; Initialize cache.
  4900. (org-element-cache-reset)
  4901. ;; Beginning/end of defun
  4902. (setq-local beginning-of-defun-function 'org-backward-element)
  4903. (setq-local end-of-defun-function
  4904. (lambda ()
  4905. (if (not (org-at-heading-p))
  4906. (org-forward-element)
  4907. (org-forward-element)
  4908. (forward-char -1))))
  4909. ;; Next error for sparse trees
  4910. (setq-local next-error-function 'org-occur-next-match)
  4911. ;; Make sure dependence stuff works reliably, even for users who set it
  4912. ;; too late :-(
  4913. (if org-enforce-todo-dependencies
  4914. (add-hook 'org-blocker-hook
  4915. 'org-block-todo-from-children-or-siblings-or-parent)
  4916. (remove-hook 'org-blocker-hook
  4917. 'org-block-todo-from-children-or-siblings-or-parent))
  4918. (if org-enforce-todo-checkbox-dependencies
  4919. (add-hook 'org-blocker-hook
  4920. 'org-block-todo-from-checkboxes)
  4921. (remove-hook 'org-blocker-hook
  4922. 'org-block-todo-from-checkboxes))
  4923. ;; Align options lines
  4924. (setq-local
  4925. align-mode-rules-list
  4926. '((org-in-buffer-settings
  4927. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4928. (modes . '(org-mode)))))
  4929. ;; Imenu
  4930. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4931. ;; Make isearch reveal context
  4932. (setq-local outline-isearch-open-invisible-function
  4933. (lambda (&rest _) (org-show-context 'isearch)))
  4934. ;; Setup the pcomplete hooks
  4935. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4936. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4937. (setq-local pcomplete-default-completion-function 'ignore)
  4938. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4939. (setq-local pcomplete-termination-string "")
  4940. (setq-local buffer-face-mode-face 'org-default)
  4941. ;; If empty file that did not turn on Org mode automatically, make
  4942. ;; it to.
  4943. (when (and org-insert-mode-line-in-empty-file
  4944. (called-interactively-p 'any)
  4945. (= (point-min) (point-max)))
  4946. (insert "# -*- mode: org -*-\n\n"))
  4947. (unless org-inhibit-startup
  4948. (org-unmodified
  4949. (when org-startup-with-beamer-mode (org-beamer-mode))
  4950. (when org-startup-align-all-tables
  4951. (org-table-map-tables #'org-table-align t))
  4952. (when org-startup-with-inline-images (org-display-inline-images))
  4953. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4954. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4955. (when org-startup-truncated (setq truncate-lines t))
  4956. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4957. (org-refresh-effort-properties)))
  4958. ;; Try to set `org-hide' face correctly.
  4959. (let ((foreground (org-find-invisible-foreground)))
  4960. (when foreground
  4961. (set-face-foreground 'org-hide foreground))))
  4962. ;; Update `customize-package-emacs-version-alist'
  4963. (add-to-list 'customize-package-emacs-version-alist
  4964. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4965. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4966. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4967. ("9.0" . "26.1")))
  4968. (defvar org-mode-transpose-word-syntax-table
  4969. (let ((st (make-syntax-table text-mode-syntax-table)))
  4970. (dolist (c org-emphasis-alist st)
  4971. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4972. (when (fboundp 'abbrev-table-put)
  4973. (abbrev-table-put org-mode-abbrev-table
  4974. :parents (list text-mode-abbrev-table)))
  4975. (defun org-find-invisible-foreground ()
  4976. (let ((candidates (remove
  4977. "unspecified-bg"
  4978. (nconc
  4979. (list (face-background 'default)
  4980. (face-background 'org-default))
  4981. (mapcar
  4982. (lambda (alist)
  4983. (when (boundp alist)
  4984. (cdr (assq 'background-color (symbol-value alist)))))
  4985. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4986. (list (face-foreground 'org-hide))))))
  4987. (car (remove nil candidates))))
  4988. (defun org-current-time (&optional rounding-minutes past)
  4989. "Current time, possibly rounded to ROUNDING-MINUTES.
  4990. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4991. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4992. the rounding returns a past time."
  4993. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4994. (car org-time-stamp-rounding-minutes)))
  4995. (time (decode-time)) res)
  4996. (if (< r 1)
  4997. (current-time)
  4998. (setq res
  4999. (apply 'encode-time
  5000. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  5001. (nthcdr 2 time))))
  5002. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  5003. (seconds-to-time (- (float-time res) (* r 60)))
  5004. res))))
  5005. (defun org-today ()
  5006. "Return today date, considering `org-extend-today-until'."
  5007. (time-to-days
  5008. (time-subtract (current-time)
  5009. (list 0 (* 3600 org-extend-today-until) 0))))
  5010. ;;;; Font-Lock stuff, including the activators
  5011. (defvar org-mouse-map (make-sparse-keymap))
  5012. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  5013. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  5014. (when org-mouse-1-follows-link
  5015. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5016. (when org-tab-follows-link
  5017. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5018. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5019. (require 'font-lock)
  5020. (defconst org-non-link-chars "]\t\n\r<>")
  5021. (defvar org-link-types-re nil
  5022. "Matches a link that has a url-like prefix like \"http:\"")
  5023. (defvar org-link-re-with-space nil
  5024. "Matches a link with spaces, optional angular brackets around it.")
  5025. (defvar org-link-re-with-space2 nil
  5026. "Matches a link with spaces, optional angular brackets around it.")
  5027. (defvar org-link-re-with-space3 nil
  5028. "Matches a link with spaces, only for internal part in bracket links.")
  5029. (defvar org-angle-link-re nil
  5030. "Matches link with angular brackets, spaces are allowed.")
  5031. (defvar org-plain-link-re nil
  5032. "Matches plain link, without spaces.")
  5033. (defvar org-bracket-link-regexp nil
  5034. "Matches a link in double brackets.")
  5035. (defvar org-bracket-link-analytic-regexp nil
  5036. "Regular expression used to analyze links.
  5037. Here is what the match groups contain after a match:
  5038. 1: http:
  5039. 2: http
  5040. 3: path
  5041. 4: [desc]
  5042. 5: desc")
  5043. (defvar org-bracket-link-analytic-regexp++ nil
  5044. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5045. (defvar org-any-link-re nil
  5046. "Regular expression matching any link.")
  5047. (defconst org-match-sexp-depth 3
  5048. "Number of stacked braces for sub/superscript matching.")
  5049. (defun org-create-multibrace-regexp (left right n)
  5050. "Create a regular expression which will match a balanced sexp.
  5051. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5052. as single character strings.
  5053. The regexp returned will match the entire expression including the
  5054. delimiters. It will also define a single group which contains the
  5055. match except for the outermost delimiters. The maximum depth of
  5056. stacked delimiters is N. Escaping delimiters is not possible."
  5057. (let* ((nothing (concat "[^" left right "]*?"))
  5058. (or "\\|")
  5059. (re nothing)
  5060. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5061. (while (> n 1)
  5062. (setq n (1- n)
  5063. re (concat re or next)
  5064. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5065. (concat left "\\(" re "\\)" right)))
  5066. (defconst org-match-substring-regexp
  5067. (concat
  5068. "\\(\\S-\\)\\([_^]\\)\\("
  5069. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5070. "\\|"
  5071. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5072. "\\|"
  5073. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5074. "The regular expression matching a sub- or superscript.")
  5075. (defconst org-match-substring-with-braces-regexp
  5076. (concat
  5077. "\\(\\S-\\)\\([_^]\\)"
  5078. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5079. "The regular expression matching a sub- or superscript, forcing braces.")
  5080. (defun org-make-link-regexps ()
  5081. "Update the link regular expressions.
  5082. This should be called after the variable `org-link-parameters' has changed."
  5083. (let ((types-re (regexp-opt (org-link-types) t)))
  5084. (setq org-link-types-re
  5085. (concat "\\`" types-re ":")
  5086. org-link-re-with-space
  5087. (concat "<?" types-re ":"
  5088. "\\([^" org-non-link-chars " ]"
  5089. "[^" org-non-link-chars "]*"
  5090. "[^" org-non-link-chars " ]\\)>?")
  5091. org-link-re-with-space2
  5092. (concat "<?" types-re ":"
  5093. "\\([^" org-non-link-chars " ]"
  5094. "[^\t\n\r]*"
  5095. "[^" org-non-link-chars " ]\\)>?")
  5096. org-link-re-with-space3
  5097. (concat "<?" types-re ":"
  5098. "\\([^" org-non-link-chars " ]"
  5099. "[^\t\n\r]*\\)")
  5100. org-angle-link-re
  5101. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5102. types-re)
  5103. org-plain-link-re
  5104. (concat
  5105. "\\<" types-re ":"
  5106. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5107. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5108. org-bracket-link-regexp
  5109. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5110. org-bracket-link-analytic-regexp
  5111. (concat
  5112. "\\[\\["
  5113. "\\(" types-re ":\\)?"
  5114. "\\([^]]+\\)"
  5115. "\\]"
  5116. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5117. "\\]")
  5118. org-bracket-link-analytic-regexp++
  5119. (concat
  5120. "\\[\\["
  5121. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5122. "\\([^]]+\\)"
  5123. "\\]"
  5124. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5125. "\\]")
  5126. org-any-link-re
  5127. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5128. org-angle-link-re "\\)\\|\\("
  5129. org-plain-link-re "\\)"))))
  5130. (org-make-link-regexps)
  5131. (defvar org-emph-face nil)
  5132. (defun org-do-emphasis-faces (limit)
  5133. "Run through the buffer and emphasize strings."
  5134. (let (rtn a)
  5135. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5136. (let* ((border (char-after (match-beginning 3)))
  5137. (bre (regexp-quote (char-to-string border))))
  5138. (when (and (not (= border (char-after (match-beginning 4))))
  5139. (not (string-match-p (concat bre ".*" bre)
  5140. (replace-regexp-in-string
  5141. "\n" " "
  5142. (substring (match-string 2) 1 -1)))))
  5143. (setq rtn t)
  5144. (setq a (assoc (match-string 3) org-emphasis-alist))
  5145. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5146. 'face
  5147. (nth 1 a))
  5148. (and (nth 2 a)
  5149. (org-remove-flyspell-overlays-in
  5150. (match-beginning 0) (match-end 0)))
  5151. (add-text-properties (match-beginning 2) (match-end 2)
  5152. '(font-lock-multiline t org-emphasis t))
  5153. (when org-hide-emphasis-markers
  5154. (add-text-properties (match-end 4) (match-beginning 5)
  5155. '(invisible org-link))
  5156. (add-text-properties (match-beginning 3) (match-end 3)
  5157. '(invisible org-link)))))
  5158. (goto-char (1+ (match-beginning 0))))
  5159. rtn))
  5160. (defun org-emphasize (&optional char)
  5161. "Insert or change an emphasis, i.e. a font like bold or italic.
  5162. If there is an active region, change that region to a new emphasis.
  5163. If there is no region, just insert the marker characters and position
  5164. the cursor between them.
  5165. CHAR should be the marker character. If it is a space, it means to
  5166. remove the emphasis of the selected region.
  5167. If CHAR is not given (for example in an interactive call) it will be
  5168. prompted for."
  5169. (interactive)
  5170. (let ((erc org-emphasis-regexp-components)
  5171. (string "") beg end move s)
  5172. (if (org-region-active-p)
  5173. (setq beg (region-beginning)
  5174. end (region-end)
  5175. string (buffer-substring beg end))
  5176. (setq move t))
  5177. (unless char
  5178. (message "Emphasis marker or tag: [%s]"
  5179. (mapconcat #'car org-emphasis-alist ""))
  5180. (setq char (read-char-exclusive)))
  5181. (if (equal char ?\s)
  5182. (setq s ""
  5183. move nil)
  5184. (unless (assoc (char-to-string char) org-emphasis-alist)
  5185. (user-error "No such emphasis marker: \"%c\"" char))
  5186. (setq s (char-to-string char)))
  5187. (while (and (> (length string) 1)
  5188. (equal (substring string 0 1) (substring string -1))
  5189. (assoc (substring string 0 1) org-emphasis-alist))
  5190. (setq string (substring string 1 -1)))
  5191. (setq string (concat s string s))
  5192. (when beg (delete-region beg end))
  5193. (unless (or (bolp)
  5194. (string-match (concat "[" (nth 0 erc) "\n]")
  5195. (char-to-string (char-before (point)))))
  5196. (insert " "))
  5197. (unless (or (eobp)
  5198. (string-match (concat "[" (nth 1 erc) "\n]")
  5199. (char-to-string (char-after (point)))))
  5200. (insert " ") (backward-char 1))
  5201. (insert string)
  5202. (and move (backward-char 1))))
  5203. (defconst org-nonsticky-props
  5204. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5205. (defsubst org-rear-nonsticky-at (pos)
  5206. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5207. (defun org-activate-plain-links (limit)
  5208. "Add link properties for plain links."
  5209. (when (and (re-search-forward org-plain-link-re limit t)
  5210. (not (org-in-src-block-p)))
  5211. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5212. 'face))
  5213. (link (match-string-no-properties 0))
  5214. (type (match-string-no-properties 1))
  5215. (path (match-string-no-properties 2))
  5216. (link-start (match-beginning 0))
  5217. (link-end (match-end 0))
  5218. (link-face (org-link-get-parameter type :face))
  5219. (help-echo (org-link-get-parameter type :help-echo))
  5220. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5221. (activate-func (org-link-get-parameter type :activate-func)))
  5222. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5223. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5224. (add-text-properties (match-beginning 0) (match-end 0)
  5225. (list
  5226. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5227. 'highlight)
  5228. 'face (cond
  5229. ;; A function that returns a face
  5230. ((functionp link-face)
  5231. (funcall link-face path))
  5232. ;; a face
  5233. ((facep link-face)
  5234. link-face)
  5235. ;; An anonymous face
  5236. ((consp link-face)
  5237. link-face)
  5238. ;; default
  5239. (t
  5240. 'org-link))
  5241. 'help-echo (cond
  5242. ((stringp help-echo)
  5243. help-echo)
  5244. ((functionp help-echo)
  5245. help-echo)
  5246. (t
  5247. (concat "LINK: "
  5248. (save-match-data
  5249. (org-link-unescape link)))))
  5250. 'htmlize-link (cond
  5251. ((functionp htmlize-link)
  5252. (funcall htmlize-link path))
  5253. (t
  5254. `(:uri ,link)))
  5255. 'keymap (or (org-link-get-parameter type :keymap)
  5256. org-mouse-map)
  5257. 'org-link-start (match-beginning 0)))
  5258. (org-rear-nonsticky-at (match-end 0))
  5259. (when activate-func
  5260. (funcall activate-func link-start link-end path nil))
  5261. t))))
  5262. (defun org-activate-code (limit)
  5263. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5264. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5265. (remove-text-properties (match-beginning 0) (match-end 0)
  5266. '(display t invisible t intangible t))
  5267. t))
  5268. (defcustom org-src-fontify-natively t
  5269. "When non-nil, fontify code in code blocks.
  5270. See also the `org-block' face."
  5271. :type 'boolean
  5272. :version "24.4"
  5273. :package-version '(Org . "8.3")
  5274. :group 'org-appearance
  5275. :group 'org-babel)
  5276. (defcustom org-allow-promoting-top-level-subtree nil
  5277. "When non-nil, allow promoting a top level subtree.
  5278. The leading star of the top level headline will be replaced
  5279. by a #."
  5280. :type 'boolean
  5281. :version "24.1"
  5282. :group 'org-appearance)
  5283. (defun org-fontify-meta-lines-and-blocks (limit)
  5284. (condition-case nil
  5285. (org-fontify-meta-lines-and-blocks-1 limit)
  5286. (error (message "org-mode fontification error in %S at %d"
  5287. (current-buffer)
  5288. (line-number-at-pos)))))
  5289. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5290. "Fontify #+ lines and blocks."
  5291. (let ((case-fold-search t))
  5292. (when (re-search-forward
  5293. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5294. limit t)
  5295. (let ((beg (match-beginning 0))
  5296. (block-start (match-end 0))
  5297. (block-end nil)
  5298. (lang (match-string 7))
  5299. (beg1 (line-beginning-position 2))
  5300. (dc1 (downcase (match-string 2)))
  5301. (dc3 (downcase (match-string 3)))
  5302. end end1 quoting block-type)
  5303. (cond
  5304. ((and (match-end 4) (equal dc3 "+begin"))
  5305. ;; Truly a block
  5306. (setq block-type (downcase (match-string 5))
  5307. quoting (member block-type org-protecting-blocks))
  5308. (when (re-search-forward
  5309. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5310. nil t) ;; on purpose, we look further than LIMIT
  5311. (setq end (min (point-max) (match-end 0))
  5312. end1 (min (point-max) (1- (match-beginning 0))))
  5313. (setq block-end (match-beginning 0))
  5314. (when quoting
  5315. (org-remove-flyspell-overlays-in beg1 end1)
  5316. (remove-text-properties beg end
  5317. '(display t invisible t intangible t)))
  5318. (add-text-properties
  5319. beg end '(font-lock-fontified t font-lock-multiline t))
  5320. (add-text-properties beg beg1 '(face org-meta-line))
  5321. (org-remove-flyspell-overlays-in beg beg1)
  5322. (add-text-properties ; For end_src
  5323. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5324. (org-remove-flyspell-overlays-in end1 end)
  5325. (cond
  5326. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5327. (org-src-font-lock-fontify-block lang block-start block-end)
  5328. (add-text-properties beg1 block-end '(src-block t)))
  5329. (quoting
  5330. (add-text-properties beg1 (min (point-max) (1+ end1))
  5331. (list 'face
  5332. (list :inherit
  5333. (let ((face-name
  5334. (intern (format "org-block-%s" lang))))
  5335. (append (and (facep face-name) (list face-name))
  5336. '(org-block))))))) ; end of source block
  5337. ((not org-fontify-quote-and-verse-blocks))
  5338. ((string= block-type "quote")
  5339. (add-face-text-property
  5340. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5341. ((string= block-type "verse")
  5342. (add-face-text-property
  5343. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5344. (add-text-properties beg beg1 '(face org-block-begin-line))
  5345. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5346. '(face org-block-end-line))
  5347. t))
  5348. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5349. (org-remove-flyspell-overlays-in
  5350. (match-beginning 0)
  5351. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5352. (add-text-properties
  5353. beg (match-end 3)
  5354. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5355. '(font-lock-fontified t invisible t)
  5356. '(font-lock-fontified t face org-document-info-keyword)))
  5357. (add-text-properties
  5358. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5359. (if (string-equal dc1 "+title:")
  5360. '(font-lock-fontified t face org-document-title)
  5361. '(font-lock-fontified t face org-document-info))))
  5362. ((string-prefix-p "+caption" dc1)
  5363. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5364. (remove-text-properties (match-beginning 0) (match-end 0)
  5365. '(display t invisible t intangible t))
  5366. ;; Handle short captions.
  5367. (save-excursion
  5368. (beginning-of-line)
  5369. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5370. (add-text-properties (line-beginning-position) (match-end 1)
  5371. '(font-lock-fontified t face org-meta-line))
  5372. (add-text-properties (match-end 0) (line-end-position)
  5373. '(font-lock-fontified t face org-block))
  5374. t)
  5375. ((member dc3 '(" " ""))
  5376. (org-remove-flyspell-overlays-in beg (match-end 0))
  5377. (add-text-properties
  5378. beg (match-end 0)
  5379. '(font-lock-fontified t face font-lock-comment-face)))
  5380. (t ;; just any other in-buffer setting, but not indented
  5381. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5382. (remove-text-properties (match-beginning 0) (match-end 0)
  5383. '(display t invisible t intangible t))
  5384. (add-text-properties beg (match-end 0)
  5385. '(font-lock-fontified t face org-meta-line))
  5386. t))))))
  5387. (defun org-fontify-drawers (limit)
  5388. "Fontify drawers."
  5389. (when (re-search-forward org-drawer-regexp limit t)
  5390. (add-text-properties
  5391. (match-beginning 0) (match-end 0)
  5392. '(font-lock-fontified t face org-special-keyword))
  5393. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5394. t))
  5395. (defun org-fontify-macros (limit)
  5396. "Fontify macros."
  5397. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5398. (add-text-properties
  5399. (match-beginning 0) (match-end 0)
  5400. '(font-lock-fontified t face org-macro))
  5401. (when org-hide-macro-markers
  5402. (add-text-properties (match-end 2) (match-beginning 2)
  5403. '(invisible t))
  5404. (add-text-properties (match-beginning 1) (match-end 1)
  5405. '(invisible t)))
  5406. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5407. t))
  5408. (defun org-activate-angle-links (limit)
  5409. "Add text properties for angle links."
  5410. (when (and (re-search-forward org-angle-link-re limit t)
  5411. (not (org-in-src-block-p)))
  5412. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5413. (add-text-properties (match-beginning 0) (match-end 0)
  5414. (list 'mouse-face 'highlight
  5415. 'keymap org-mouse-map
  5416. 'font-lock-multiline t))
  5417. (org-rear-nonsticky-at (match-end 0))
  5418. t))
  5419. (defun org-activate-footnote-links (limit)
  5420. "Add text properties for footnotes."
  5421. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5422. (when fn
  5423. (let* ((beg (nth 1 fn))
  5424. (end (nth 2 fn))
  5425. (label (car fn))
  5426. (referencep (/= (line-beginning-position) beg)))
  5427. (when (and referencep (nth 3 fn))
  5428. (save-excursion
  5429. (goto-char beg)
  5430. (search-forward (or label "fn:"))
  5431. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5432. (add-text-properties beg end
  5433. (list 'mouse-face 'highlight
  5434. 'keymap org-mouse-map
  5435. 'help-echo
  5436. (if referencep "Footnote reference"
  5437. "Footnote definition")
  5438. 'font-lock-fontified t
  5439. 'font-lock-multiline t
  5440. 'face 'org-footnote))))))
  5441. (defun org-activate-bracket-links (limit)
  5442. "Add text properties for bracketed links."
  5443. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5444. (not (org-in-src-block-p)))
  5445. (let* ((hl (save-match-data
  5446. (org-link-expand-abbrev (match-string-no-properties 1))))
  5447. (type (save-match-data
  5448. (and (string-match org-plain-link-re hl)
  5449. (match-string-no-properties 1 hl))))
  5450. (path (save-match-data
  5451. (and (string-match org-plain-link-re hl)
  5452. (match-string-no-properties 2 hl))))
  5453. (link-start (match-beginning 0))
  5454. (link-end (match-end 0))
  5455. (bracketp t)
  5456. (help-echo (org-link-get-parameter type :help-echo))
  5457. (help (cond
  5458. ((stringp help-echo)
  5459. help-echo)
  5460. ((functionp help-echo)
  5461. help-echo)
  5462. (t
  5463. (concat "LINK: "
  5464. (save-match-data
  5465. (org-link-unescape hl))))))
  5466. (link-face (org-link-get-parameter type :face))
  5467. (face (cond
  5468. ;; A function that returns a face
  5469. ((functionp link-face)
  5470. (funcall link-face path))
  5471. ;; a face
  5472. ((facep link-face)
  5473. link-face)
  5474. ;; An anonymous face
  5475. ((consp link-face)
  5476. link-face)
  5477. ;; default
  5478. (t
  5479. 'org-link)))
  5480. (keymap (or (org-link-get-parameter type :keymap)
  5481. org-mouse-map))
  5482. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5483. 'highlight))
  5484. (htmlize (org-link-get-parameter type :htmlize-link))
  5485. (htmlize-link (cond
  5486. ((functionp htmlize)
  5487. (funcall htmlize))
  5488. (t
  5489. `(:uri ,(format "%s:%s" type path)))))
  5490. (activate-func (org-link-get-parameter type :activate-func))
  5491. ;; invisible part
  5492. (ip (list 'invisible (or
  5493. (org-link-get-parameter type :display)
  5494. 'org-link)
  5495. 'face face
  5496. 'keymap keymap
  5497. 'mouse-face mouse-face
  5498. 'font-lock-multiline t
  5499. 'help-echo help
  5500. 'htmlize-link htmlize-link))
  5501. ;; visible part
  5502. (vp (list 'keymap keymap
  5503. 'face face
  5504. 'mouse-face mouse-face
  5505. 'font-lock-multiline t
  5506. 'help-echo help
  5507. 'htmlize-link htmlize-link)))
  5508. ;; We need to remove the invisible property here. Table narrowing
  5509. ;; may have made some of this invisible.
  5510. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5511. (remove-text-properties (match-beginning 0) (match-end 0)
  5512. '(invisible nil))
  5513. (if (match-end 3)
  5514. (progn
  5515. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5516. (org-rear-nonsticky-at (match-beginning 3))
  5517. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5518. (org-rear-nonsticky-at (match-end 3))
  5519. (add-text-properties (match-end 3) (match-end 0) ip)
  5520. (org-rear-nonsticky-at (match-end 0)))
  5521. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5522. (org-rear-nonsticky-at (match-beginning 1))
  5523. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5524. (org-rear-nonsticky-at (match-end 1))
  5525. (add-text-properties (match-end 1) (match-end 0) ip)
  5526. (org-rear-nonsticky-at (match-end 0)))
  5527. (when activate-func
  5528. (funcall activate-func link-start link-end path bracketp))
  5529. t)))
  5530. (defun org-activate-dates (limit)
  5531. "Add text properties for dates."
  5532. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5533. (not (equal (char-before (match-beginning 0)) 91)))
  5534. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5535. (add-text-properties (match-beginning 0) (match-end 0)
  5536. (list 'mouse-face 'highlight
  5537. 'keymap org-mouse-map))
  5538. (org-rear-nonsticky-at (match-end 0))
  5539. (when org-display-custom-times
  5540. (if (match-end 3)
  5541. (org-display-custom-time (match-beginning 3) (match-end 3))
  5542. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5543. t))
  5544. (defvar-local org-target-link-regexp nil
  5545. "Regular expression matching radio targets in plain text.")
  5546. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5547. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5548. border border border))
  5549. "Regular expression matching a link target.")
  5550. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5551. "Regular expression matching a radio target.")
  5552. (defconst org-any-target-regexp
  5553. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5554. "Regular expression matching any target.")
  5555. (defun org-activate-target-links (limit)
  5556. "Add text properties for target matches."
  5557. (when org-target-link-regexp
  5558. (let ((case-fold-search t))
  5559. (when (re-search-forward org-target-link-regexp limit t)
  5560. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5561. (add-text-properties (match-beginning 1) (match-end 1)
  5562. (list 'mouse-face 'highlight
  5563. 'keymap org-mouse-map
  5564. 'help-echo "Radio target link"
  5565. 'org-linked-text t))
  5566. (org-rear-nonsticky-at (match-end 1))
  5567. t))))
  5568. (defun org-update-radio-target-regexp ()
  5569. "Find all radio targets in this file and update the regular expression.
  5570. Also refresh fontification if needed."
  5571. (interactive)
  5572. (let ((old-regexp org-target-link-regexp)
  5573. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5574. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5575. (targets
  5576. (org-with-wide-buffer
  5577. (goto-char (point-min))
  5578. (let (rtn)
  5579. (while (re-search-forward org-radio-target-regexp nil t)
  5580. ;; Make sure point is really within the object.
  5581. (backward-char)
  5582. (let ((obj (org-element-context)))
  5583. (when (eq (org-element-type obj) 'radio-target)
  5584. (cl-pushnew (org-element-property :value obj) rtn
  5585. :test #'equal))))
  5586. rtn))))
  5587. (setq org-target-link-regexp
  5588. (and targets
  5589. (concat before-re
  5590. (mapconcat
  5591. (lambda (x)
  5592. (replace-regexp-in-string
  5593. " +" "\\s-+" (regexp-quote x) t t))
  5594. targets
  5595. "\\|")
  5596. after-re)))
  5597. (unless (equal old-regexp org-target-link-regexp)
  5598. ;; Clean-up cache.
  5599. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5600. ((not org-target-link-regexp) old-regexp)
  5601. (t
  5602. (concat before-re
  5603. (mapconcat
  5604. (lambda (re)
  5605. (substring re (length before-re)
  5606. (- (length after-re))))
  5607. (list old-regexp org-target-link-regexp)
  5608. "\\|")
  5609. after-re)))))
  5610. (org-with-wide-buffer
  5611. (goto-char (point-min))
  5612. (while (re-search-forward regexp nil t)
  5613. (org-element-cache-refresh (match-beginning 1)))))
  5614. ;; Re fontify buffer.
  5615. (when (memq 'radio org-highlight-links)
  5616. (org-restart-font-lock)))))
  5617. (defun org-hide-wide-columns (limit)
  5618. (let (s e)
  5619. (setq s (text-property-any (point) (or limit (point-max))
  5620. 'org-cwidth t))
  5621. (when s
  5622. (setq e (next-single-property-change s 'org-cwidth))
  5623. (add-text-properties s e '(invisible org-cwidth))
  5624. (goto-char e)
  5625. t)))
  5626. (defvar org-latex-and-related-regexp nil
  5627. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5628. (defun org-compute-latex-and-related-regexp ()
  5629. "Compute regular expression for LaTeX, entities and sub/superscript.
  5630. Result depends on variable `org-highlight-latex-and-related'."
  5631. (setq-local
  5632. org-latex-and-related-regexp
  5633. (let* ((re-sub
  5634. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5635. ((eq org-use-sub-superscripts '{})
  5636. (list org-match-substring-with-braces-regexp))
  5637. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5638. (re-latex
  5639. (when (memq 'latex org-highlight-latex-and-related)
  5640. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5641. (delq nil
  5642. (mapcar (lambda (x)
  5643. (and (member (car x) matchers) (nth 1 x)))
  5644. org-latex-regexps)))))
  5645. (re-entities
  5646. (when (memq 'entities org-highlight-latex-and-related)
  5647. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5648. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5649. (defun org-do-latex-and-related (limit)
  5650. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5651. LIMIT bounds the search for syntax to highlight. Stop at first
  5652. highlighted object, if any. Return t if some highlighting was
  5653. done, nil otherwise."
  5654. (when (org-string-nw-p org-latex-and-related-regexp)
  5655. (catch 'found
  5656. (while (re-search-forward org-latex-and-related-regexp limit t)
  5657. (unless
  5658. (cl-some
  5659. (lambda (f)
  5660. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5661. (save-excursion
  5662. (goto-char (1+ (match-beginning 0)))
  5663. (face-at-point nil t)))
  5664. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5665. '(?_ ?^))
  5666. 1
  5667. 0)))
  5668. (font-lock-prepend-text-property
  5669. (+ offset (match-beginning 0)) (match-end 0)
  5670. 'face 'org-latex-and-related)
  5671. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5672. '(font-lock-multiline t)))
  5673. (throw 'found t)))
  5674. nil)))
  5675. (defun org-restart-font-lock ()
  5676. "Restart `font-lock-mode', to force refontification."
  5677. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5678. (font-lock-mode -1)
  5679. (font-lock-mode 1)))
  5680. (defun org-activate-tags (limit)
  5681. (when (re-search-forward
  5682. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5683. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5684. (add-text-properties (match-beginning 1) (match-end 1)
  5685. (list 'mouse-face 'highlight
  5686. 'keymap org-mouse-map))
  5687. (org-rear-nonsticky-at (match-end 1))
  5688. t))
  5689. (defun org-outline-level ()
  5690. "Compute the outline level of the heading at point.
  5691. If this is called at a normal headline, the level is the number
  5692. of stars. Use `org-reduced-level' to remove the effect of
  5693. `org-odd-levels'. Unlike to `org-current-level', this function
  5694. takes into consideration inlinetasks."
  5695. (org-with-wide-buffer
  5696. (end-of-line)
  5697. (if (re-search-backward org-outline-regexp-bol nil t)
  5698. (1- (- (match-end 0) (match-beginning 0)))
  5699. 0)))
  5700. (defvar org-font-lock-keywords nil)
  5701. (defsubst org-re-property (property &optional literal allow-null value)
  5702. "Return a regexp matching a PROPERTY line.
  5703. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5704. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5705. non-nil, match properties even without a value.
  5706. Match group 3 is set to the value when it exists. If there is no
  5707. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5708. With optional argument VALUE, match only property lines with
  5709. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5710. unless LITERAL is non-nil."
  5711. (concat
  5712. "^\\(?4:[ \t]*\\)"
  5713. (format "\\(?1::\\(?2:%s\\):\\)"
  5714. (if literal property (regexp-quote property)))
  5715. (cond (value
  5716. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5717. (if literal value (regexp-quote value))))
  5718. (allow-null
  5719. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5720. (t
  5721. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5722. (defconst org-property-re
  5723. (org-re-property "\\S-+" 'literal t)
  5724. "Regular expression matching a property line.
  5725. There are four matching groups:
  5726. 1: :PROPKEY: including the leading and trailing colon,
  5727. 2: PROPKEY without the leading and trailing colon,
  5728. 3: PROPVAL without leading or trailing spaces,
  5729. 4: the indentation of the current line,
  5730. 5: trailing whitespace.")
  5731. (defvar org-font-lock-hook nil
  5732. "Functions to be called for special font lock stuff.")
  5733. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5734. (defvar org-font-lock-set-keywords-hook nil
  5735. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5736. This is called after `org-font-lock-extra-keywords' is defined, but before
  5737. it is installed to be used by font lock. This can be useful if something
  5738. needs to be inserted at a specific position in the font-lock sequence.")
  5739. (defun org-font-lock-hook (limit)
  5740. "Run `org-font-lock-hook' within LIMIT."
  5741. (run-hook-with-args 'org-font-lock-hook limit))
  5742. (defun org-set-font-lock-defaults ()
  5743. "Set font lock defaults for the current buffer."
  5744. (let* ((em org-fontify-emphasized-text)
  5745. (lk org-highlight-links)
  5746. (org-font-lock-extra-keywords
  5747. (list
  5748. ;; Call the hook
  5749. '(org-font-lock-hook)
  5750. ;; Headlines
  5751. `(,(if org-fontify-whole-heading-line
  5752. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5753. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5754. (1 (org-get-level-face 1))
  5755. (2 (org-get-level-face 2))
  5756. (3 (org-get-level-face 3)))
  5757. ;; Table lines
  5758. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5759. (1 'org-table t))
  5760. ;; Table internals
  5761. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5762. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5763. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5764. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5765. ;; Drawers
  5766. '(org-fontify-drawers)
  5767. ;; Properties
  5768. (list org-property-re
  5769. '(1 'org-special-keyword t)
  5770. '(3 'org-property-value t))
  5771. ;; Links
  5772. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5773. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5774. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5775. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5776. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5777. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5778. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5779. ;; Targets.
  5780. (list org-any-target-regexp '(0 'org-target t))
  5781. ;; Diary sexps.
  5782. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5783. ;; Macro
  5784. '(org-fontify-macros)
  5785. '(org-hide-wide-columns (0 nil append))
  5786. ;; TODO keyword
  5787. (list (format org-heading-keyword-regexp-format
  5788. org-todo-regexp)
  5789. '(2 (org-get-todo-face 2) t))
  5790. ;; DONE
  5791. (if org-fontify-done-headline
  5792. (list (format org-heading-keyword-regexp-format
  5793. (concat
  5794. "\\(?:"
  5795. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5796. "\\)"))
  5797. '(2 'org-headline-done t))
  5798. nil)
  5799. ;; Priorities
  5800. '(org-font-lock-add-priority-faces)
  5801. ;; Tags
  5802. '(org-font-lock-add-tag-faces)
  5803. ;; Tags groups
  5804. (when (and org-group-tags org-tag-groups-alist)
  5805. (list (concat org-outline-regexp-bol ".+\\(:"
  5806. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5807. ":\\).*$")
  5808. '(1 'org-tag-group prepend)))
  5809. ;; Special keywords
  5810. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5811. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5812. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5813. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5814. ;; Emphasis
  5815. (when em '(org-do-emphasis-faces))
  5816. ;; Checkboxes
  5817. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5818. 1 'org-checkbox prepend)
  5819. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5820. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5821. (0 (org-get-checkbox-statistics-face) t)))
  5822. ;; Description list items
  5823. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5824. 1 'org-list-dt prepend)
  5825. ;; ARCHIVEd headings
  5826. (list (concat
  5827. org-outline-regexp-bol
  5828. "\\(.*:" org-archive-tag ":.*\\)")
  5829. '(1 'org-archived prepend))
  5830. ;; Specials
  5831. '(org-do-latex-and-related)
  5832. '(org-fontify-entities)
  5833. '(org-raise-scripts)
  5834. ;; Code
  5835. '(org-activate-code (1 'org-code t))
  5836. ;; COMMENT
  5837. (list (format
  5838. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5839. org-todo-regexp
  5840. org-comment-string)
  5841. '(9 'org-special-keyword t))
  5842. ;; Blocks and meta lines
  5843. '(org-fontify-meta-lines-and-blocks))))
  5844. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5845. (run-hooks 'org-font-lock-set-keywords-hook)
  5846. ;; Now set the full font-lock-keywords
  5847. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5848. (setq-local font-lock-defaults
  5849. '(org-font-lock-keywords t nil nil backward-paragraph))
  5850. (kill-local-variable 'font-lock-keywords)
  5851. nil))
  5852. (defun org-toggle-pretty-entities ()
  5853. "Toggle the composition display of entities as UTF8 characters."
  5854. (interactive)
  5855. (setq-local org-pretty-entities (not org-pretty-entities))
  5856. (org-restart-font-lock)
  5857. (if org-pretty-entities
  5858. (message "Entities are now displayed as UTF8 characters")
  5859. (save-restriction
  5860. (widen)
  5861. (decompose-region (point-min) (point-max))
  5862. (message "Entities are now displayed as plain text"))))
  5863. (defvar-local org-custom-properties-overlays nil
  5864. "List of overlays used for custom properties.")
  5865. (defun org-toggle-custom-properties-visibility ()
  5866. "Display or hide properties in `org-custom-properties'."
  5867. (interactive)
  5868. (if org-custom-properties-overlays
  5869. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5870. (setq org-custom-properties-overlays nil))
  5871. (when org-custom-properties
  5872. (org-with-wide-buffer
  5873. (goto-char (point-min))
  5874. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5875. (while (re-search-forward regexp nil t)
  5876. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5877. (when (and end (< (point) end))
  5878. ;; Hide first custom property in current drawer.
  5879. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5880. (overlay-put o 'invisible t)
  5881. (overlay-put o 'org-custom-property t)
  5882. (push o org-custom-properties-overlays))
  5883. ;; Hide additional custom properties in the same drawer.
  5884. (while (re-search-forward regexp end t)
  5885. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5886. (overlay-put o 'invisible t)
  5887. (overlay-put o 'org-custom-property t)
  5888. (push o org-custom-properties-overlays)))))
  5889. ;; Each entry is limited to a single property drawer.
  5890. (outline-next-heading)))))))
  5891. (defun org-fontify-entities (limit)
  5892. "Find an entity to fontify."
  5893. (let (ee)
  5894. (when org-pretty-entities
  5895. (catch 'match
  5896. ;; "\_ "-family is left out on purpose. Only the first one,
  5897. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5898. ;; confusing when adding a second white space character.
  5899. (while (re-search-forward
  5900. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5901. limit t)
  5902. (when (and (not (org-at-comment-p))
  5903. (setq ee (org-entity-get (match-string 1)))
  5904. (= (length (nth 6 ee)) 1))
  5905. (let* ((end (if (equal (match-string 2) "{}")
  5906. (match-end 2)
  5907. (match-end 1))))
  5908. (add-text-properties
  5909. (match-beginning 0) end
  5910. (list 'font-lock-fontified t))
  5911. (compose-region (match-beginning 0) end
  5912. (nth 6 ee) nil)
  5913. (backward-char 1)
  5914. (throw 'match t))))
  5915. nil))))
  5916. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5917. "Fontify string S like in Org mode."
  5918. (with-temp-buffer
  5919. (insert s)
  5920. (let ((org-odd-levels-only odd-levels))
  5921. (org-mode)
  5922. (org-font-lock-ensure)
  5923. (buffer-string))))
  5924. (defvar org-m nil)
  5925. (defvar org-l nil)
  5926. (defvar org-f nil)
  5927. (defun org-get-level-face (n)
  5928. "Get the right face for match N in font-lock matching of headlines."
  5929. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5930. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5931. (if org-cycle-level-faces
  5932. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5933. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5934. (cond
  5935. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5936. ((eq n 2) org-f)
  5937. (t (unless org-level-color-stars-only org-f))))
  5938. (defun org-face-from-face-or-color (context inherit face-or-color)
  5939. "Create a face list that inherits INHERIT, but sets the foreground color.
  5940. When FACE-OR-COLOR is not a string, just return it."
  5941. (if (stringp face-or-color)
  5942. (list :inherit inherit
  5943. (cdr (assoc context org-faces-easy-properties))
  5944. face-or-color)
  5945. face-or-color))
  5946. (defun org-get-todo-face (kwd)
  5947. "Get the right face for a TODO keyword KWD.
  5948. If KWD is a number, get the corresponding match group."
  5949. (when (numberp kwd) (setq kwd (match-string kwd)))
  5950. (or (org-face-from-face-or-color
  5951. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5952. (and (member kwd org-done-keywords) 'org-done)
  5953. 'org-todo))
  5954. (defun org-get-priority-face (priority)
  5955. "Get the right face for PRIORITY.
  5956. PRIORITY is a character."
  5957. (or (org-face-from-face-or-color
  5958. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5959. 'org-priority))
  5960. (defun org-get-tag-face (tag)
  5961. "Get the right face for TAG.
  5962. If TAG is a number, get the corresponding match group."
  5963. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5964. (or (org-face-from-face-or-color
  5965. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5966. 'org-tag)))
  5967. (defun org-font-lock-add-priority-faces (limit)
  5968. "Add the special priority faces."
  5969. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5970. (add-text-properties
  5971. (match-beginning 1) (match-end 1)
  5972. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5973. 'font-lock-fontified t))))
  5974. (defun org-font-lock-add-tag-faces (limit)
  5975. "Add the special tag faces."
  5976. (when (and org-tag-faces org-tags-special-faces-re)
  5977. (while (re-search-forward org-tags-special-faces-re limit t)
  5978. (add-text-properties (match-beginning 1) (match-end 1)
  5979. (list 'face (org-get-tag-face 1)
  5980. 'font-lock-fontified t))
  5981. (backward-char 1))))
  5982. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5983. "Remove fontification and activation overlays from links."
  5984. (font-lock-default-unfontify-region beg end)
  5985. (let* ((buffer-undo-list t)
  5986. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5987. (inhibit-modification-hooks t)
  5988. deactivate-mark buffer-file-name buffer-file-truename)
  5989. (decompose-region beg end)
  5990. (remove-text-properties beg end
  5991. '(mouse-face t keymap t org-linked-text t
  5992. invisible t intangible t
  5993. org-emphasis t))
  5994. (org-remove-font-lock-display-properties beg end)))
  5995. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5996. ((raise 0.3) (height 0.7))
  5997. ((raise -0.5))
  5998. ((raise 0.5)))
  5999. "Display properties for showing superscripts and subscripts.")
  6000. (defun org-remove-font-lock-display-properties (beg end)
  6001. "Remove specific display properties that have been added by font lock.
  6002. The will remove the raise properties that are used to show superscripts
  6003. and subscripts."
  6004. (let (next prop)
  6005. (while (< beg end)
  6006. (setq next (next-single-property-change beg 'display nil end)
  6007. prop (get-text-property beg 'display))
  6008. (when (member prop org-script-display)
  6009. (put-text-property beg next 'display nil))
  6010. (setq beg next))))
  6011. (defun org-raise-scripts (limit)
  6012. "Add raise properties to sub/superscripts."
  6013. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  6014. (re-search-forward
  6015. (if (eq org-use-sub-superscripts t)
  6016. org-match-substring-regexp
  6017. org-match-substring-with-braces-regexp)
  6018. limit t))
  6019. (let* ((pos (point)) table-p comment-p
  6020. (mpos (match-beginning 3))
  6021. (emph-p (get-text-property mpos 'org-emphasis))
  6022. (link-p (get-text-property mpos 'mouse-face))
  6023. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  6024. (goto-char (point-at-bol))
  6025. (setq table-p (looking-at-p org-table-dataline-regexp)
  6026. comment-p (looking-at-p "^[ \t]*#[ +]"))
  6027. (goto-char pos)
  6028. ;; Handle a_b^c
  6029. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  6030. (unless (or comment-p emph-p link-p keyw-p)
  6031. (put-text-property (match-beginning 3) (match-end 0)
  6032. 'display
  6033. (if (equal (char-after (match-beginning 2)) ?^)
  6034. (nth (if table-p 3 1) org-script-display)
  6035. (nth (if table-p 2 0) org-script-display)))
  6036. (add-text-properties (match-beginning 2) (match-end 2)
  6037. (list 'invisible t
  6038. 'org-dwidth t 'org-dwidth-n 1))
  6039. (if (and (eq (char-after (match-beginning 3)) ?{)
  6040. (eq (char-before (match-end 3)) ?}))
  6041. (progn
  6042. (add-text-properties
  6043. (match-beginning 3) (1+ (match-beginning 3))
  6044. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6045. (add-text-properties
  6046. (1- (match-end 3)) (match-end 3)
  6047. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6048. t)))
  6049. ;;;; Visibility cycling, including org-goto and indirect buffer
  6050. ;;; Cycling
  6051. (defvar-local org-cycle-global-status nil)
  6052. (put 'org-cycle-global-status 'org-state t)
  6053. (defvar-local org-cycle-subtree-status nil)
  6054. (put 'org-cycle-subtree-status 'org-state t)
  6055. (defvar org-inlinetask-min-level)
  6056. (defun org-unlogged-message (&rest args)
  6057. "Display a message, but avoid logging it in the *Messages* buffer."
  6058. (let ((message-log-max nil))
  6059. (apply 'message args)))
  6060. ;;;###autoload
  6061. (defun org-cycle (&optional arg)
  6062. "TAB-action and visibility cycling for Org mode.
  6063. This is the command invoked in Org mode by the `TAB' key. Its main
  6064. purpose is outline visibility cycling, but it also invokes other actions
  6065. in special contexts.
  6066. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6067. the entire
  6068. buffer through 3 states (global cycling)
  6069. 1. OVERVIEW: Show only top-level headlines.
  6070. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6071. 3. SHOW ALL: Show everything.
  6072. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6073. switch to the startup visibility,
  6074. determined by the variable `org-startup-folded', and by any VISIBILITY
  6075. properties in the buffer.
  6076. With a `\\[universal-argument] \\[universal-argument] \
  6077. \\[universal-argument]' prefix argument, show the entire buffer, including
  6078. any drawers.
  6079. When inside a table, re-align the table and move to the next field.
  6080. When point is at the beginning of a headline, rotate the subtree started
  6081. by this line through 3 different states (local cycling)
  6082. 1. FOLDED: Only the main headline is shown.
  6083. 2. CHILDREN: The main headline and the direct children are shown.
  6084. From this state, you can move to one of the children
  6085. and zoom in further.
  6086. 3. SUBTREE: Show the entire subtree, including body text.
  6087. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6088. When point is at the beginning of an empty headline and the variable
  6089. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6090. of the headline by demoting and promoting it to likely levels. This
  6091. speeds up creation document structure by pressing `TAB' once or several
  6092. times right after creating a new headline.
  6093. When there is a numeric prefix, go up to a heading with level ARG, do
  6094. a `show-subtree' and return to the previous cursor position. If ARG
  6095. is negative, go up that many levels.
  6096. When point is not at the beginning of a headline, execute the global
  6097. binding for `TAB', which is re-indenting the line. See the option
  6098. `org-cycle-emulate-tab' for details.
  6099. As a special case, if point is at the beginning of the buffer and there is
  6100. no headline in line 1, this function will act as if called with prefix arg
  6101. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6102. prefix arg, but only
  6103. if the variable `org-cycle-global-at-bob' is t."
  6104. (interactive "P")
  6105. (org-load-modules-maybe)
  6106. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6107. (and org-cycle-level-after-item/entry-creation
  6108. (or (org-cycle-level)
  6109. (org-cycle-item-indentation))))
  6110. (let* ((limit-level
  6111. (or org-cycle-max-level
  6112. (and (boundp 'org-inlinetask-min-level)
  6113. org-inlinetask-min-level
  6114. (1- org-inlinetask-min-level))))
  6115. (nstars (and limit-level
  6116. (if org-odd-levels-only
  6117. (and limit-level (1- (* limit-level 2)))
  6118. limit-level)))
  6119. (org-outline-regexp
  6120. (if (not (derived-mode-p 'org-mode))
  6121. outline-regexp
  6122. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6123. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6124. (not (looking-at org-outline-regexp))))
  6125. (org-cycle-hook
  6126. (if bob-special
  6127. (delq 'org-optimize-window-after-visibility-change
  6128. (copy-sequence org-cycle-hook))
  6129. org-cycle-hook))
  6130. (pos (point)))
  6131. (cond
  6132. ((equal arg '(16))
  6133. (setq last-command 'dummy)
  6134. (org-set-startup-visibility)
  6135. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6136. ((equal arg '(64))
  6137. (outline-show-all)
  6138. (org-unlogged-message "Entire buffer visible, including drawers"))
  6139. ((equal arg '(4)) (org-cycle-internal-global))
  6140. ;; Try hiding block at point.
  6141. ((org-hide-block-toggle-maybe))
  6142. ;; Try cdlatex TAB completion
  6143. ((org-try-cdlatex-tab))
  6144. ;; Table: enter it or move to the next field.
  6145. ((org-at-table-p 'any)
  6146. (if (org-at-table.el-p)
  6147. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6148. Use `\\[org-edit-special]' to edit table.el tables"))
  6149. (if arg (org-table-edit-field t)
  6150. (org-table-justify-field-maybe)
  6151. (call-interactively 'org-table-next-field))))
  6152. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6153. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6154. (bob-special (org-cycle-internal-global))
  6155. ;; Drawers: delegate to `org-flag-drawer'.
  6156. ((save-excursion
  6157. (beginning-of-line 1)
  6158. (looking-at org-drawer-regexp))
  6159. (org-flag-drawer ; toggle block visibility
  6160. (not (get-char-property (match-end 0) 'invisible))))
  6161. ;; Show-subtree, ARG levels up from here.
  6162. ((integerp arg)
  6163. (save-excursion
  6164. (org-back-to-heading)
  6165. (outline-up-heading (if (< arg 0) (- arg)
  6166. (- (funcall outline-level) arg)))
  6167. (org-show-subtree)))
  6168. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6169. ((and (featurep 'org-inlinetask)
  6170. (org-inlinetask-at-task-p)
  6171. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6172. (org-inlinetask-toggle-visibility))
  6173. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6174. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6175. (save-excursion (move-beginning-of-line 1)
  6176. (looking-at org-outline-regexp)))
  6177. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6178. (org-cycle-internal-local))
  6179. ;; From there: TAB emulation and template completion.
  6180. (buffer-read-only (org-back-to-heading))
  6181. ((run-hook-with-args-until-success
  6182. 'org-tab-after-check-for-cycling-hook))
  6183. ((org-try-structure-completion))
  6184. ((run-hook-with-args-until-success
  6185. 'org-tab-before-tab-emulation-hook))
  6186. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6187. (or (not (bolp))
  6188. (not (looking-at org-outline-regexp))))
  6189. (call-interactively (global-key-binding "\t")))
  6190. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6191. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6192. (or (and (eq org-cycle-emulate-tab 'white)
  6193. (= (match-end 0) (point-at-eol)))
  6194. (and (eq org-cycle-emulate-tab 'whitestart)
  6195. (>= (match-end 0) pos))))
  6196. t
  6197. (eq org-cycle-emulate-tab t))
  6198. (call-interactively (global-key-binding "\t")))
  6199. (t (save-excursion
  6200. (org-back-to-heading)
  6201. (org-cycle)))))))
  6202. (defun org-cycle-internal-global ()
  6203. "Do the global cycling action."
  6204. ;; Hack to avoid display of messages for .org attachments in Gnus
  6205. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6206. (cond
  6207. ((and (eq last-command this-command)
  6208. (eq org-cycle-global-status 'overview))
  6209. ;; We just created the overview - now do table of contents
  6210. ;; This can be slow in very large buffers, so indicate action
  6211. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6212. (unless ga (org-unlogged-message "CONTENTS..."))
  6213. (org-content)
  6214. (unless ga (org-unlogged-message "CONTENTS...done"))
  6215. (setq org-cycle-global-status 'contents)
  6216. (run-hook-with-args 'org-cycle-hook 'contents))
  6217. ((and (eq last-command this-command)
  6218. (eq org-cycle-global-status 'contents))
  6219. ;; We just showed the table of contents - now show everything
  6220. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6221. (outline-show-all)
  6222. (unless ga (org-unlogged-message "SHOW ALL"))
  6223. (setq org-cycle-global-status 'all)
  6224. (run-hook-with-args 'org-cycle-hook 'all))
  6225. (t
  6226. ;; Default action: go to overview
  6227. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6228. (org-overview)
  6229. (unless ga (org-unlogged-message "OVERVIEW"))
  6230. (setq org-cycle-global-status 'overview)
  6231. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6232. (defvar org-called-with-limited-levels nil
  6233. "Non-nil when `org-with-limited-levels' is currently active.")
  6234. (defun org-cycle-internal-local ()
  6235. "Do the local cycling action."
  6236. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6237. ;; First, determine end of headline (EOH), end of subtree or item
  6238. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6239. (save-excursion
  6240. (if (org-at-item-p)
  6241. (progn
  6242. (beginning-of-line)
  6243. (setq struct (org-list-struct))
  6244. (setq eoh (point-at-eol))
  6245. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6246. (setq has-children (org-list-has-child-p (point) struct)))
  6247. (org-back-to-heading)
  6248. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6249. (setq eos (save-excursion (org-end-of-subtree t t)
  6250. (when (bolp) (backward-char)) (point)))
  6251. (setq has-children
  6252. (or (save-excursion
  6253. (let ((level (funcall outline-level)))
  6254. (outline-next-heading)
  6255. (and (org-at-heading-p t)
  6256. (> (funcall outline-level) level))))
  6257. (save-excursion
  6258. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6259. ;; Determine end invisible part of buffer (EOL)
  6260. (beginning-of-line 2)
  6261. (while (and (not (eobp)) ;This is like `next-line'.
  6262. (get-char-property (1- (point)) 'invisible))
  6263. (goto-char (next-single-char-property-change (point) 'invisible))
  6264. (and (eolp) (beginning-of-line 2)))
  6265. (setq eol (point)))
  6266. ;; Find out what to do next and set `this-command'
  6267. (cond
  6268. ((= eos eoh)
  6269. ;; Nothing is hidden behind this heading
  6270. (unless (org-before-first-heading-p)
  6271. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6272. (org-unlogged-message "EMPTY ENTRY")
  6273. (setq org-cycle-subtree-status nil)
  6274. (save-excursion
  6275. (goto-char eos)
  6276. (outline-next-heading)
  6277. (when (outline-invisible-p) (org-flag-heading nil))))
  6278. ((and (or (>= eol eos)
  6279. (not (string-match "\\S-" (buffer-substring eol eos))))
  6280. (or has-children
  6281. (not (setq children-skipped
  6282. org-cycle-skip-children-state-if-no-children))))
  6283. ;; Entire subtree is hidden in one line: children view
  6284. (unless (org-before-first-heading-p)
  6285. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6286. (if (org-at-item-p)
  6287. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6288. (org-show-entry)
  6289. (org-with-limited-levels (org-show-children))
  6290. ;; FIXME: This slows down the func way too much.
  6291. ;; How keep drawers hidden in subtree anyway?
  6292. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6293. ;; (org-cycle-hide-drawers 'subtree))
  6294. ;; Fold every list in subtree to top-level items.
  6295. (when (eq org-cycle-include-plain-lists 'integrate)
  6296. (save-excursion
  6297. (org-back-to-heading)
  6298. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6299. (beginning-of-line 1)
  6300. (let* ((struct (org-list-struct))
  6301. (prevs (org-list-prevs-alist struct))
  6302. (end (org-list-get-bottom-point struct)))
  6303. (dolist (e (org-list-get-all-items (point) struct prevs))
  6304. (org-list-set-item-visibility e struct 'folded))
  6305. (goto-char (if (< end eos) end eos)))))))
  6306. (org-unlogged-message "CHILDREN")
  6307. (save-excursion
  6308. (goto-char eos)
  6309. (outline-next-heading)
  6310. (when (outline-invisible-p) (org-flag-heading nil)))
  6311. (setq org-cycle-subtree-status 'children)
  6312. (unless (org-before-first-heading-p)
  6313. (run-hook-with-args 'org-cycle-hook 'children)))
  6314. ((or children-skipped
  6315. (and (eq last-command this-command)
  6316. (eq org-cycle-subtree-status 'children)))
  6317. ;; We just showed the children, or no children are there,
  6318. ;; now show everything.
  6319. (unless (org-before-first-heading-p)
  6320. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6321. (outline-flag-region eoh eos nil)
  6322. (org-unlogged-message
  6323. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6324. (setq org-cycle-subtree-status 'subtree)
  6325. (unless (org-before-first-heading-p)
  6326. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6327. (t
  6328. ;; Default action: hide the subtree.
  6329. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6330. (outline-flag-region eoh eos t)
  6331. (org-unlogged-message "FOLDED")
  6332. (setq org-cycle-subtree-status 'folded)
  6333. (unless (org-before-first-heading-p)
  6334. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6335. ;;;###autoload
  6336. (defun org-global-cycle (&optional arg)
  6337. "Cycle the global visibility. For details see `org-cycle'.
  6338. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6339. With a numeric prefix, show all headlines up to that level."
  6340. (interactive "P")
  6341. (let ((org-cycle-include-plain-lists
  6342. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6343. (cond
  6344. ((integerp arg)
  6345. (outline-show-all)
  6346. (outline-hide-sublevels arg)
  6347. (setq org-cycle-global-status 'contents))
  6348. ((equal arg '(4))
  6349. (org-set-startup-visibility)
  6350. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6351. (t
  6352. (org-cycle '(4))))))
  6353. (defun org-set-startup-visibility ()
  6354. "Set the visibility required by startup options and properties."
  6355. (cond
  6356. ((eq org-startup-folded t)
  6357. (org-overview))
  6358. ((eq org-startup-folded 'content)
  6359. (org-content))
  6360. ((or (eq org-startup-folded 'showeverything)
  6361. (eq org-startup-folded nil))
  6362. (outline-show-all)))
  6363. (unless (eq org-startup-folded 'showeverything)
  6364. (when org-hide-block-startup (org-hide-block-all))
  6365. (org-set-visibility-according-to-property 'no-cleanup)
  6366. (org-cycle-hide-archived-subtrees 'all)
  6367. (org-cycle-hide-drawers 'all)
  6368. (org-cycle-show-empty-lines t)))
  6369. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6370. "Switch subtree visibilities according to :VISIBILITY: property."
  6371. (interactive)
  6372. (org-with-wide-buffer
  6373. (goto-char (point-min))
  6374. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6375. (if (not (org-at-property-p)) (outline-next-heading)
  6376. (let ((state (match-string 3)))
  6377. (save-excursion
  6378. (org-back-to-heading t)
  6379. (outline-hide-subtree)
  6380. (org-reveal)
  6381. (cond
  6382. ((equal state "folded")
  6383. (outline-hide-subtree))
  6384. ((equal state "children")
  6385. (org-show-hidden-entry)
  6386. (org-show-children))
  6387. ((equal state "content")
  6388. (save-excursion
  6389. (save-restriction
  6390. (org-narrow-to-subtree)
  6391. (org-content))))
  6392. ((member state '("all" "showall"))
  6393. (outline-show-subtree)))))))
  6394. (unless no-cleanup
  6395. (org-cycle-hide-archived-subtrees 'all)
  6396. (org-cycle-hide-drawers 'all)
  6397. (org-cycle-show-empty-lines 'all))))
  6398. ;; This function uses outline-regexp instead of the more fundamental
  6399. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6400. ;; buffers, where outline-regexp is needed.
  6401. (defun org-overview ()
  6402. "Switch to overview mode, showing only top-level headlines.
  6403. This shows all headlines with a level equal or greater than the level
  6404. of the first headline in the buffer. This is important, because if the
  6405. first headline is not level one, then (hide-sublevels 1) gives confusing
  6406. results."
  6407. (interactive)
  6408. (save-excursion
  6409. (let ((level
  6410. (save-excursion
  6411. (goto-char (point-min))
  6412. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6413. (goto-char (match-beginning 0))
  6414. (funcall outline-level)))))
  6415. (and level (outline-hide-sublevels level)))))
  6416. (defun org-content (&optional arg)
  6417. "Show all headlines in the buffer, like a table of contents.
  6418. With numerical argument N, show content up to level N."
  6419. (interactive "P")
  6420. (org-overview)
  6421. (save-excursion
  6422. ;; Visit all headings and show their offspring
  6423. (and (integerp arg) (org-overview))
  6424. (goto-char (point-max))
  6425. (catch 'exit
  6426. (while (and (progn (condition-case nil
  6427. (outline-previous-visible-heading 1)
  6428. (error (goto-char (point-min))))
  6429. t)
  6430. (looking-at org-outline-regexp))
  6431. (if (integerp arg)
  6432. (org-show-children (1- arg))
  6433. (outline-show-branches))
  6434. (when (bobp) (throw 'exit nil))))))
  6435. (defun org-optimize-window-after-visibility-change (state)
  6436. "Adjust the window after a change in outline visibility.
  6437. This function is the default value of the hook `org-cycle-hook'."
  6438. (when (get-buffer-window (current-buffer))
  6439. (cond
  6440. ((eq state 'content) nil)
  6441. ((eq state 'all) nil)
  6442. ((eq state 'folded) nil)
  6443. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6444. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6445. (defun org-remove-empty-overlays-at (pos)
  6446. "Remove outline overlays that do not contain non-white stuff."
  6447. (dolist (o (overlays-at pos))
  6448. (and (eq 'outline (overlay-get o 'invisible))
  6449. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6450. (overlay-end o))))
  6451. (delete-overlay o))))
  6452. (defun org-clean-visibility-after-subtree-move ()
  6453. "Fix visibility issues after moving a subtree."
  6454. ;; First, find a reasonable region to look at:
  6455. ;; Start two siblings above, end three below
  6456. (let* ((beg (save-excursion
  6457. (and (org-get-last-sibling)
  6458. (org-get-last-sibling))
  6459. (point)))
  6460. (end (save-excursion
  6461. (and (org-get-next-sibling)
  6462. (org-get-next-sibling)
  6463. (org-get-next-sibling))
  6464. (if (org-at-heading-p)
  6465. (point-at-eol)
  6466. (point))))
  6467. (level (looking-at "\\*+"))
  6468. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6469. (save-excursion
  6470. (save-restriction
  6471. (narrow-to-region beg end)
  6472. (when re
  6473. ;; Properly fold already folded siblings
  6474. (goto-char (point-min))
  6475. (while (re-search-forward re nil t)
  6476. (when (and (not (outline-invisible-p))
  6477. (save-excursion
  6478. (goto-char (point-at-eol)) (outline-invisible-p)))
  6479. (outline-hide-entry))))
  6480. (org-cycle-show-empty-lines 'overview)
  6481. (org-cycle-hide-drawers 'overview)))))
  6482. (defun org-cycle-show-empty-lines (state)
  6483. "Show empty lines above all visible headlines.
  6484. The region to be covered depends on STATE when called through
  6485. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6486. entire buffer covered. Note that an empty line is only shown if there
  6487. are at least `org-cycle-separator-lines' empty lines before the headline."
  6488. (when (/= org-cycle-separator-lines 0)
  6489. (save-excursion
  6490. (let* ((n (abs org-cycle-separator-lines))
  6491. (re (cond
  6492. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6493. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6494. (t (let ((ns (number-to-string (- n 2))))
  6495. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6496. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6497. beg end)
  6498. (cond
  6499. ((memq state '(overview contents t))
  6500. (setq beg (point-min) end (point-max)))
  6501. ((memq state '(children folded))
  6502. (setq beg (point)
  6503. end (progn (org-end-of-subtree t t)
  6504. (line-beginning-position 2)))))
  6505. (when beg
  6506. (goto-char beg)
  6507. (while (re-search-forward re end t)
  6508. (unless (get-char-property (match-end 1) 'invisible)
  6509. (let ((e (match-end 1))
  6510. (b (if (>= org-cycle-separator-lines 0)
  6511. (match-beginning 1)
  6512. (save-excursion
  6513. (goto-char (match-beginning 0))
  6514. (skip-chars-backward " \t\n")
  6515. (line-end-position)))))
  6516. (outline-flag-region b e nil))))))))
  6517. ;; Never hide empty lines at the end of the file.
  6518. (save-excursion
  6519. (goto-char (point-max))
  6520. (outline-previous-heading)
  6521. (outline-end-of-heading)
  6522. (when (and (looking-at "[ \t\n]+")
  6523. (= (match-end 0) (point-max)))
  6524. (outline-flag-region (point) (match-end 0) nil))))
  6525. (defun org-show-empty-lines-in-parent ()
  6526. "Move to the parent and re-show empty lines before visible headlines."
  6527. (save-excursion
  6528. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6529. (org-cycle-show-empty-lines context))))
  6530. (defun org-files-list ()
  6531. "Return `org-agenda-files' list, plus all open Org files.
  6532. This is useful for operations that need to scan all of a user's
  6533. open and agenda-wise Org files."
  6534. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6535. (dolist (buf (buffer-list))
  6536. (with-current-buffer buf
  6537. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6538. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6539. files))
  6540. (defsubst org-entry-beginning-position ()
  6541. "Return the beginning position of the current entry."
  6542. (save-excursion (org-back-to-heading t) (point)))
  6543. (defsubst org-entry-end-position ()
  6544. "Return the end position of the current entry."
  6545. (save-excursion (outline-next-heading) (point)))
  6546. (defun org-cycle-hide-drawers (state &optional exceptions)
  6547. "Re-hide all drawers after a visibility state change.
  6548. When non-nil, optional argument EXCEPTIONS is a list of strings
  6549. specifying which drawers should not be hidden."
  6550. (when (and (derived-mode-p 'org-mode)
  6551. (not (memq state '(overview folded contents))))
  6552. (save-excursion
  6553. (let* ((globalp (memq state '(contents all)))
  6554. (beg (if globalp (point-min) (point)))
  6555. (end (if globalp (point-max)
  6556. (if (eq state 'children)
  6557. (save-excursion (outline-next-heading) (point))
  6558. (org-end-of-subtree t)))))
  6559. (goto-char beg)
  6560. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6561. (unless (member-ignore-case (match-string 1) exceptions)
  6562. (let ((drawer (org-element-at-point)))
  6563. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6564. (org-flag-drawer t drawer)
  6565. ;; Make sure to skip drawer entirely or we might flag
  6566. ;; it another time when matching its ending line with
  6567. ;; `org-drawer-regexp'.
  6568. (goto-char (org-element-property :end drawer))))))))))
  6569. (defun org-flag-drawer (flag &optional element)
  6570. "When FLAG is non-nil, hide the drawer we are at.
  6571. Otherwise make it visible. When optional argument ELEMENT is
  6572. a parsed drawer, as returned by `org-element-at-point', hide or
  6573. show that drawer instead."
  6574. (let ((drawer (or element
  6575. (and (save-excursion
  6576. (beginning-of-line)
  6577. (looking-at-p org-drawer-regexp))
  6578. (org-element-at-point)))))
  6579. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6580. (let ((post (org-element-property :post-affiliated drawer)))
  6581. (save-excursion
  6582. (outline-flag-region
  6583. (progn (goto-char post) (line-end-position))
  6584. (progn (goto-char (org-element-property :end drawer))
  6585. (skip-chars-backward " \r\t\n")
  6586. (line-end-position))
  6587. flag))
  6588. ;; When the drawer is hidden away, make sure point lies in
  6589. ;; a visible part of the buffer.
  6590. (when (and flag (> (line-beginning-position) post))
  6591. (goto-char post))))))
  6592. (defun org-subtree-end-visible-p ()
  6593. "Is the end of the current subtree visible?"
  6594. (pos-visible-in-window-p
  6595. (save-excursion (org-end-of-subtree t) (point))))
  6596. (defun org-first-headline-recenter ()
  6597. "Move cursor to the first headline and recenter the headline."
  6598. (let ((window (get-buffer-window)))
  6599. (when window
  6600. (goto-char (point-min))
  6601. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6602. (set-window-start window (line-beginning-position))))))
  6603. ;;; Saving and restoring visibility
  6604. (defun org-outline-overlay-data (&optional use-markers)
  6605. "Return a list of the locations of all outline overlays.
  6606. These are overlays with the `invisible' property value `outline'.
  6607. The return value is a list of cons cells, with start and stop
  6608. positions for each overlay.
  6609. If USE-MARKERS is set, return the positions as markers."
  6610. (let (beg end)
  6611. (org-with-wide-buffer
  6612. (delq nil
  6613. (mapcar (lambda (o)
  6614. (when (eq (overlay-get o 'invisible) 'outline)
  6615. (setq beg (overlay-start o)
  6616. end (overlay-end o))
  6617. (and beg end (> end beg)
  6618. (if use-markers
  6619. (cons (copy-marker beg)
  6620. (copy-marker end t))
  6621. (cons beg end)))))
  6622. (overlays-in (point-min) (point-max)))))))
  6623. (defun org-set-outline-overlay-data (data)
  6624. "Create visibility overlays for all positions in DATA.
  6625. DATA should have been made by `org-outline-overlay-data'."
  6626. (org-with-wide-buffer
  6627. (outline-show-all)
  6628. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6629. ;;; Folding of blocks
  6630. (defvar-local org-hide-block-overlays nil
  6631. "Overlays hiding blocks.")
  6632. (defun org-block-map (function &optional start end)
  6633. "Call FUNCTION at the head of all source blocks in the current buffer.
  6634. Optional arguments START and END can be used to limit the range."
  6635. (let ((start (or start (point-min)))
  6636. (end (or end (point-max))))
  6637. (save-excursion
  6638. (goto-char start)
  6639. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6640. (save-excursion
  6641. (save-match-data
  6642. (goto-char (match-beginning 0))
  6643. (funcall function)))))))
  6644. (defun org-hide-block-toggle-all ()
  6645. "Toggle the visibility of all blocks in the current buffer."
  6646. (org-block-map 'org-hide-block-toggle))
  6647. (defun org-hide-block-all ()
  6648. "Fold all blocks in the current buffer."
  6649. (interactive)
  6650. (org-show-block-all)
  6651. (org-block-map 'org-hide-block-toggle-maybe))
  6652. (defun org-show-block-all ()
  6653. "Unfold all blocks in the current buffer."
  6654. (interactive)
  6655. (mapc #'delete-overlay org-hide-block-overlays)
  6656. (setq org-hide-block-overlays nil))
  6657. (defun org-hide-block-toggle-maybe ()
  6658. "Toggle visibility of block at point.
  6659. Unlike to `org-hide-block-toggle', this function does not throw
  6660. an error. Return a non-nil value when toggling is successful."
  6661. (interactive)
  6662. (ignore-errors (org-hide-block-toggle)))
  6663. (defun org-hide-block-toggle (&optional force)
  6664. "Toggle the visibility of the current block.
  6665. When optional argument FORCE is `off', make block visible. If it
  6666. is non-nil, hide it unconditionally. Throw an error when not at
  6667. a block. Return a non-nil value when toggling is successful."
  6668. (interactive)
  6669. (let ((element (org-element-at-point)))
  6670. (unless (memq (org-element-type element)
  6671. '(center-block comment-block dynamic-block example-block
  6672. export-block quote-block special-block
  6673. src-block verse-block))
  6674. (user-error "Not at a block"))
  6675. (let* ((start (save-excursion
  6676. (goto-char (org-element-property :post-affiliated element))
  6677. (line-end-position)))
  6678. (end (save-excursion
  6679. (goto-char (org-element-property :end element))
  6680. (skip-chars-backward " \r\t\n")
  6681. (line-end-position)))
  6682. (overlays (overlays-at start)))
  6683. (cond
  6684. ;; Do nothing when not before or at the block opening line or
  6685. ;; at the block closing line.
  6686. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6687. ((and (not (eq force 'off))
  6688. (not (memq t (mapcar
  6689. (lambda (o)
  6690. (eq (overlay-get o 'invisible) 'org-hide-block))
  6691. overlays))))
  6692. (let ((ov (make-overlay start end)))
  6693. (overlay-put ov 'invisible 'org-hide-block)
  6694. ;; Make the block accessible to `isearch'.
  6695. (overlay-put
  6696. ov 'isearch-open-invisible
  6697. (lambda (ov)
  6698. (when (memq ov org-hide-block-overlays)
  6699. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6700. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6701. (delete-overlay ov))))
  6702. (push ov org-hide-block-overlays)
  6703. ;; When the block is hidden away, make sure point is left in
  6704. ;; a visible part of the buffer.
  6705. (when (> (line-beginning-position) start)
  6706. (goto-char start)
  6707. (beginning-of-line))
  6708. ;; Signal successful toggling.
  6709. t))
  6710. ((or (not force) (eq force 'off))
  6711. (dolist (ov overlays t)
  6712. (when (memq ov org-hide-block-overlays)
  6713. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6714. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6715. (delete-overlay ov))))))))
  6716. ;; Remove overlays when changing major mode
  6717. (add-hook 'org-mode-hook
  6718. (lambda () (add-hook 'change-major-mode-hook
  6719. 'org-show-block-all 'append 'local)))
  6720. ;;; Org-goto
  6721. (defvar org-goto-window-configuration nil)
  6722. (defvar org-goto-marker nil)
  6723. (defvar org-goto-map)
  6724. (defun org-goto-map ()
  6725. "Set the keymap `org-goto'."
  6726. (setq org-goto-map
  6727. (let ((map (make-sparse-keymap)))
  6728. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6729. mouse-drag-region universal-argument org-occur)))
  6730. (dolist (cmd cmds)
  6731. (substitute-key-definition cmd cmd map global-map)))
  6732. (suppress-keymap map)
  6733. (org-defkey map "\C-m" 'org-goto-ret)
  6734. (org-defkey map [(return)] 'org-goto-ret)
  6735. (org-defkey map [(left)] 'org-goto-left)
  6736. (org-defkey map [(right)] 'org-goto-right)
  6737. (org-defkey map [(control ?g)] 'org-goto-quit)
  6738. (org-defkey map "\C-i" 'org-cycle)
  6739. (org-defkey map [(tab)] 'org-cycle)
  6740. (org-defkey map [(down)] 'outline-next-visible-heading)
  6741. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6742. (if org-goto-auto-isearch
  6743. (if (fboundp 'define-key-after)
  6744. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6745. nil)
  6746. (org-defkey map "q" 'org-goto-quit)
  6747. (org-defkey map "n" 'outline-next-visible-heading)
  6748. (org-defkey map "p" 'outline-previous-visible-heading)
  6749. (org-defkey map "f" 'outline-forward-same-level)
  6750. (org-defkey map "b" 'outline-backward-same-level)
  6751. (org-defkey map "u" 'outline-up-heading))
  6752. (org-defkey map "/" 'org-occur)
  6753. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6754. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6755. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6756. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6757. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6758. map)))
  6759. (defconst org-goto-help
  6760. "Browse buffer copy, to find location or copy text.%s
  6761. RET=jump to location C-g=quit and return to previous location
  6762. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6763. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6764. (defun org-goto (&optional alternative-interface)
  6765. "Look up a different location in the current file, keeping current visibility.
  6766. When you want look-up or go to a different location in a
  6767. document, the fastest way is often to fold the entire buffer and
  6768. then dive into the tree. This method has the disadvantage, that
  6769. the previous location will be folded, which may not be what you
  6770. want.
  6771. This command works around this by showing a copy of the current
  6772. buffer in an indirect buffer, in overview mode. You can dive
  6773. into the tree in that copy, use org-occur and incremental search
  6774. to find a location. When pressing RET or `Q', the command
  6775. returns to the original buffer in which the visibility is still
  6776. unchanged. After RET it will also jump to the location selected
  6777. in the indirect buffer and expose the headline hierarchy above.
  6778. With a prefix argument, use the alternative interface: e.g., if
  6779. `org-goto-interface' is `outline' use `outline-path-completion'."
  6780. (interactive "P")
  6781. (org-goto-map)
  6782. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6783. (org-refile-use-outline-path t)
  6784. (org-refile-target-verify-function nil)
  6785. (interface
  6786. (if (not alternative-interface)
  6787. org-goto-interface
  6788. (if (eq org-goto-interface 'outline)
  6789. 'outline-path-completion
  6790. 'outline)))
  6791. (org-goto-start-pos (point))
  6792. (selected-point
  6793. (if (eq interface 'outline)
  6794. (car (org-get-location (current-buffer) org-goto-help))
  6795. (let ((pa (org-refile-get-location "Goto")))
  6796. (org-refile-check-position pa)
  6797. (nth 3 pa)))))
  6798. (if selected-point
  6799. (progn
  6800. (org-mark-ring-push org-goto-start-pos)
  6801. (goto-char selected-point)
  6802. (when (or (outline-invisible-p) (org-invisible-p2))
  6803. (org-show-context 'org-goto)))
  6804. (message "Quit"))))
  6805. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6806. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6807. (defvar org-goto-local-auto-isearch-map) ; defined below
  6808. (defun org-get-location (_buf help)
  6809. "Let the user select a location in current buffer.
  6810. This function uses a recursive edit. It returns the selected position
  6811. or nil."
  6812. (org-no-popups
  6813. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6814. (isearch-hide-immediately nil)
  6815. (isearch-search-fun-function
  6816. (lambda () 'org-goto-local-search-headings))
  6817. (org-goto-selected-point org-goto-exit-command))
  6818. (save-excursion
  6819. (save-window-excursion
  6820. (delete-other-windows)
  6821. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6822. (pop-to-buffer-same-window
  6823. (condition-case nil
  6824. (make-indirect-buffer (current-buffer) "*org-goto*")
  6825. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6826. (with-output-to-temp-buffer "*Org Help*"
  6827. (princ (format help (if org-goto-auto-isearch
  6828. " Just type for auto-isearch."
  6829. " n/p/f/b/u to navigate, q to quit."))))
  6830. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6831. (setq buffer-read-only nil)
  6832. (let ((org-startup-truncated t)
  6833. (org-startup-folded nil)
  6834. (org-startup-align-all-tables nil))
  6835. (org-mode)
  6836. (org-overview))
  6837. (setq buffer-read-only t)
  6838. (if (and (boundp 'org-goto-start-pos)
  6839. (integer-or-marker-p org-goto-start-pos))
  6840. (progn (goto-char org-goto-start-pos)
  6841. (when (outline-invisible-p)
  6842. (org-show-set-visibility 'lineage)))
  6843. (goto-char (point-min)))
  6844. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6845. (message "Select location and press RET")
  6846. (use-local-map org-goto-map)
  6847. (recursive-edit)))
  6848. (kill-buffer "*org-goto*")
  6849. (cons org-goto-selected-point org-goto-exit-command))))
  6850. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6851. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6852. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6853. (if (fboundp 'isearch-other-control-char)
  6854. (progn
  6855. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6856. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6857. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6858. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6859. (define-key org-goto-local-auto-isearch-map [return] nil))
  6860. (defun org-goto-local-search-headings (string bound noerror)
  6861. "Search and make sure that any matches are in headlines."
  6862. (catch 'return
  6863. (while (if isearch-forward
  6864. (search-forward string bound noerror)
  6865. (search-backward string bound noerror))
  6866. (when (save-match-data
  6867. (and (save-excursion
  6868. (beginning-of-line)
  6869. (looking-at org-complex-heading-regexp))
  6870. (or (not (match-beginning 5))
  6871. (< (point) (match-beginning 5)))))
  6872. (throw 'return (point))))))
  6873. (defun org-goto-local-auto-isearch ()
  6874. "Start isearch."
  6875. (interactive)
  6876. (goto-char (point-min))
  6877. (let ((keys (this-command-keys)))
  6878. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6879. (isearch-mode t)
  6880. (isearch-process-search-char (string-to-char keys)))))
  6881. (defun org-goto-ret (&optional _arg)
  6882. "Finish `org-goto' by going to the new location."
  6883. (interactive "P")
  6884. (setq org-goto-selected-point (point))
  6885. (setq org-goto-exit-command 'return)
  6886. (throw 'exit nil))
  6887. (defun org-goto-left ()
  6888. "Finish `org-goto' by going to the new location."
  6889. (interactive)
  6890. (if (org-at-heading-p)
  6891. (progn
  6892. (beginning-of-line 1)
  6893. (setq org-goto-selected-point (point)
  6894. org-goto-exit-command 'left)
  6895. (throw 'exit nil))
  6896. (user-error "Not on a heading")))
  6897. (defun org-goto-right ()
  6898. "Finish `org-goto' by going to the new location."
  6899. (interactive)
  6900. (if (org-at-heading-p)
  6901. (progn
  6902. (setq org-goto-selected-point (point)
  6903. org-goto-exit-command 'right)
  6904. (throw 'exit nil))
  6905. (user-error "Not on a heading")))
  6906. (defun org-goto-quit ()
  6907. "Finish `org-goto' without cursor motion."
  6908. (interactive)
  6909. (setq org-goto-selected-point nil)
  6910. (setq org-goto-exit-command 'quit)
  6911. (throw 'exit nil))
  6912. ;;; Indirect buffer display of subtrees
  6913. (defvar org-indirect-dedicated-frame nil
  6914. "This is the frame being used for indirect tree display.")
  6915. (defvar org-last-indirect-buffer nil)
  6916. (defun org-tree-to-indirect-buffer (&optional arg)
  6917. "Create indirect buffer and narrow it to current subtree.
  6918. With a numerical prefix ARG, go up to this level and then take that tree.
  6919. If ARG is negative, go up that many levels.
  6920. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6921. indirect buffer previously made with this command, to avoid proliferation of
  6922. indirect buffers. However, when you call the command with a \
  6923. `\\[universal-argument]' prefix, or
  6924. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6925. so that you can work with several indirect buffers at the same time. If
  6926. `org-indirect-buffer-display' is `dedicated-frame', the \
  6927. `\\[universal-argument]' prefix also
  6928. requests that a new frame be made for the new buffer, so that the dedicated
  6929. frame is not changed."
  6930. (interactive "P")
  6931. (let ((cbuf (current-buffer))
  6932. (cwin (selected-window))
  6933. (pos (point))
  6934. beg end level heading ibuf)
  6935. (save-excursion
  6936. (org-back-to-heading t)
  6937. (when (numberp arg)
  6938. (setq level (org-outline-level))
  6939. (when (< arg 0) (setq arg (+ level arg)))
  6940. (while (> (setq level (org-outline-level)) arg)
  6941. (org-up-heading-safe)))
  6942. (setq beg (point)
  6943. heading (org-get-heading 'no-tags))
  6944. (org-end-of-subtree t t)
  6945. (when (org-at-heading-p) (backward-char 1))
  6946. (setq end (point)))
  6947. (when (and (buffer-live-p org-last-indirect-buffer)
  6948. (not (eq org-indirect-buffer-display 'new-frame))
  6949. (not arg))
  6950. (kill-buffer org-last-indirect-buffer))
  6951. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6952. org-last-indirect-buffer ibuf)
  6953. (cond
  6954. ((or (eq org-indirect-buffer-display 'new-frame)
  6955. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6956. (select-frame (make-frame))
  6957. (delete-other-windows)
  6958. (pop-to-buffer-same-window ibuf)
  6959. (org-set-frame-title heading))
  6960. ((eq org-indirect-buffer-display 'dedicated-frame)
  6961. (raise-frame
  6962. (select-frame (or (and org-indirect-dedicated-frame
  6963. (frame-live-p org-indirect-dedicated-frame)
  6964. org-indirect-dedicated-frame)
  6965. (setq org-indirect-dedicated-frame (make-frame)))))
  6966. (delete-other-windows)
  6967. (pop-to-buffer-same-window ibuf)
  6968. (org-set-frame-title (concat "Indirect: " heading)))
  6969. ((eq org-indirect-buffer-display 'current-window)
  6970. (pop-to-buffer-same-window ibuf))
  6971. ((eq org-indirect-buffer-display 'other-window)
  6972. (pop-to-buffer ibuf))
  6973. (t (error "Invalid value")))
  6974. (narrow-to-region beg end)
  6975. (outline-show-all)
  6976. (goto-char pos)
  6977. (run-hook-with-args 'org-cycle-hook 'all)
  6978. (and (window-live-p cwin) (select-window cwin))))
  6979. (defun org-get-indirect-buffer (&optional buffer heading)
  6980. (setq buffer (or buffer (current-buffer)))
  6981. (let ((n 1) (base (buffer-name buffer)) bname)
  6982. (while (buffer-live-p
  6983. (get-buffer
  6984. (setq bname
  6985. (concat base "-"
  6986. (if heading (concat heading "-" (number-to-string n))
  6987. (number-to-string n))))))
  6988. (setq n (1+ n)))
  6989. (condition-case nil
  6990. (make-indirect-buffer buffer bname 'clone)
  6991. (error (make-indirect-buffer buffer bname)))))
  6992. (defun org-set-frame-title (title)
  6993. "Set the title of the current frame to the string TITLE."
  6994. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6995. ;;;; Structure editing
  6996. ;;; Inserting headlines
  6997. (defun org--line-empty-p (n)
  6998. "Is the Nth next line empty?
  6999. Counts the current line as N = 1 and the previous line as N = 0;
  7000. see `beginning-of-line'."
  7001. (save-excursion
  7002. (and (not (bobp))
  7003. (or (beginning-of-line n) t)
  7004. (save-match-data
  7005. (looking-at "[ \t]*$")))))
  7006. (defun org-previous-line-empty-p ()
  7007. "Is the previous line a blank line?
  7008. When NEXT is non-nil, check the next line instead."
  7009. (org--line-empty-p 0))
  7010. (defun org-next-line-empty-p ()
  7011. "Is the previous line a blank line?
  7012. When NEXT is non-nil, check the next line instead."
  7013. (org--line-empty-p 2))
  7014. (defun org-insert-heading (&optional arg invisible-ok top)
  7015. "Insert a new heading or an item with the same depth at point.
  7016. If point is at the beginning of a heading or a list item, insert
  7017. a new heading or a new item above the current one. When at the
  7018. beginning of a regular line of text, turn it into a heading.
  7019. If point is in the middle of a line, split it and create a new
  7020. headline/item with the text in the current line after point (see
  7021. `org-M-RET-may-split-line' on how to modify this behavior). As
  7022. a special case, on a headline, splitting can only happen on the
  7023. title itself. E.g., this excludes breaking stars or tags.
  7024. With a `\\[universal-argument]' prefix, set \
  7025. `org-insert-heading-respect-content' to
  7026. a non-nil value for the duration of the command. This forces the
  7027. insertion of a heading after the current subtree, independently
  7028. on the location of point.
  7029. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  7030. insert the heading at the end of the tree
  7031. above the current heading. For example, if point is within a
  7032. 2nd-level heading, then it will insert a 2nd-level heading at
  7033. the end of the 1st-level parent subtree.
  7034. When INVISIBLE-OK is set, stop at invisible headlines when going
  7035. back. This is important for non-interactive uses of the
  7036. command.
  7037. When optional argument TOP is non-nil, insert a level 1 heading,
  7038. unconditionally."
  7039. (interactive "P")
  7040. (let ((itemp (and (not top) (org-in-item-p)))
  7041. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7042. (respect-content (or org-insert-heading-respect-content
  7043. (equal arg '(4))))
  7044. (initial-content ""))
  7045. (cond
  7046. ((or (= (buffer-size) 0)
  7047. (and (not (save-excursion
  7048. (and (ignore-errors (org-back-to-heading invisible-ok))
  7049. (org-at-heading-p))))
  7050. (or arg (not itemp))))
  7051. ;; At beginning of buffer or so high up that only a heading
  7052. ;; makes sense.
  7053. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7054. ((not respect-content)
  7055. (unless may-split (end-of-line))
  7056. (insert "\n* "))
  7057. ((re-search-forward org-outline-regexp-bol nil t)
  7058. (beginning-of-line)
  7059. (insert "* \n")
  7060. (backward-char))
  7061. (t (goto-char (point-max))
  7062. (insert "\n* ")))
  7063. (run-hooks 'org-insert-heading-hook))
  7064. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7065. (t
  7066. ;; Maybe move at the end of the subtree
  7067. (when (equal arg '(16))
  7068. (org-up-heading-safe)
  7069. (org-end-of-subtree t))
  7070. ;; Insert a heading
  7071. (save-restriction
  7072. (widen)
  7073. (let* ((level nil)
  7074. (on-heading (org-at-heading-p))
  7075. (empty-line-p (if on-heading
  7076. (org-previous-line-empty-p)
  7077. ;; We will decide later
  7078. nil))
  7079. ;; Get a level string to fall back on.
  7080. (fix-level
  7081. (if (org-before-first-heading-p) "*"
  7082. (save-excursion
  7083. (org-back-to-heading t)
  7084. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7085. (looking-at org-outline-regexp)
  7086. (make-string (1- (length (match-string 0))) ?*))))
  7087. (stars
  7088. (save-excursion
  7089. (condition-case nil
  7090. (if top "* "
  7091. (org-back-to-heading invisible-ok)
  7092. (when (and (not on-heading)
  7093. (featurep 'org-inlinetask)
  7094. (integerp org-inlinetask-min-level)
  7095. (>= (length (match-string 0))
  7096. org-inlinetask-min-level))
  7097. ;; Find a heading level before the inline
  7098. ;; task.
  7099. (while (and (setq level (org-up-heading-safe))
  7100. (>= level org-inlinetask-min-level)))
  7101. (if (org-at-heading-p)
  7102. (org-back-to-heading invisible-ok)
  7103. (error "This should not happen")))
  7104. (unless (and (save-excursion
  7105. (save-match-data
  7106. (org-backward-heading-same-level
  7107. 1 invisible-ok))
  7108. (= (point) (match-beginning 0)))
  7109. (not (org-next-line-empty-p)))
  7110. (setq empty-line-p (or empty-line-p
  7111. (org-previous-line-empty-p))))
  7112. (match-string 0))
  7113. (error (or fix-level "* ")))))
  7114. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7115. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7116. ;; If we insert after content, move there and clean up
  7117. ;; whitespace.
  7118. (when respect-content
  7119. (if (not (org-before-first-heading-p))
  7120. (org-end-of-subtree nil t)
  7121. (re-search-forward org-outline-regexp-bol)
  7122. (beginning-of-line 0))
  7123. (skip-chars-backward " \r\t\n")
  7124. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7125. (looking-at "[ \t]+") (replace-match ""))
  7126. (unless (eobp) (forward-char 1))
  7127. (when (looking-at "^\\*")
  7128. (unless (bobp) (backward-char 1))
  7129. (insert "\n")))
  7130. ;; If we are splitting, grab the text that should be moved
  7131. ;; to the new headline.
  7132. (when may-split
  7133. (if (org-at-heading-p)
  7134. ;; This is a heading: split intelligently (keeping
  7135. ;; tags).
  7136. (let ((pos (point)))
  7137. (beginning-of-line)
  7138. (let ((case-fold-search nil))
  7139. (unless (looking-at org-complex-heading-regexp)
  7140. (error "This should not happen")))
  7141. (when (and (match-beginning 4)
  7142. (> pos (match-beginning 4))
  7143. (< pos (match-end 4)))
  7144. (setq initial-content (buffer-substring pos (match-end 4)))
  7145. (goto-char pos)
  7146. (delete-region (point) (match-end 4))
  7147. (if (looking-at "[ \t]*$")
  7148. (replace-match "")
  7149. (insert (make-string (length initial-content) ?\s)))
  7150. (setq initial-content (org-trim initial-content)))
  7151. (goto-char pos))
  7152. ;; A normal line.
  7153. (setq initial-content
  7154. (org-trim
  7155. (delete-and-extract-region (point) (line-end-position))))))
  7156. ;; If we are at the beginning of the line, insert before it.
  7157. ;; Otherwise, after it.
  7158. (cond
  7159. ((and (bolp) (looking-at "[ \t]*$")))
  7160. ((bolp) (save-excursion (insert "\n")))
  7161. (t (end-of-line)
  7162. (insert "\n")))
  7163. ;; Insert the new heading
  7164. (insert stars)
  7165. (just-one-space)
  7166. (insert initial-content)
  7167. (unless (and blank (org-previous-line-empty-p))
  7168. (org-N-empty-lines-before-current (if blank 1 0)))
  7169. ;; Adjust visibility, which may be messed up if we removed
  7170. ;; blank lines while previous entry was hidden.
  7171. (let ((bol (line-beginning-position)))
  7172. (dolist (o (overlays-at (1- bol)))
  7173. (when (and (eq (overlay-get o 'invisible) 'outline)
  7174. (eq (overlay-end o) bol))
  7175. (move-overlay o (overlay-start o) (1- bol)))))
  7176. (run-hooks 'org-insert-heading-hook)))))))
  7177. (defun org-N-empty-lines-before-current (N)
  7178. "Make the number of empty lines before current exactly N.
  7179. So this will delete or add empty lines."
  7180. (save-excursion
  7181. (beginning-of-line)
  7182. (let ((p (point)))
  7183. (skip-chars-backward " \r\t\n")
  7184. (unless (bolp) (forward-line))
  7185. (delete-region (point) p))
  7186. (when (> N 0) (insert (make-string N ?\n)))))
  7187. (defun org-get-heading (&optional no-tags no-todo)
  7188. "Return the heading of the current entry, without the stars.
  7189. When NO-TAGS is non-nil, don't include tags.
  7190. When NO-TODO is non-nil, don't include TODO keywords."
  7191. (save-excursion
  7192. (org-back-to-heading t)
  7193. (let ((case-fold-search nil))
  7194. (cond
  7195. ((and no-tags no-todo)
  7196. (looking-at org-complex-heading-regexp)
  7197. ;; Return value has to be a string, but match group 4 is
  7198. ;; optional.
  7199. (or (match-string 4) ""))
  7200. (no-tags
  7201. (looking-at (concat org-outline-regexp
  7202. "\\(.*?\\)"
  7203. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7204. (match-string 1))
  7205. (no-todo
  7206. (looking-at org-todo-line-regexp)
  7207. (match-string 3))
  7208. (t (looking-at org-heading-regexp)
  7209. (match-string 2))))))
  7210. (defvar orgstruct-mode) ; defined below
  7211. (defun org-heading-components ()
  7212. "Return the components of the current heading.
  7213. This is a list with the following elements:
  7214. - the level as an integer
  7215. - the reduced level, different if `org-odd-levels-only' is set.
  7216. - the TODO keyword, or nil
  7217. - the priority character, like ?A, or nil if no priority is given
  7218. - the headline text itself, or the tags string if no headline text
  7219. - the tags string, or nil."
  7220. (save-excursion
  7221. (org-back-to-heading t)
  7222. (when (let (case-fold-search)
  7223. (looking-at
  7224. (if orgstruct-mode
  7225. org-heading-regexp
  7226. org-complex-heading-regexp)))
  7227. (if orgstruct-mode
  7228. (list (length (match-string 1))
  7229. (org-reduced-level (length (match-string 1)))
  7230. nil
  7231. nil
  7232. (match-string 2)
  7233. nil)
  7234. (list (length (match-string 1))
  7235. (org-reduced-level (length (match-string 1)))
  7236. (match-string-no-properties 2)
  7237. (and (match-end 3) (aref (match-string 3) 2))
  7238. (match-string-no-properties 4)
  7239. (match-string-no-properties 5))))))
  7240. (defun org-get-entry ()
  7241. "Get the entry text, after heading, entire subtree."
  7242. (save-excursion
  7243. (org-back-to-heading t)
  7244. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7245. (defun org-edit-headline (&optional heading)
  7246. "Edit the current headline.
  7247. Set it to HEADING when provided."
  7248. (interactive)
  7249. (org-with-wide-buffer
  7250. (org-back-to-heading t)
  7251. (let ((case-fold-search nil))
  7252. (when (looking-at org-complex-heading-regexp)
  7253. (let* ((old (match-string-no-properties 4))
  7254. (new (save-match-data
  7255. (org-trim (or heading (read-string "Edit: " old))))))
  7256. (unless (equal old new)
  7257. (if old (replace-match new t t nil 4)
  7258. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7259. (insert " " new))
  7260. (org-set-tags nil t)
  7261. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7262. (defun org-insert-heading-after-current ()
  7263. "Insert a new heading with same level as current, after current subtree."
  7264. (interactive)
  7265. (org-back-to-heading)
  7266. (org-insert-heading)
  7267. (org-move-subtree-down)
  7268. (end-of-line 1))
  7269. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7270. "Insert heading with `org-insert-heading-respect-content' set to t."
  7271. (interactive)
  7272. (org-insert-heading '(4) invisible-ok))
  7273. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7274. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7275. (interactive)
  7276. (org-insert-todo-heading force-state '(4)))
  7277. (defun org-insert-todo-heading (arg &optional force-heading)
  7278. "Insert a new heading with the same level and TODO state as current heading.
  7279. If the heading has no TODO state, or if the state is DONE, use
  7280. the first state (TODO by default). Also with one prefix arg,
  7281. force first state. With two prefix args, force inserting at the
  7282. end of the parent subtree.
  7283. When called at a plain list item, insert a new item with an
  7284. unchecked check box."
  7285. (interactive "P")
  7286. (when (or force-heading (not (org-insert-item 'checkbox)))
  7287. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7288. force-heading))
  7289. (save-excursion
  7290. (org-back-to-heading)
  7291. (outline-previous-heading)
  7292. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7293. (let* ((new-mark-x
  7294. (if (or (equal arg '(4))
  7295. (not (match-beginning 2))
  7296. (member (match-string 2) org-done-keywords))
  7297. (car org-todo-keywords-1)
  7298. (match-string 2)))
  7299. (new-mark
  7300. (or
  7301. (run-hook-with-args-until-success
  7302. 'org-todo-get-default-hook new-mark-x nil)
  7303. new-mark-x)))
  7304. (beginning-of-line 1)
  7305. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7306. (if org-treat-insert-todo-heading-as-state-change
  7307. (org-todo new-mark)
  7308. (insert new-mark " "))))
  7309. (when org-provide-todo-statistics
  7310. (org-update-parent-todo-statistics))))
  7311. (defun org-insert-subheading (arg)
  7312. "Insert a new subheading and demote it.
  7313. Works for outline headings and for plain lists alike."
  7314. (interactive "P")
  7315. (org-insert-heading arg)
  7316. (cond
  7317. ((org-at-heading-p) (org-do-demote))
  7318. ((org-at-item-p) (org-indent-item))))
  7319. (defun org-insert-todo-subheading (arg)
  7320. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7321. Works for outline headings and for plain lists alike."
  7322. (interactive "P")
  7323. (org-insert-todo-heading arg)
  7324. (cond
  7325. ((org-at-heading-p) (org-do-demote))
  7326. ((org-at-item-p) (org-indent-item))))
  7327. ;;; Promotion and Demotion
  7328. (defvar org-after-demote-entry-hook nil
  7329. "Hook run after an entry has been demoted.
  7330. The cursor will be at the beginning of the entry.
  7331. When a subtree is being demoted, the hook will be called for each node.")
  7332. (defvar org-after-promote-entry-hook nil
  7333. "Hook run after an entry has been promoted.
  7334. The cursor will be at the beginning of the entry.
  7335. When a subtree is being promoted, the hook will be called for each node.")
  7336. (defun org-promote-subtree ()
  7337. "Promote the entire subtree.
  7338. See also `org-promote'."
  7339. (interactive)
  7340. (save-excursion
  7341. (org-with-limited-levels (org-map-tree 'org-promote)))
  7342. (org-fix-position-after-promote))
  7343. (defun org-demote-subtree ()
  7344. "Demote the entire subtree.
  7345. See `org-demote' and `org-promote'."
  7346. (interactive)
  7347. (save-excursion
  7348. (org-with-limited-levels (org-map-tree 'org-demote)))
  7349. (org-fix-position-after-promote))
  7350. (defun org-do-promote ()
  7351. "Promote the current heading higher up the tree.
  7352. If the region is active in `transient-mark-mode', promote all
  7353. headings in the region."
  7354. (interactive)
  7355. (save-excursion
  7356. (if (org-region-active-p)
  7357. (org-map-region 'org-promote (region-beginning) (region-end))
  7358. (org-promote)))
  7359. (org-fix-position-after-promote))
  7360. (defun org-do-demote ()
  7361. "Demote the current heading lower down the tree.
  7362. If the region is active in `transient-mark-mode', demote all
  7363. headings in the region."
  7364. (interactive)
  7365. (save-excursion
  7366. (if (org-region-active-p)
  7367. (org-map-region 'org-demote (region-beginning) (region-end))
  7368. (org-demote)))
  7369. (org-fix-position-after-promote))
  7370. (defun org-fix-position-after-promote ()
  7371. "Fix cursor position and indentation after demoting/promoting."
  7372. (let ((pos (point)))
  7373. (when (save-excursion
  7374. (beginning-of-line)
  7375. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7376. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7377. (cond ((eobp) (insert " "))
  7378. ((eolp) (insert " "))
  7379. ((equal (char-after) ?\s) (forward-char 1))))))
  7380. (defun org-current-level ()
  7381. "Return the level of the current entry, or nil if before the first headline.
  7382. The level is the number of stars at the beginning of the
  7383. headline. Use `org-reduced-level' to remove the effect of
  7384. `org-odd-levels'. Unlike to `org-outline-level', this function
  7385. ignores inlinetasks."
  7386. (let ((level (org-with-limited-levels (org-outline-level))))
  7387. (and (> level 0) level)))
  7388. (defun org-get-previous-line-level ()
  7389. "Return the outline depth of the last headline before the current line.
  7390. Returns 0 for the first headline in the buffer, and nil if before the
  7391. first headline."
  7392. (and (org-current-level)
  7393. (or (and (/= (line-beginning-position) (point-min))
  7394. (save-excursion (beginning-of-line 0) (org-current-level)))
  7395. 0)))
  7396. (defun org-reduced-level (l)
  7397. "Compute the effective level of a heading.
  7398. This takes into account the setting of `org-odd-levels-only'."
  7399. (cond
  7400. ((zerop l) 0)
  7401. (org-odd-levels-only (1+ (floor (/ l 2))))
  7402. (t l)))
  7403. (defun org-level-increment ()
  7404. "Return the number of stars that will be added or removed at a
  7405. time to headlines when structure editing, based on the value of
  7406. `org-odd-levels-only'."
  7407. (if org-odd-levels-only 2 1))
  7408. (defun org-get-valid-level (level &optional change)
  7409. "Rectify a level change under the influence of `org-odd-levels-only'
  7410. LEVEL is a current level, CHANGE is by how much the level should be
  7411. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7412. even level numbers will become the next higher odd number."
  7413. (if org-odd-levels-only
  7414. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7415. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7416. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7417. (max 1 (+ level (or change 0)))))
  7418. (defun org-promote ()
  7419. "Promote the current heading higher up the tree."
  7420. (org-with-wide-buffer
  7421. (org-back-to-heading t)
  7422. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7423. after-change-functions))
  7424. (level (save-match-data (funcall outline-level)))
  7425. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7426. (diff (abs (- level (length up-head) -1))))
  7427. (cond
  7428. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7429. (replace-match "# " nil t))
  7430. ((= level 1)
  7431. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7432. (t (replace-match up-head nil t)))
  7433. (unless (= level 1)
  7434. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7435. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7436. (run-hooks 'org-after-promote-entry-hook))))
  7437. (defun org-demote ()
  7438. "Demote the current heading lower down the tree."
  7439. (org-with-wide-buffer
  7440. (org-back-to-heading t)
  7441. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7442. after-change-functions))
  7443. (level (save-match-data (funcall outline-level)))
  7444. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7445. (diff (abs (- level (length down-head) -1))))
  7446. (replace-match down-head nil t)
  7447. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7448. (when org-adapt-indentation (org-fixup-indentation diff))
  7449. (run-hooks 'org-after-demote-entry-hook))))
  7450. (defun org-cycle-level ()
  7451. "Cycle the level of an empty headline through possible states.
  7452. This goes first to child, then to parent, level, then up the hierarchy.
  7453. After top level, it switches back to sibling level."
  7454. (interactive)
  7455. (let ((org-adapt-indentation nil))
  7456. (when (org-point-at-end-of-empty-headline)
  7457. (setq this-command 'org-cycle-level) ; Only needed for caching
  7458. (let ((cur-level (org-current-level))
  7459. (prev-level (org-get-previous-line-level)))
  7460. (cond
  7461. ;; If first headline in file, promote to top-level.
  7462. ((= prev-level 0)
  7463. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7464. do (org-do-promote)))
  7465. ;; If same level as prev, demote one.
  7466. ((= prev-level cur-level)
  7467. (org-do-demote))
  7468. ;; If parent is top-level, promote to top level if not already.
  7469. ((= prev-level 1)
  7470. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7471. do (org-do-promote)))
  7472. ;; If top-level, return to prev-level.
  7473. ((= cur-level 1)
  7474. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7475. do (org-do-demote)))
  7476. ;; If less than prev-level, promote one.
  7477. ((< cur-level prev-level)
  7478. (org-do-promote))
  7479. ;; If deeper than prev-level, promote until higher than
  7480. ;; prev-level.
  7481. ((> cur-level prev-level)
  7482. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7483. do (org-do-promote))))
  7484. t))))
  7485. (defun org-map-tree (fun)
  7486. "Call FUN for every heading underneath the current one."
  7487. (org-back-to-heading t)
  7488. (let ((level (funcall outline-level)))
  7489. (save-excursion
  7490. (funcall fun)
  7491. (while (and (progn
  7492. (outline-next-heading)
  7493. (> (funcall outline-level) level))
  7494. (not (eobp)))
  7495. (funcall fun)))))
  7496. (defun org-map-region (fun beg end)
  7497. "Call FUN for every heading between BEG and END."
  7498. (let ((org-ignore-region t))
  7499. (save-excursion
  7500. (setq end (copy-marker end))
  7501. (goto-char beg)
  7502. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7503. (< (point) end))
  7504. (funcall fun))
  7505. (while (and (progn
  7506. (outline-next-heading)
  7507. (< (point) end))
  7508. (not (eobp)))
  7509. (funcall fun)))))
  7510. (defun org-fixup-indentation (diff)
  7511. "Change the indentation in the current entry by DIFF.
  7512. DIFF is an integer. Indentation is done according to the
  7513. following rules:
  7514. - Planning information and property drawers are always indented
  7515. according to the new level of the headline;
  7516. - Footnote definitions and their contents are ignored;
  7517. - Inlinetasks' boundaries are not shifted;
  7518. - Empty lines are ignored;
  7519. - Other lines' indentation are shifted by DIFF columns, unless
  7520. it would introduce a structural change in the document, in
  7521. which case no shifting is done at all.
  7522. Assume point is at a heading or an inlinetask beginning."
  7523. (org-with-wide-buffer
  7524. (narrow-to-region (line-beginning-position)
  7525. (save-excursion
  7526. (if (org-with-limited-levels (org-at-heading-p))
  7527. (org-with-limited-levels (outline-next-heading))
  7528. (org-inlinetask-goto-end))
  7529. (point)))
  7530. (forward-line)
  7531. ;; Indent properly planning info and property drawer.
  7532. (when (looking-at-p org-planning-line-re)
  7533. (org-indent-line)
  7534. (forward-line))
  7535. (when (looking-at org-property-drawer-re)
  7536. (goto-char (match-end 0))
  7537. (forward-line)
  7538. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7539. (catch 'no-shift
  7540. (when (zerop diff) (throw 'no-shift nil))
  7541. ;; If DIFF is negative, first check if a shift is possible at all
  7542. ;; (e.g., it doesn't break structure). This can only happen if
  7543. ;; some contents are not properly indented.
  7544. (let ((case-fold-search t))
  7545. (when (< diff 0)
  7546. (let ((diff (- diff))
  7547. (forbidden-re (concat org-outline-regexp
  7548. "\\|"
  7549. (substring org-footnote-definition-re 1))))
  7550. (save-excursion
  7551. (while (not (eobp))
  7552. (cond
  7553. ((looking-at-p "[ \t]*$") (forward-line))
  7554. ((and (looking-at-p org-footnote-definition-re)
  7555. (let ((e (org-element-at-point)))
  7556. (and (eq (org-element-type e) 'footnote-definition)
  7557. (goto-char (org-element-property :end e))))))
  7558. ((looking-at-p org-outline-regexp) (forward-line))
  7559. ;; Give up if shifting would move before column 0 or
  7560. ;; if it would introduce a headline or a footnote
  7561. ;; definition.
  7562. (t
  7563. (skip-chars-forward " \t")
  7564. (let ((ind (current-column)))
  7565. (when (or (< ind diff)
  7566. (and (= ind diff) (looking-at-p forbidden-re)))
  7567. (throw 'no-shift nil)))
  7568. ;; Ignore contents of example blocks and source
  7569. ;; blocks if their indentation is meant to be
  7570. ;; preserved. Jump to block's closing line.
  7571. (beginning-of-line)
  7572. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7573. (let ((e (org-element-at-point)))
  7574. (and (memq (org-element-type e)
  7575. '(example-block src-block))
  7576. (or org-src-preserve-indentation
  7577. (org-element-property :preserve-indent e))
  7578. (goto-char (org-element-property :end e))
  7579. (progn (skip-chars-backward " \r\t\n")
  7580. (beginning-of-line)
  7581. t))))
  7582. (forward-line))))))))
  7583. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7584. ;; by DIFF. Also skip contents of source or example blocks
  7585. ;; when indentation is meant to be preserved.
  7586. (while (not (eobp))
  7587. (cond
  7588. ((and (looking-at-p org-footnote-definition-re)
  7589. (let ((e (org-element-at-point)))
  7590. (and (eq (org-element-type e) 'footnote-definition)
  7591. (goto-char (org-element-property :end e))))))
  7592. ((looking-at-p org-outline-regexp) (forward-line))
  7593. ((looking-at-p "[ \t]*$") (forward-line))
  7594. (t
  7595. (indent-line-to (+ (org-get-indentation) diff))
  7596. (beginning-of-line)
  7597. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7598. (let ((e (org-element-at-point)))
  7599. (and (memq (org-element-type e)
  7600. '(example-block src-block))
  7601. (or org-src-preserve-indentation
  7602. (org-element-property :preserve-indent e))
  7603. (goto-char (org-element-property :end e))
  7604. (progn (skip-chars-backward " \r\t\n")
  7605. (beginning-of-line)
  7606. t))))
  7607. (forward-line)))))))))
  7608. (defun org-convert-to-odd-levels ()
  7609. "Convert an Org file with all levels allowed to one with odd levels.
  7610. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7611. level 5 etc."
  7612. (interactive)
  7613. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7614. (let ((outline-level 'org-outline-level)
  7615. (org-odd-levels-only nil) n)
  7616. (save-excursion
  7617. (goto-char (point-min))
  7618. (while (re-search-forward "^\\*\\*+ " nil t)
  7619. (setq n (- (length (match-string 0)) 2))
  7620. (while (>= (setq n (1- n)) 0)
  7621. (org-demote))
  7622. (end-of-line 1))))))
  7623. (defun org-convert-to-oddeven-levels ()
  7624. "Convert an Org file with only odd levels to one with odd/even levels.
  7625. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7626. file contains a section with an even level, conversion would
  7627. destroy the structure of the file. An error is signaled in this
  7628. case."
  7629. (interactive)
  7630. (goto-char (point-min))
  7631. ;; First check if there are no even levels
  7632. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7633. (org-show-set-visibility 'canonical)
  7634. (error "Not all levels are odd in this file. Conversion not possible"))
  7635. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7636. (let ((outline-regexp org-outline-regexp)
  7637. (outline-level 'org-outline-level)
  7638. (org-odd-levels-only nil) n)
  7639. (save-excursion
  7640. (goto-char (point-min))
  7641. (while (re-search-forward "^\\*\\*+ " nil t)
  7642. (setq n (/ (1- (length (match-string 0))) 2))
  7643. (while (>= (setq n (1- n)) 0)
  7644. (org-promote))
  7645. (end-of-line 1))))))
  7646. (defun org-tr-level (n)
  7647. "Make N odd if required."
  7648. (if org-odd-levels-only (1+ (/ n 2)) n))
  7649. ;;; Vertical tree motion, cutting and pasting of subtrees
  7650. (defun org-move-subtree-up (&optional arg)
  7651. "Move the current subtree up past ARG headlines of the same level."
  7652. (interactive "p")
  7653. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7654. (defun org-move-subtree-down (&optional arg)
  7655. "Move the current subtree down past ARG headlines of the same level."
  7656. (interactive "p")
  7657. (setq arg (prefix-numeric-value arg))
  7658. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7659. 'org-get-last-sibling))
  7660. (ins-point (make-marker))
  7661. (cnt (abs arg))
  7662. (col (current-column))
  7663. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7664. ;; Select the tree
  7665. (org-back-to-heading)
  7666. (setq beg0 (point))
  7667. (save-excursion
  7668. (setq ne-beg (org-back-over-empty-lines))
  7669. (setq beg (point)))
  7670. (save-match-data
  7671. (save-excursion (outline-end-of-heading)
  7672. (setq folded (outline-invisible-p)))
  7673. (progn (org-end-of-subtree nil t)
  7674. (unless (eobp) (backward-char))))
  7675. (outline-next-heading)
  7676. (setq ne-end (org-back-over-empty-lines))
  7677. (setq end (point))
  7678. (goto-char beg0)
  7679. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7680. ;; include less whitespace
  7681. (save-excursion
  7682. (goto-char beg)
  7683. (forward-line (- ne-beg ne-end))
  7684. (setq beg (point))))
  7685. ;; Find insertion point, with error handling
  7686. (while (> cnt 0)
  7687. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7688. (progn (goto-char beg0)
  7689. (user-error "Cannot move past superior level or buffer limit")))
  7690. (setq cnt (1- cnt)))
  7691. (when (> arg 0)
  7692. ;; Moving forward - still need to move over subtree
  7693. (org-end-of-subtree t t)
  7694. (save-excursion
  7695. (org-back-over-empty-lines)
  7696. (or (bolp) (newline))))
  7697. (setq ne-ins (org-back-over-empty-lines))
  7698. (move-marker ins-point (point))
  7699. (setq txt (buffer-substring beg end))
  7700. (org-save-markers-in-region beg end)
  7701. (delete-region beg end)
  7702. (org-remove-empty-overlays-at beg)
  7703. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7704. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7705. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7706. (let ((bbb (point)))
  7707. (insert-before-markers txt)
  7708. (org-reinstall-markers-in-region bbb)
  7709. (move-marker ins-point bbb))
  7710. (or (bolp) (insert "\n"))
  7711. (setq ins-end (point))
  7712. (goto-char ins-point)
  7713. (org-skip-whitespace)
  7714. (when (and (< arg 0)
  7715. (org-first-sibling-p)
  7716. (> ne-ins ne-beg))
  7717. ;; Move whitespace back to beginning
  7718. (save-excursion
  7719. (goto-char ins-end)
  7720. (let ((kill-whole-line t))
  7721. (kill-line (- ne-ins ne-beg)) (point)))
  7722. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7723. (move-marker ins-point nil)
  7724. (if folded
  7725. (outline-hide-subtree)
  7726. (org-show-entry)
  7727. (org-show-children)
  7728. (org-cycle-hide-drawers 'children))
  7729. (org-clean-visibility-after-subtree-move)
  7730. ;; move back to the initial column we were at
  7731. (move-to-column col)))
  7732. (defvar org-subtree-clip ""
  7733. "Clipboard for cut and paste of subtrees.
  7734. This is actually only a copy of the kill, because we use the normal kill
  7735. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7736. (defvar org-subtree-clip-folded nil
  7737. "Was the last copied subtree folded?
  7738. This is used to fold the tree back after pasting.")
  7739. (defun org-cut-subtree (&optional n)
  7740. "Cut the current subtree into the clipboard.
  7741. With prefix arg N, cut this many sequential subtrees.
  7742. This is a short-hand for marking the subtree and then cutting it."
  7743. (interactive "p")
  7744. (org-copy-subtree n 'cut))
  7745. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7746. "Copy the current subtree it in the clipboard.
  7747. With prefix arg N, copy this many sequential subtrees.
  7748. This is a short-hand for marking the subtree and then copying it.
  7749. If CUT is non-nil, actually cut the subtree.
  7750. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7751. of some markers in the region, even if CUT is non-nil. This is
  7752. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7753. (interactive "p")
  7754. (let (beg end folded (beg0 (point)))
  7755. (if (called-interactively-p 'any)
  7756. (org-back-to-heading nil) ; take what looks like a subtree
  7757. (org-back-to-heading t)) ; take what is really there
  7758. (setq beg (point))
  7759. (skip-chars-forward " \t\r\n")
  7760. (save-match-data
  7761. (if nosubtrees
  7762. (outline-next-heading)
  7763. (save-excursion (outline-end-of-heading)
  7764. (setq folded (outline-invisible-p)))
  7765. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7766. (org-end-of-subtree t t)))
  7767. ;; Include the end of an inlinetask
  7768. (when (and (featurep 'org-inlinetask)
  7769. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7770. "END[ \t]*$")))
  7771. (end-of-line))
  7772. (setq end (point))
  7773. (goto-char beg0)
  7774. (when (> end beg)
  7775. (setq org-subtree-clip-folded folded)
  7776. (when (or cut force-store-markers)
  7777. (org-save-markers-in-region beg end))
  7778. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7779. (setq org-subtree-clip (current-kill 0))
  7780. (message "%s: Subtree(s) with %d characters"
  7781. (if cut "Cut" "Copied")
  7782. (length org-subtree-clip)))))
  7783. (defun org-paste-subtree (&optional level tree for-yank remove)
  7784. "Paste the clipboard as a subtree, with modification of headline level.
  7785. The entire subtree is promoted or demoted in order to match a new headline
  7786. level.
  7787. If the cursor is at the beginning of a headline, the same level as
  7788. that headline is used to paste the tree.
  7789. If not, the new level is derived from the *visible* headings
  7790. before and after the insertion point, and taken to be the inferior headline
  7791. level of the two. So if the previous visible heading is level 3 and the
  7792. next is level 4 (or vice versa), level 4 will be used for insertion.
  7793. This makes sure that the subtree remains an independent subtree and does
  7794. not swallow low level entries.
  7795. You can also force a different level, either by using a numeric prefix
  7796. argument, or by inserting the heading marker by hand. For example, if the
  7797. cursor is after \"*****\", then the tree will be shifted to level 5.
  7798. If optional TREE is given, use this text instead of the kill ring.
  7799. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7800. move back over whitespace before inserting, and move point to the end of
  7801. the inserted text when done.
  7802. When REMOVE is non-nil, remove the subtree from the clipboard."
  7803. (interactive "P")
  7804. (setq tree (or tree (and kill-ring (current-kill 0))))
  7805. (unless (org-kill-is-subtree-p tree)
  7806. (user-error "%s"
  7807. (substitute-command-keys
  7808. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7809. (org-with-limited-levels
  7810. (let* ((visp (not (outline-invisible-p)))
  7811. (txt tree)
  7812. (^re_ "\\(\\*+\\)[ \t]*")
  7813. (old-level (if (string-match org-outline-regexp-bol txt)
  7814. (- (match-end 0) (match-beginning 0) 1)
  7815. -1))
  7816. (force-level (cond (level (prefix-numeric-value level))
  7817. ((and (looking-at "[ \t]*$")
  7818. (string-match
  7819. "^\\*+$" (buffer-substring
  7820. (point-at-bol) (point))))
  7821. (- (match-end 0) (match-beginning 0)))
  7822. ((and (bolp)
  7823. (looking-at org-outline-regexp))
  7824. (- (match-end 0) (point) 1))))
  7825. (previous-level (save-excursion
  7826. (condition-case nil
  7827. (progn
  7828. (outline-previous-visible-heading 1)
  7829. (if (looking-at ^re_)
  7830. (- (match-end 0) (match-beginning 0) 1)
  7831. 1))
  7832. (error 1))))
  7833. (next-level (save-excursion
  7834. (condition-case nil
  7835. (progn
  7836. (or (looking-at org-outline-regexp)
  7837. (outline-next-visible-heading 1))
  7838. (if (looking-at ^re_)
  7839. (- (match-end 0) (match-beginning 0) 1)
  7840. 1))
  7841. (error 1))))
  7842. (new-level (or force-level (max previous-level next-level)))
  7843. (shift (if (or (= old-level -1)
  7844. (= new-level -1)
  7845. (= old-level new-level))
  7846. 0
  7847. (- new-level old-level)))
  7848. (delta (if (> shift 0) -1 1))
  7849. (func (if (> shift 0) 'org-demote 'org-promote))
  7850. (org-odd-levels-only nil)
  7851. beg end newend)
  7852. ;; Remove the forced level indicator
  7853. (when force-level
  7854. (delete-region (point-at-bol) (point)))
  7855. ;; Paste
  7856. (beginning-of-line (if (bolp) 1 2))
  7857. (setq beg (point))
  7858. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7859. (insert-before-markers txt)
  7860. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7861. (setq newend (point))
  7862. (org-reinstall-markers-in-region beg)
  7863. (setq end (point))
  7864. (goto-char beg)
  7865. (skip-chars-forward " \t\n\r")
  7866. (setq beg (point))
  7867. (when (and (outline-invisible-p) visp)
  7868. (save-excursion (outline-show-heading)))
  7869. ;; Shift if necessary
  7870. (unless (= shift 0)
  7871. (save-restriction
  7872. (narrow-to-region beg end)
  7873. (while (not (= shift 0))
  7874. (org-map-region func (point-min) (point-max))
  7875. (setq shift (+ delta shift)))
  7876. (goto-char (point-min))
  7877. (setq newend (point-max))))
  7878. (when (or (called-interactively-p 'interactive) for-yank)
  7879. (message "Clipboard pasted as level %d subtree" new-level))
  7880. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7881. kill-ring
  7882. (eq org-subtree-clip (current-kill 0))
  7883. org-subtree-clip-folded)
  7884. ;; The tree was folded before it was killed/copied
  7885. (outline-hide-subtree))
  7886. (and for-yank (goto-char newend))
  7887. (and remove (setq kill-ring (cdr kill-ring))))))
  7888. (defun org-kill-is-subtree-p (&optional txt)
  7889. "Check if the current kill is an outline subtree, or a set of trees.
  7890. Returns nil if kill does not start with a headline, or if the first
  7891. headline level is not the largest headline level in the tree.
  7892. So this will actually accept several entries of equal levels as well,
  7893. which is OK for `org-paste-subtree'.
  7894. If optional TXT is given, check this string instead of the current kill."
  7895. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7896. (re (org-get-limited-outline-regexp))
  7897. (^re (concat "^" re))
  7898. (start-level (and kill
  7899. (string-match
  7900. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7901. kill)
  7902. (- (match-end 2) (match-beginning 2) 1)))
  7903. (start (1+ (or (match-beginning 2) -1))))
  7904. (if (not start-level)
  7905. (progn
  7906. nil) ;; does not even start with a heading
  7907. (catch 'exit
  7908. (while (setq start (string-match ^re kill (1+ start)))
  7909. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7910. (throw 'exit nil)))
  7911. t))))
  7912. (defvar org-markers-to-move nil
  7913. "Markers that should be moved with a cut-and-paste operation.
  7914. Those markers are stored together with their positions relative to
  7915. the start of the region.")
  7916. (defun org-save-markers-in-region (beg end)
  7917. "Check markers in region.
  7918. If these markers are between BEG and END, record their position relative
  7919. to BEG, so that after moving the block of text, we can put the markers back
  7920. into place.
  7921. This function gets called just before an entry or tree gets cut from the
  7922. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7923. called immediately, to move the markers with the entries."
  7924. (setq org-markers-to-move nil)
  7925. (when (featurep 'org-clock)
  7926. (org-clock-save-markers-for-cut-and-paste beg end))
  7927. (when (featurep 'org-agenda)
  7928. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7929. (defun org-check-and-save-marker (marker beg end)
  7930. "Check if MARKER is between BEG and END.
  7931. If yes, remember the marker and the distance to BEG."
  7932. (when (and (marker-buffer marker)
  7933. (equal (marker-buffer marker) (current-buffer))
  7934. (>= marker beg) (< marker end))
  7935. (push (cons marker (- marker beg)) org-markers-to-move)))
  7936. (defun org-reinstall-markers-in-region (beg)
  7937. "Move all remembered markers to their position relative to BEG."
  7938. (dolist (x org-markers-to-move)
  7939. (move-marker (car x) (+ beg (cdr x))))
  7940. (setq org-markers-to-move nil))
  7941. (defun org-narrow-to-subtree ()
  7942. "Narrow buffer to the current subtree."
  7943. (interactive)
  7944. (save-excursion
  7945. (save-match-data
  7946. (org-with-limited-levels
  7947. (narrow-to-region
  7948. (progn (org-back-to-heading t) (point))
  7949. (progn (org-end-of-subtree t t)
  7950. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7951. (point)))))))
  7952. (defun org-narrow-to-block ()
  7953. "Narrow buffer to the current block."
  7954. (interactive)
  7955. (let* ((case-fold-search t)
  7956. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7957. "^[ \t]*#\\+end_.*")))
  7958. (if blockp
  7959. (narrow-to-region (car blockp) (cdr blockp))
  7960. (user-error "Not in a block"))))
  7961. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7962. "Clone the task (subtree) at point N times.
  7963. The clones will be inserted as siblings.
  7964. In interactive use, the user will be prompted for the number of
  7965. clones to be produced. If the entry has a timestamp, the user
  7966. will also be prompted for a time shift, which may be a repeater
  7967. as used in time stamps, for example `+3d'. To disable this,
  7968. you can call the function with a universal prefix argument.
  7969. When a valid repeater is given and the entry contains any time
  7970. stamps, the clones will become a sequence in time, with time
  7971. stamps in the subtree shifted for each clone produced. If SHIFT
  7972. is nil or the empty string, time stamps will be left alone. The
  7973. ID property of the original subtree is removed.
  7974. In each clone, all the CLOCK entries will be removed. This
  7975. prevents Org from considering that the clocked times overlap.
  7976. If the original subtree did contain time stamps with a repeater,
  7977. the following will happen:
  7978. - the repeater will be removed in each clone
  7979. - an additional clone will be produced, with the current, unshifted
  7980. date(s) in the entry.
  7981. - the original entry will be placed *after* all the clones, with
  7982. repeater intact.
  7983. - the start days in the repeater in the original entry will be shifted
  7984. to past the last clone.
  7985. In this way you can spell out a number of instances of a repeating task,
  7986. and still retain the repeater to cover future instances of the task.
  7987. As described above, N+1 clones are produced when the original
  7988. subtree has a repeater. Setting N to 0, then, can be used to
  7989. remove the repeater from a subtree and create a shifted clone
  7990. with the original repeater."
  7991. (interactive "nNumber of clones to produce: ")
  7992. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7993. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7994. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7995. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7996. (shift
  7997. (or shift
  7998. (if (and (not (equal current-prefix-arg '(4)))
  7999. (save-excursion
  8000. (goto-char beg)
  8001. (re-search-forward org-ts-regexp-both end-of-tree t)))
  8002. (read-from-minibuffer
  8003. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  8004. ""))) ;No time shift
  8005. (doshift
  8006. (and (org-string-nw-p shift)
  8007. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  8008. shift)
  8009. (user-error "Invalid shift specification %s" shift)))))
  8010. (goto-char end-of-tree)
  8011. (unless (bolp) (insert "\n"))
  8012. (let* ((end (point))
  8013. (template (buffer-substring beg end))
  8014. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  8015. (shift-what (pcase (and doshift (match-string 2 shift))
  8016. (`nil nil)
  8017. ("d" 'day)
  8018. ("w" (setq shift-n (* 7 shift-n)) 'day)
  8019. ("m" 'month)
  8020. ("y" 'year)
  8021. (_ (error "Unsupported time unit"))))
  8022. (nmin 1)
  8023. (nmax n)
  8024. (n-no-remove -1)
  8025. (idprop (org-entry-get nil "ID")))
  8026. (when (and doshift
  8027. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  8028. template))
  8029. (delete-region beg end)
  8030. (setq end beg)
  8031. (setq nmin 0)
  8032. (setq nmax (1+ nmax))
  8033. (setq n-no-remove nmax))
  8034. (goto-char end)
  8035. (cl-loop for n from nmin to nmax do
  8036. (insert
  8037. ;; Prepare clone.
  8038. (with-temp-buffer
  8039. (insert template)
  8040. (org-mode)
  8041. (goto-char (point-min))
  8042. (org-show-subtree)
  8043. (and idprop (if org-clone-delete-id
  8044. (org-entry-delete nil "ID")
  8045. (org-id-get-create t)))
  8046. (unless (= n 0)
  8047. (while (re-search-forward org-clock-line-re nil t)
  8048. (delete-region (line-beginning-position)
  8049. (line-beginning-position 2)))
  8050. (goto-char (point-min))
  8051. (while (re-search-forward org-drawer-regexp nil t)
  8052. (org-remove-empty-drawer-at (point))))
  8053. (goto-char (point-min))
  8054. (when doshift
  8055. (while (re-search-forward org-ts-regexp-both nil t)
  8056. (org-timestamp-change (* n shift-n) shift-what))
  8057. (unless (= n n-no-remove)
  8058. (goto-char (point-min))
  8059. (while (re-search-forward org-ts-regexp nil t)
  8060. (save-excursion
  8061. (goto-char (match-beginning 0))
  8062. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8063. (delete-region (match-beginning 1) (match-end 1)))))))
  8064. (buffer-string)))))
  8065. (goto-char beg)))
  8066. ;;; Outline Sorting
  8067. (defun org-sort (with-case)
  8068. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8069. Optional argument WITH-CASE means sort case-sensitively."
  8070. (interactive "P")
  8071. (cond
  8072. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8073. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8074. (t
  8075. (org-call-with-arg 'org-sort-entries with-case))))
  8076. (defun org-sort-remove-invisible (s)
  8077. "Remove invisible links from string S."
  8078. (remove-text-properties 0 (length s) org-rm-props s)
  8079. (while (string-match org-bracket-link-regexp s)
  8080. (setq s (replace-match (if (match-end 2)
  8081. (match-string 3 s)
  8082. (match-string 1 s))
  8083. t t s)))
  8084. (let ((st (format " %s " s)))
  8085. (while (string-match org-emph-re st)
  8086. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8087. (setq s (substring st 1 -1)))
  8088. s)
  8089. (defvar org-priority-regexp) ; defined later in the file
  8090. (defvar org-after-sorting-entries-or-items-hook nil
  8091. "Hook that is run after a bunch of entries or items have been sorted.
  8092. When children are sorted, the cursor is in the parent line when this
  8093. hook gets called. When a region or a plain list is sorted, the cursor
  8094. will be in the first entry of the sorted region/list.")
  8095. (defun org-sort-entries
  8096. (&optional with-case sorting-type getkey-func compare-func property
  8097. interactive?)
  8098. "Sort entries on a certain level of an outline tree.
  8099. If there is an active region, the entries in the region are sorted.
  8100. Else, if the cursor is before the first entry, sort the top-level items.
  8101. Else, the children of the entry at point are sorted.
  8102. Sorting can be alphabetically, numerically, by date/time as given by
  8103. a time stamp, by a property, by priority order, or by a custom function.
  8104. The command prompts for the sorting type unless it has been given to the
  8105. function through the SORTING-TYPE argument, which needs to be a character,
  8106. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8107. the precise meaning of each character:
  8108. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8109. c By creation time, which is assumed to be the first inactive time stamp
  8110. at the beginning of a line.
  8111. d By deadline date/time.
  8112. k By clocking time.
  8113. n Numerically, by converting the beginning of the entry/item to a number.
  8114. o By order of TODO keywords.
  8115. p By priority according to the cookie.
  8116. r By the value of a property.
  8117. s By scheduled date/time.
  8118. t By date/time, either the first active time stamp in the entry, or, if
  8119. none exist, by the first inactive one.
  8120. Capital letters will reverse the sort order.
  8121. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8122. called with point at the beginning of the record. It must return a
  8123. value that is compatible with COMPARE-FUNC, the function used to
  8124. compare entries.
  8125. Comparing entries ignores case by default. However, with an optional argument
  8126. WITH-CASE, the sorting considers case as well.
  8127. Sorting is done against the visible part of the headlines, it ignores hidden
  8128. links.
  8129. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  8130. A non-nil value for INTERACTIVE? is used to signal that this
  8131. function is being called interactively."
  8132. (interactive (list current-prefix-arg nil nil nil nil t))
  8133. (let ((case-func (if with-case 'identity 'downcase))
  8134. (cmstr
  8135. ;; The clock marker is lost when using `sort-subr', let's
  8136. ;; store the clocking string.
  8137. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8138. (save-excursion
  8139. (goto-char org-clock-marker)
  8140. (buffer-substring-no-properties (line-beginning-position)
  8141. (point)))))
  8142. start beg end stars re re2
  8143. txt what tmp)
  8144. ;; Find beginning and end of region to sort
  8145. (cond
  8146. ((org-region-active-p)
  8147. ;; we will sort the region
  8148. (setq end (region-end)
  8149. what "region")
  8150. (goto-char (region-beginning))
  8151. (unless (org-at-heading-p) (outline-next-heading))
  8152. (setq start (point)))
  8153. ((or (org-at-heading-p)
  8154. (ignore-errors (progn (org-back-to-heading) t)))
  8155. ;; we will sort the children of the current headline
  8156. (org-back-to-heading)
  8157. (setq start (point)
  8158. end (progn (org-end-of-subtree t t)
  8159. (or (bolp) (insert "\n"))
  8160. (when (>= (org-back-over-empty-lines) 1)
  8161. (forward-line 1))
  8162. (point))
  8163. what "children")
  8164. (goto-char start)
  8165. (outline-show-subtree)
  8166. (outline-next-heading))
  8167. (t
  8168. ;; we will sort the top-level entries in this file
  8169. (goto-char (point-min))
  8170. (or (org-at-heading-p) (outline-next-heading))
  8171. (setq start (point))
  8172. (goto-char (point-max))
  8173. (beginning-of-line 1)
  8174. (when (looking-at ".*?\\S-")
  8175. ;; File ends in a non-white line
  8176. (end-of-line 1)
  8177. (insert "\n"))
  8178. (setq end (point-max))
  8179. (setq what "top-level")
  8180. (goto-char start)
  8181. (outline-show-all)))
  8182. (setq beg (point))
  8183. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8184. (looking-at "\\(\\*+\\)")
  8185. (setq stars (match-string 1)
  8186. re (concat "^" (regexp-quote stars) " +")
  8187. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8188. txt (buffer-substring beg end))
  8189. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8190. (when (and (not (equal stars "*")) (string-match re2 txt))
  8191. (user-error "Region to sort contains a level above the first entry"))
  8192. (unless sorting-type
  8193. (message
  8194. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8195. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8196. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8197. what)
  8198. (setq sorting-type (read-char-exclusive)))
  8199. (unless getkey-func
  8200. (and (= (downcase sorting-type) ?f)
  8201. (setq getkey-func
  8202. (or (and interactive?
  8203. (org-read-function
  8204. "Function for extracting keys: "))
  8205. (error "Missing key extractor")))))
  8206. (and (= (downcase sorting-type) ?r)
  8207. (not property)
  8208. (setq property
  8209. (completing-read "Property: "
  8210. (mapcar #'list (org-buffer-property-keys t))
  8211. nil t)))
  8212. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8213. (message "Sorting entries...")
  8214. (save-restriction
  8215. (narrow-to-region start end)
  8216. (let ((dcst (downcase sorting-type))
  8217. (case-fold-search nil)
  8218. (now (current-time)))
  8219. (sort-subr
  8220. (/= dcst sorting-type)
  8221. ;; This function moves to the beginning character of the "record" to
  8222. ;; be sorted.
  8223. (lambda nil
  8224. (if (re-search-forward re nil t)
  8225. (goto-char (match-beginning 0))
  8226. (goto-char (point-max))))
  8227. ;; This function moves to the last character of the "record" being
  8228. ;; sorted.
  8229. (lambda nil
  8230. (save-match-data
  8231. (condition-case nil
  8232. (outline-forward-same-level 1)
  8233. (error
  8234. (goto-char (point-max))))))
  8235. ;; This function returns the value that gets sorted against.
  8236. (lambda nil
  8237. (cond
  8238. ((= dcst ?n)
  8239. (if (looking-at org-complex-heading-regexp)
  8240. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8241. nil))
  8242. ((= dcst ?a)
  8243. (if (looking-at org-complex-heading-regexp)
  8244. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8245. nil))
  8246. ((= dcst ?k)
  8247. (or (get-text-property (point) :org-clock-minutes) 0))
  8248. ((= dcst ?t)
  8249. (let ((end (save-excursion (outline-next-heading) (point))))
  8250. (if (or (re-search-forward org-ts-regexp end t)
  8251. (re-search-forward org-ts-regexp-both end t))
  8252. (org-time-string-to-seconds (match-string 0))
  8253. (float-time now))))
  8254. ((= dcst ?c)
  8255. (let ((end (save-excursion (outline-next-heading) (point))))
  8256. (if (re-search-forward
  8257. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8258. end t)
  8259. (org-time-string-to-seconds (match-string 0))
  8260. (float-time now))))
  8261. ((= dcst ?s)
  8262. (let ((end (save-excursion (outline-next-heading) (point))))
  8263. (if (re-search-forward org-scheduled-time-regexp end t)
  8264. (org-time-string-to-seconds (match-string 1))
  8265. (float-time now))))
  8266. ((= dcst ?d)
  8267. (let ((end (save-excursion (outline-next-heading) (point))))
  8268. (if (re-search-forward org-deadline-time-regexp end t)
  8269. (org-time-string-to-seconds (match-string 1))
  8270. (float-time now))))
  8271. ((= dcst ?p)
  8272. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8273. (string-to-char (match-string 2))
  8274. org-default-priority))
  8275. ((= dcst ?r)
  8276. (or (org-entry-get nil property) ""))
  8277. ((= dcst ?o)
  8278. (when (looking-at org-complex-heading-regexp)
  8279. (let* ((m (match-string 2))
  8280. (s (if (member m org-done-keywords) '- '+)))
  8281. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8282. ((= dcst ?f)
  8283. (if getkey-func
  8284. (progn
  8285. (setq tmp (funcall getkey-func))
  8286. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8287. tmp)
  8288. (error "Invalid key function `%s'" getkey-func)))
  8289. (t (error "Invalid sorting type `%c'" sorting-type))))
  8290. nil
  8291. (cond
  8292. ((= dcst ?a) 'string<)
  8293. ((= dcst ?f)
  8294. (or compare-func
  8295. (and interactive?
  8296. (org-read-function
  8297. (concat "Function for comparing keys "
  8298. "(empty for default `sort-subr' predicate): ")
  8299. 'allow-empty))))
  8300. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8301. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8302. ;; Reset the clock marker if needed
  8303. (when cmstr
  8304. (save-excursion
  8305. (goto-char start)
  8306. (search-forward cmstr nil t)
  8307. (move-marker org-clock-marker (point))))
  8308. (message "Sorting entries...done")))
  8309. ;;; The orgstruct minor mode
  8310. ;; Define a minor mode which can be used in other modes in order to
  8311. ;; integrate the Org mode structure editing commands.
  8312. ;; This is really a hack, because the Org mode structure commands use
  8313. ;; keys which normally belong to the major mode. Here is how it
  8314. ;; works: The minor mode defines all the keys necessary to operate the
  8315. ;; structure commands, but wraps the commands into a function which
  8316. ;; tests if the cursor is currently at a headline or a plain list
  8317. ;; item. If that is the case, the structure command is used,
  8318. ;; temporarily setting many Org mode variables like regular
  8319. ;; expressions for filling etc. However, when any of those keys is
  8320. ;; used at a different location, function uses `key-binding' to look
  8321. ;; up if the key has an associated command in another currently active
  8322. ;; keymap (minor modes, major mode, global), and executes that
  8323. ;; command. There might be problems if any of the keys is otherwise
  8324. ;; used as a prefix key.
  8325. (defcustom orgstruct-heading-prefix-regexp ""
  8326. "Regexp that matches the custom prefix of Org headlines in
  8327. orgstruct(++)-mode."
  8328. :group 'org
  8329. :version "24.4"
  8330. :package-version '(Org . "8.3")
  8331. :type 'regexp)
  8332. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8333. (defcustom orgstruct-setup-hook nil
  8334. "Hook run after orgstruct-mode-map is filled."
  8335. :group 'org
  8336. :version "24.4"
  8337. :package-version '(Org . "8.0")
  8338. :type 'hook)
  8339. (defvar orgstruct-initialized nil)
  8340. (defvar org-local-vars nil
  8341. "List of local variables, for use by `orgstruct-mode'.")
  8342. ;;;###autoload
  8343. (define-minor-mode orgstruct-mode
  8344. "Toggle the minor mode `orgstruct-mode'.
  8345. This mode is for using Org mode structure commands in other
  8346. modes. The following keys behave as if Org mode were active, if
  8347. the cursor is on a headline, or on a plain list item (both as
  8348. defined by Org mode)."
  8349. nil " OrgStruct" (make-sparse-keymap)
  8350. (funcall (if orgstruct-mode
  8351. 'add-to-invisibility-spec
  8352. 'remove-from-invisibility-spec)
  8353. '(outline . t))
  8354. (when orgstruct-mode
  8355. (org-load-modules-maybe)
  8356. (unless orgstruct-initialized
  8357. (orgstruct-setup)
  8358. (setq orgstruct-initialized t))))
  8359. ;;;###autoload
  8360. (defun turn-on-orgstruct ()
  8361. "Unconditionally turn on `orgstruct-mode'."
  8362. (orgstruct-mode 1))
  8363. (defvar-local orgstruct-is-++ nil
  8364. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8365. (defvar-local org-fb-vars nil)
  8366. (defun orgstruct++-mode (&optional arg)
  8367. "Toggle `orgstruct-mode', the enhanced version of it.
  8368. In addition to setting orgstruct-mode, this also exports all
  8369. indentation and autofilling variables from Org mode into the
  8370. buffer. It will also recognize item context in multiline items."
  8371. (interactive "P")
  8372. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8373. (if (< arg 1)
  8374. (progn (orgstruct-mode -1)
  8375. (dolist (v org-fb-vars)
  8376. (set (make-local-variable (car v))
  8377. (if (eq (car-safe (cadr v)) 'quote)
  8378. (cl-cadadr v)
  8379. (nth 1 v)))))
  8380. (orgstruct-mode 1)
  8381. (setq org-fb-vars nil)
  8382. (unless org-local-vars
  8383. (setq org-local-vars (org-get-local-variables)))
  8384. (let (var val)
  8385. (dolist (x org-local-vars)
  8386. (when (string-match
  8387. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8388. \\|fill-prefix\\|indent-\\)"
  8389. (symbol-name (car x)))
  8390. (setq var (car x) val (nth 1 x))
  8391. (push (list var `(quote ,(eval var))) org-fb-vars)
  8392. (set (make-local-variable var)
  8393. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8394. (setq-local orgstruct-is-++ t))))
  8395. ;;;###autoload
  8396. (defun turn-on-orgstruct++ ()
  8397. "Unconditionally turn on `orgstruct++-mode'."
  8398. (orgstruct++-mode 1))
  8399. (defun orgstruct-error ()
  8400. "Error when there is no default binding for a structure key."
  8401. (interactive)
  8402. (funcall (if (fboundp 'user-error)
  8403. 'user-error
  8404. 'error)
  8405. "This key has no function outside structure elements"))
  8406. (defun orgstruct-setup ()
  8407. "Setup orgstruct keymap."
  8408. (dolist (cell '((org-demote . t)
  8409. (org-metaleft . t)
  8410. (org-metaright . t)
  8411. (org-promote . t)
  8412. (org-shiftmetaleft . t)
  8413. (org-shiftmetaright . t)
  8414. org-backward-element
  8415. org-backward-heading-same-level
  8416. org-ctrl-c-ret
  8417. org-ctrl-c-minus
  8418. org-ctrl-c-star
  8419. org-cycle
  8420. org-force-cycle-archived
  8421. org-forward-heading-same-level
  8422. org-insert-heading
  8423. org-insert-heading-respect-content
  8424. org-kill-note-or-show-branches
  8425. org-mark-subtree
  8426. org-meta-return
  8427. org-metadown
  8428. org-metaup
  8429. org-narrow-to-subtree
  8430. org-promote-subtree
  8431. org-reveal
  8432. org-shiftdown
  8433. org-shiftleft
  8434. org-shiftmetadown
  8435. org-shiftmetaup
  8436. org-shiftright
  8437. org-shifttab
  8438. org-shifttab
  8439. org-shiftup
  8440. org-show-children
  8441. org-show-subtree
  8442. org-sort
  8443. org-up-element
  8444. outline-demote
  8445. outline-next-visible-heading
  8446. outline-previous-visible-heading
  8447. outline-promote
  8448. outline-up-heading))
  8449. (let ((f (or (car-safe cell) cell))
  8450. (disable-when-heading-prefix (cdr-safe cell)))
  8451. (when (fboundp f)
  8452. (let ((new-bindings))
  8453. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8454. (where-is-internal f outline-mode-map)))
  8455. (push binding new-bindings)
  8456. ;; TODO use local-function-key-map
  8457. (dolist (rep '(("<tab>" . "TAB")
  8458. ("<return>" . "RET")
  8459. ("<escape>" . "ESC")
  8460. ("<delete>" . "DEL")))
  8461. (setq binding (read-kbd-macro
  8462. (let ((case-fold-search))
  8463. (replace-regexp-in-string
  8464. (regexp-quote (cdr rep))
  8465. (car rep)
  8466. (key-description binding)))))
  8467. (cl-pushnew binding new-bindings :test 'equal)))
  8468. (dolist (binding new-bindings)
  8469. (let ((key (lookup-key orgstruct-mode-map binding)))
  8470. (when (or (not key) (numberp key))
  8471. (ignore-errors
  8472. (org-defkey orgstruct-mode-map
  8473. binding
  8474. (orgstruct-make-binding
  8475. f binding disable-when-heading-prefix))))))))))
  8476. (run-hooks 'orgstruct-setup-hook))
  8477. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8478. "Create a function for binding in the structure minor mode.
  8479. FUN is the command to call inside a table. KEY is the key that
  8480. should be checked in for a command to execute outside of tables.
  8481. Non-nil `disable-when-heading-prefix' means to disable the command
  8482. if `orgstruct-heading-prefix-regexp' is not empty."
  8483. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8484. (let ((nname name)
  8485. (i 0))
  8486. (while (fboundp (intern nname))
  8487. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8488. (setq name (intern nname)))
  8489. (eval
  8490. (let ((bindings '((org-heading-regexp
  8491. (concat "^"
  8492. orgstruct-heading-prefix-regexp
  8493. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8494. (org-outline-regexp
  8495. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8496. (org-outline-regexp-bol
  8497. (concat "^" org-outline-regexp))
  8498. (outline-regexp org-outline-regexp)
  8499. (outline-heading-end-regexp "\n")
  8500. (outline-level 'org-outline-level)
  8501. (outline-heading-alist))))
  8502. `(defun ,name (arg)
  8503. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8504. "Outside of structure, run the binding of `"
  8505. (key-description key) "'."
  8506. (when disable-when-heading-prefix
  8507. (concat
  8508. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8509. "back to the default binding due to limitations of Org's implementation of\n"
  8510. "`" (symbol-name fun) "'.")))
  8511. (interactive "p")
  8512. (let* ((disable
  8513. ,(and disable-when-heading-prefix
  8514. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8515. (fallback
  8516. (or disable
  8517. (not
  8518. (let* ,bindings
  8519. (org-context-p 'headline 'item
  8520. ,(when (memq fun
  8521. '(org-insert-heading
  8522. org-insert-heading-respect-content
  8523. org-meta-return))
  8524. '(when orgstruct-is-++
  8525. 'item-body))))))))
  8526. (if fallback
  8527. (let* ((orgstruct-mode)
  8528. (binding
  8529. (let ((key ,key))
  8530. (catch 'exit
  8531. (dolist
  8532. (rep
  8533. '(nil
  8534. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8535. ("<\\([^>]*\\)return>" . "\\1RET")
  8536. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8537. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8538. nil)
  8539. (when rep
  8540. (setq key (read-kbd-macro
  8541. (let ((case-fold-search))
  8542. (replace-regexp-in-string
  8543. (car rep)
  8544. (cdr rep)
  8545. (key-description key))))))
  8546. (when (key-binding key)
  8547. (throw 'exit (key-binding key))))))))
  8548. (if (keymapp binding)
  8549. (org-set-transient-map binding)
  8550. (let ((func (or binding
  8551. (unless disable
  8552. 'orgstruct-error))))
  8553. (when func
  8554. (call-interactively func)))))
  8555. (org-run-like-in-org-mode
  8556. (lambda ()
  8557. (interactive)
  8558. (let* ,bindings
  8559. (call-interactively ',fun)))))))))
  8560. name))
  8561. (defun org-contextualize-keys (alist contexts)
  8562. "Return valid elements in ALIST depending on CONTEXTS.
  8563. `org-agenda-custom-commands' or `org-capture-templates' are the
  8564. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8565. or `org-capture-templates-contexts' are the associated contexts
  8566. definitions."
  8567. (let ((contexts
  8568. ;; normalize contexts
  8569. (mapcar
  8570. (lambda(c) (cond ((listp (cadr c))
  8571. (list (car c) (car c) (nth 1 c)))
  8572. ((string= "" (cadr c))
  8573. (list (car c) (car c) (nth 2 c)))
  8574. (t c)))
  8575. contexts))
  8576. (a alist) r s)
  8577. ;; loop over all commands or templates
  8578. (dolist (c a)
  8579. (let (vrules repl)
  8580. (cond
  8581. ((not (assoc (car c) contexts))
  8582. (push c r))
  8583. ((and (assoc (car c) contexts)
  8584. (setq vrules (org-contextualize-validate-key
  8585. (car c) contexts)))
  8586. (mapc (lambda (vr)
  8587. (unless (equal (car vr) (cadr vr))
  8588. (setq repl vr)))
  8589. vrules)
  8590. (if (not repl) (push c r)
  8591. (push (cadr repl) s)
  8592. (push
  8593. (cons (car c)
  8594. (cdr (or (assoc (cadr repl) alist)
  8595. (error "Undefined key `%s' as contextual replacement for `%s'"
  8596. (cadr repl) (car c)))))
  8597. r))))))
  8598. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8599. (delq
  8600. nil
  8601. (delete-dups
  8602. (mapcar (lambda (x)
  8603. (let ((tpl (car x)))
  8604. (unless (delq
  8605. nil
  8606. (mapcar (lambda (y)
  8607. (equal y tpl))
  8608. s))
  8609. x)))
  8610. (reverse r))))))
  8611. (defun org-contextualize-validate-key (key contexts)
  8612. "Check CONTEXTS for agenda or capture KEY."
  8613. (let (res)
  8614. (dolist (r contexts)
  8615. (dolist (rr (car (last r)))
  8616. (when
  8617. (and (equal key (car r))
  8618. (if (functionp rr) (funcall rr)
  8619. (or (and (eq (car rr) 'in-file)
  8620. (buffer-file-name)
  8621. (string-match (cdr rr) (buffer-file-name)))
  8622. (and (eq (car rr) 'in-mode)
  8623. (string-match (cdr rr) (symbol-name major-mode)))
  8624. (and (eq (car rr) 'in-buffer)
  8625. (string-match (cdr rr) (buffer-name)))
  8626. (when (and (eq (car rr) 'not-in-file)
  8627. (buffer-file-name))
  8628. (not (string-match (cdr rr) (buffer-file-name))))
  8629. (when (eq (car rr) 'not-in-mode)
  8630. (not (string-match (cdr rr) (symbol-name major-mode))))
  8631. (when (eq (car rr) 'not-in-buffer)
  8632. (not (string-match (cdr rr) (buffer-name)))))))
  8633. (push r res))))
  8634. (delete-dups (delq nil res))))
  8635. (defun org-context-p (&rest contexts)
  8636. "Check if local context is any of CONTEXTS.
  8637. Possible values in the list of contexts are `table', `headline', and `item'."
  8638. (let ((pos (point)))
  8639. (goto-char (point-at-bol))
  8640. (prog1 (or (and (memq 'table contexts)
  8641. (looking-at "[ \t]*|"))
  8642. (and (memq 'headline contexts)
  8643. (looking-at org-outline-regexp))
  8644. (and (memq 'item contexts)
  8645. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8646. (and (memq 'item-body contexts)
  8647. (org-in-item-p)))
  8648. (goto-char pos))))
  8649. (defconst org-unique-local-variables
  8650. '(org-element--cache
  8651. org-element--cache-objects
  8652. org-element--cache-sync-keys
  8653. org-element--cache-sync-requests
  8654. org-element--cache-sync-timer)
  8655. "List of local variables that cannot be transferred to another buffer.")
  8656. (defun org-get-local-variables ()
  8657. "Return a list of all local variables in an Org mode buffer."
  8658. (delq nil
  8659. (mapcar
  8660. (lambda (x)
  8661. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8662. (name (car binding)))
  8663. (and (not (get name 'org-state))
  8664. (not (memq name org-unique-local-variables))
  8665. (string-match-p
  8666. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8667. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8668. (symbol-name name))
  8669. binding)))
  8670. (with-temp-buffer
  8671. (org-mode)
  8672. (buffer-local-variables)))))
  8673. (defun org-clone-local-variables (from-buffer &optional regexp)
  8674. "Clone local variables from FROM-BUFFER.
  8675. Optional argument REGEXP selects variables to clone."
  8676. (dolist (pair (buffer-local-variables from-buffer))
  8677. (let ((name (car pair)))
  8678. (when (and (symbolp name)
  8679. (not (memq name org-unique-local-variables))
  8680. (or (null regexp) (string-match regexp (symbol-name name))))
  8681. (set (make-local-variable name) (cdr pair))))))
  8682. ;;;###autoload
  8683. (defun org-run-like-in-org-mode (cmd)
  8684. "Run a command, pretending that the current buffer is in Org mode.
  8685. This will temporarily bind local variables that are typically bound in
  8686. Org mode to the values they have in Org mode, and then interactively
  8687. call CMD."
  8688. (org-load-modules-maybe)
  8689. (unless org-local-vars
  8690. (setq org-local-vars (org-get-local-variables)))
  8691. (let (binds)
  8692. (dolist (var org-local-vars)
  8693. (when (or (not (boundp (car var)))
  8694. (eq (symbol-value (car var))
  8695. (default-value (car var))))
  8696. (push (list (car var) `(quote ,(cadr var))) binds)))
  8697. (eval `(let ,binds
  8698. (call-interactively (quote ,cmd))))))
  8699. (defun org-get-category (&optional pos force-refresh)
  8700. "Get the category applying to position POS."
  8701. (save-match-data
  8702. (when force-refresh (org-refresh-category-properties))
  8703. (let ((pos (or pos (point))))
  8704. (or (get-text-property pos 'org-category)
  8705. (progn (org-refresh-category-properties)
  8706. (get-text-property pos 'org-category))))))
  8707. ;;; Refresh properties
  8708. (defun org-refresh-properties (dprop tprop)
  8709. "Refresh buffer text properties.
  8710. DPROP is the drawer property and TPROP is either the
  8711. corresponding text property to set, or an alist with each element
  8712. being a text property (as a symbol) and a function to apply to
  8713. the value of the drawer property."
  8714. (let* ((case-fold-search t)
  8715. (inhibit-read-only t)
  8716. (inherit? (org-property-inherit-p dprop))
  8717. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8718. (global (and inherit? (org--property-global-value dprop nil))))
  8719. (org-with-silent-modifications
  8720. (org-with-point-at 1
  8721. ;; Set global values (e.g., values defined through
  8722. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8723. (when global (put-text-property (point-min) (point-max) tprop global))
  8724. ;; Set local values.
  8725. (while (re-search-forward property-re nil t)
  8726. (when (org-at-property-p)
  8727. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8728. (outline-next-heading))))))
  8729. (defun org-refresh-property (tprop p &optional inherit)
  8730. "Refresh the buffer text property TPROP from the drawer property P.
  8731. The refresh happens only for the current headline, or the whole
  8732. sub-tree if optional argument INHERIT is non-nil."
  8733. (unless (org-before-first-heading-p)
  8734. (save-excursion
  8735. (org-back-to-heading t)
  8736. (let ((start (point))
  8737. (end (save-excursion
  8738. (if inherit (org-end-of-subtree t t)
  8739. (or (outline-next-heading) (point-max))))))
  8740. (if (symbolp tprop)
  8741. ;; TPROP is a text property symbol.
  8742. (put-text-property start end tprop p)
  8743. ;; TPROP is an alist with (property . function) elements.
  8744. (pcase-dolist (`(,prop . ,f) tprop)
  8745. (put-text-property start end prop (funcall f p))))))))
  8746. (defun org-refresh-category-properties ()
  8747. "Refresh category text properties in the buffer."
  8748. (let ((case-fold-search t)
  8749. (inhibit-read-only t)
  8750. (default-category
  8751. (cond ((null org-category)
  8752. (if buffer-file-name
  8753. (file-name-sans-extension
  8754. (file-name-nondirectory buffer-file-name))
  8755. "???"))
  8756. ((symbolp org-category) (symbol-name org-category))
  8757. (t org-category))))
  8758. (org-with-silent-modifications
  8759. (org-with-wide-buffer
  8760. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8761. ;; This is the default category for the buffer. If none is
  8762. ;; found, fall-back to `org-category' or buffer file name.
  8763. (put-text-property
  8764. (point-min) (point-max)
  8765. 'org-category
  8766. (catch 'buffer-category
  8767. (goto-char (point-max))
  8768. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8769. (let ((element (org-element-at-point)))
  8770. (when (eq (org-element-type element) 'keyword)
  8771. (throw 'buffer-category
  8772. (org-element-property :value element)))))
  8773. default-category))
  8774. ;; Set sub-tree specific categories.
  8775. (goto-char (point-min))
  8776. (let ((regexp (org-re-property "CATEGORY")))
  8777. (while (re-search-forward regexp nil t)
  8778. (let ((value (match-string-no-properties 3)))
  8779. (when (org-at-property-p)
  8780. (put-text-property
  8781. (save-excursion (org-back-to-heading t) (point))
  8782. (save-excursion (org-end-of-subtree t t) (point))
  8783. 'org-category
  8784. value)))))))))
  8785. (defun org-refresh-stats-properties ()
  8786. "Refresh stats text properties in the buffer."
  8787. (org-with-silent-modifications
  8788. (org-with-point-at 1
  8789. (let ((regexp (concat org-outline-regexp-bol
  8790. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8791. (while (re-search-forward regexp nil t)
  8792. (let* ((numerator (string-to-number (match-string 1)))
  8793. (denominator (and (match-end 2)
  8794. (string-to-number (match-string 2))))
  8795. (stats (cond ((not denominator) numerator) ;percent
  8796. ((= denominator 0) 0)
  8797. (t (/ (* numerator 100) denominator)))))
  8798. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8799. 'org-stats stats)))))))
  8800. (defun org-refresh-effort-properties ()
  8801. "Refresh effort properties"
  8802. (org-refresh-properties
  8803. org-effort-property
  8804. '((effort . identity)
  8805. (effort-minutes . org-duration-string-to-minutes))))
  8806. ;;;; Link Stuff
  8807. ;;; Link abbreviations
  8808. (defun org-link-expand-abbrev (link)
  8809. "Apply replacements as defined in `org-link-abbrev-alist'."
  8810. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8811. (let* ((key (match-string 1 link))
  8812. (as (or (assoc key org-link-abbrev-alist-local)
  8813. (assoc key org-link-abbrev-alist)))
  8814. (tag (and (match-end 2) (match-string 3 link)))
  8815. rpl)
  8816. (if (not as)
  8817. link
  8818. (setq rpl (cdr as))
  8819. (cond
  8820. ((symbolp rpl) (funcall rpl tag))
  8821. ((string-match "%(\\([^)]+\\))" rpl)
  8822. (replace-match
  8823. (save-match-data
  8824. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8825. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8826. ((string-match "%h" rpl)
  8827. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8828. (t (concat rpl tag)))))
  8829. link))
  8830. ;;; Storing and inserting links
  8831. (defvar org-insert-link-history nil
  8832. "Minibuffer history for links inserted with `org-insert-link'.")
  8833. (defvar org-stored-links nil
  8834. "Contains the links stored with `org-store-link'.")
  8835. (defvar org-store-link-plist nil
  8836. "Plist with info about the most recently link created with `org-store-link'.")
  8837. (defun org-store-link-functions ()
  8838. "Return a list of functions that are called to create and store a link.
  8839. The functions defined in the :store property of
  8840. `org-link-parameters'.
  8841. Each function will be called in turn until one returns a non-nil
  8842. value. Each function should check if it is responsible for
  8843. creating this link (for example by looking at the major mode).
  8844. If not, it must exit and return nil. If yes, it should return
  8845. a non-nil value after calling `org-store-link-props' with a list
  8846. of properties and values. Special properties are:
  8847. :type The link prefix, like \"http\". This must be given.
  8848. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8849. This is obligatory as well.
  8850. :description Optional default description for the second pair
  8851. of brackets in an Org mode link. The user can still change
  8852. this when inserting this link into an Org mode buffer.
  8853. In addition to these, any additional properties can be specified
  8854. and then used in capture templates."
  8855. (cl-loop for link in org-link-parameters
  8856. with store-func
  8857. do (setq store-func (org-link-get-parameter (car link) :store))
  8858. if store-func
  8859. collect store-func))
  8860. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8861. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8862. ;;;###autoload
  8863. (defun org-store-link (arg)
  8864. "Store an org-link to the current location.
  8865. \\<org-mode-map>
  8866. This link is added to `org-stored-links' and can later be inserted
  8867. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8868. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8869. A single
  8870. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8871. `org-gnus-prefer-web-links' for links to Usenet articles.
  8872. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8873. skipping storing functions that are not
  8874. part of Org core.
  8875. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8876. prefix ARG forces storing a link for each line in the
  8877. active region."
  8878. (interactive "P")
  8879. (org-load-modules-maybe)
  8880. (if (and (equal arg '(64)) (org-region-active-p))
  8881. (save-excursion
  8882. (let ((end (region-end)))
  8883. (goto-char (region-beginning))
  8884. (set-mark (point))
  8885. (while (< (point-at-eol) end)
  8886. (move-end-of-line 1) (activate-mark)
  8887. (let (current-prefix-arg)
  8888. (call-interactively 'org-store-link))
  8889. (move-beginning-of-line 2)
  8890. (set-mark (point)))))
  8891. (setq org-store-link-plist nil)
  8892. (let (link cpltxt desc description search
  8893. txt custom-id agenda-link sfuns sfunsn)
  8894. (cond
  8895. ;; Store a link using an external link type
  8896. ((and (not (equal arg '(16)))
  8897. (setq sfuns
  8898. (delq
  8899. nil (mapcar (lambda (f)
  8900. (let (fs) (if (funcall f) (push f fs))))
  8901. (org-store-link-functions)))
  8902. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8903. (or (and (cdr sfuns)
  8904. (funcall (intern
  8905. (completing-read
  8906. "Which function for creating the link? "
  8907. sfunsn nil t (car sfunsn)))))
  8908. (funcall (caar sfuns)))
  8909. (setq link (plist-get org-store-link-plist :link)
  8910. desc (or (plist-get org-store-link-plist
  8911. :description)
  8912. link))))
  8913. ;; Store a link from a source code buffer.
  8914. ((org-src-edit-buffer-p)
  8915. (let ((coderef-format (org-src-coderef-format)))
  8916. (cond ((save-excursion
  8917. (beginning-of-line)
  8918. (looking-at (org-src-coderef-regexp coderef-format)))
  8919. (setq link (format "(%s)" (match-string-no-properties 3))))
  8920. ((called-interactively-p 'any)
  8921. (let ((label (read-string "Code line label: ")))
  8922. (end-of-line)
  8923. (setq link (format coderef-format label))
  8924. (let ((gc (- 79 (length link))))
  8925. (if (< (current-column) gc)
  8926. (org-move-to-column gc t)
  8927. (insert " ")))
  8928. (insert link)
  8929. (setq link (concat "(" label ")"))
  8930. (setq desc nil)))
  8931. (t (setq link nil)))))
  8932. ;; We are in the agenda, link to referenced location
  8933. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8934. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8935. (get-text-property (point) 'org-marker))))
  8936. (when m
  8937. (org-with-point-at m
  8938. (setq agenda-link
  8939. (if (called-interactively-p 'any)
  8940. (call-interactively 'org-store-link)
  8941. (org-store-link nil)))))))
  8942. ((eq major-mode 'calendar-mode)
  8943. (let ((cd (calendar-cursor-to-date)))
  8944. (setq link
  8945. (format-time-string
  8946. (car org-time-stamp-formats)
  8947. (apply 'encode-time
  8948. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8949. nil nil nil))))
  8950. (org-store-link-props :type "calendar" :date cd)))
  8951. ((eq major-mode 'help-mode)
  8952. (setq link (concat "help:" (save-excursion
  8953. (goto-char (point-min))
  8954. (looking-at "^[^ ]+")
  8955. (match-string 0))))
  8956. (org-store-link-props :type "help"))
  8957. ((eq major-mode 'w3-mode)
  8958. (setq cpltxt (if (and (buffer-name)
  8959. (not (string-match "Untitled" (buffer-name))))
  8960. (buffer-name)
  8961. (url-view-url t))
  8962. link (url-view-url t))
  8963. (org-store-link-props :type "w3" :url (url-view-url t)))
  8964. ((eq major-mode 'image-mode)
  8965. (setq cpltxt (concat "file:"
  8966. (abbreviate-file-name buffer-file-name))
  8967. link cpltxt)
  8968. (org-store-link-props :type "image" :file buffer-file-name))
  8969. ;; In dired, store a link to the file of the current line
  8970. ((derived-mode-p 'dired-mode)
  8971. (let ((file (dired-get-filename nil t)))
  8972. (setq file (if file
  8973. (abbreviate-file-name
  8974. (expand-file-name (dired-get-filename nil t)))
  8975. ;; otherwise, no file so use current directory.
  8976. default-directory))
  8977. (setq cpltxt (concat "file:" file)
  8978. link cpltxt)))
  8979. ((setq search (run-hook-with-args-until-success
  8980. 'org-create-file-search-functions))
  8981. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8982. "::" search))
  8983. (setq cpltxt (or description link)))
  8984. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8985. (org-with-limited-levels
  8986. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8987. (cond
  8988. ;; Store a link using the target at point
  8989. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8990. (setq cpltxt
  8991. (concat "file:"
  8992. (abbreviate-file-name
  8993. (buffer-file-name (buffer-base-buffer)))
  8994. "::" (match-string 1))
  8995. link cpltxt))
  8996. ((and (featurep 'org-id)
  8997. (or (eq org-id-link-to-org-use-id t)
  8998. (and (called-interactively-p 'any)
  8999. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  9000. (and (eq org-id-link-to-org-use-id
  9001. 'create-if-interactive-and-no-custom-id)
  9002. (not custom-id))))
  9003. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  9004. ;; Store a link using the ID at point
  9005. (setq link (condition-case nil
  9006. (prog1 (org-id-store-link)
  9007. (setq desc (or (plist-get org-store-link-plist
  9008. :description)
  9009. "")))
  9010. (error
  9011. ;; Probably before first headline, link only to file
  9012. (concat "file:"
  9013. (abbreviate-file-name
  9014. (buffer-file-name (buffer-base-buffer))))))))
  9015. (t
  9016. ;; Just link to current headline
  9017. (setq cpltxt (concat "file:"
  9018. (abbreviate-file-name
  9019. (buffer-file-name (buffer-base-buffer)))))
  9020. ;; Add a context search string
  9021. (when (org-xor org-context-in-file-links
  9022. (equal arg '(4)))
  9023. (let* ((element (org-element-at-point))
  9024. (name (org-element-property :name element)))
  9025. (setq txt (cond
  9026. ((org-at-heading-p) nil)
  9027. (name)
  9028. ((org-region-active-p)
  9029. (buffer-substring (region-beginning) (region-end)))))
  9030. (when (or (null txt) (string-match "\\S-" txt))
  9031. (setq cpltxt
  9032. (concat cpltxt "::"
  9033. (condition-case nil
  9034. (org-make-org-heading-search-string txt)
  9035. (error "")))
  9036. desc (or name
  9037. (nth 4 (ignore-errors (org-heading-components)))
  9038. "NONE")))))
  9039. (when (string-match "::\\'" cpltxt)
  9040. (setq cpltxt (substring cpltxt 0 -2)))
  9041. (setq link cpltxt)))))
  9042. ((buffer-file-name (buffer-base-buffer))
  9043. ;; Just link to this file here.
  9044. (setq cpltxt (concat "file:"
  9045. (abbreviate-file-name
  9046. (buffer-file-name (buffer-base-buffer)))))
  9047. ;; Add a context string.
  9048. (when (org-xor org-context-in-file-links
  9049. (equal arg '(4)))
  9050. (setq txt (if (org-region-active-p)
  9051. (buffer-substring (region-beginning) (region-end))
  9052. (buffer-substring (point-at-bol) (point-at-eol))))
  9053. ;; Only use search option if there is some text.
  9054. (when (string-match "\\S-" txt)
  9055. (setq cpltxt
  9056. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  9057. desc "NONE")))
  9058. (setq link cpltxt))
  9059. ((called-interactively-p 'interactive)
  9060. (user-error "No method for storing a link from this buffer"))
  9061. (t (setq link nil)))
  9062. ;; We're done setting link and desc, clean up
  9063. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9064. (setq link (or link cpltxt)
  9065. desc (or desc cpltxt))
  9066. (cond ((not desc))
  9067. ((equal desc "NONE") (setq desc nil))
  9068. (t (setq desc
  9069. (replace-regexp-in-string
  9070. org-bracket-link-analytic-regexp
  9071. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9072. desc))))
  9073. ;; Return the link
  9074. (if (not (and (or (called-interactively-p 'any)
  9075. executing-kbd-macro)
  9076. link))
  9077. (or agenda-link (and link (org-make-link-string link desc)))
  9078. (push (list link desc) org-stored-links)
  9079. (message "Stored: %s" (or desc link))
  9080. (when custom-id
  9081. (setq link (concat "file:" (abbreviate-file-name
  9082. (buffer-file-name)) "::#" custom-id))
  9083. (push (list link desc) org-stored-links))
  9084. (car org-stored-links)))))
  9085. (defun org-store-link-props (&rest plist)
  9086. "Store link properties, extract names, addresses and dates."
  9087. (let ((x (plist-get plist :from)))
  9088. (when x
  9089. (let ((adr (mail-extract-address-components x)))
  9090. (setq plist (plist-put plist :fromname (car adr)))
  9091. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9092. (let ((x (plist-get plist :to)))
  9093. (when x
  9094. (let ((adr (mail-extract-address-components x)))
  9095. (setq plist (plist-put plist :toname (car adr)))
  9096. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9097. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9098. (when x
  9099. (setq plist (plist-put plist :date-timestamp
  9100. (format-time-string
  9101. (org-time-stamp-format t) x)))
  9102. (setq plist (plist-put plist :date-timestamp-inactive
  9103. (format-time-string
  9104. (org-time-stamp-format t t) x)))))
  9105. (let ((from (plist-get plist :from))
  9106. (to (plist-get plist :to)))
  9107. (when (and from to org-from-is-user-regexp)
  9108. (setq plist
  9109. (plist-put plist :fromto
  9110. (if (string-match org-from-is-user-regexp from)
  9111. (concat "to %t")
  9112. (concat "from %f"))))))
  9113. (setq org-store-link-plist plist))
  9114. (defun org-add-link-props (&rest plist)
  9115. "Add these properties to the link property list."
  9116. (let (key value)
  9117. (while plist
  9118. (setq key (pop plist) value (pop plist))
  9119. (setq org-store-link-plist
  9120. (plist-put org-store-link-plist key value)))))
  9121. (defun org-email-link-description (&optional fmt)
  9122. "Return the description part of an email link.
  9123. This takes information from `org-store-link-plist' and formats it
  9124. according to FMT (default from `org-email-link-description-format')."
  9125. (setq fmt (or fmt org-email-link-description-format))
  9126. (let* ((p org-store-link-plist)
  9127. (to (plist-get p :toaddress))
  9128. (from (plist-get p :fromaddress))
  9129. (table
  9130. (list
  9131. (cons "%c" (plist-get p :fromto))
  9132. (cons "%F" (plist-get p :from))
  9133. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9134. (cons "%T" (plist-get p :to))
  9135. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9136. (cons "%s" (plist-get p :subject))
  9137. (cons "%d" (plist-get p :date))
  9138. (cons "%m" (plist-get p :message-id)))))
  9139. (when (string-match "%c" fmt)
  9140. ;; Check if the user wrote this message
  9141. (if (and org-from-is-user-regexp from to
  9142. (save-match-data (string-match org-from-is-user-regexp from)))
  9143. (setq fmt (replace-match "to %t" t t fmt))
  9144. (setq fmt (replace-match "from %f" t t fmt))))
  9145. (org-replace-escapes fmt table)))
  9146. (defun org-make-org-heading-search-string (&optional string)
  9147. "Make search string for the current headline or STRING."
  9148. (let ((s (or string
  9149. (and (derived-mode-p 'org-mode)
  9150. (save-excursion
  9151. (org-back-to-heading t)
  9152. (org-element-property :raw-value (org-element-at-point))))))
  9153. (lines org-context-in-file-links))
  9154. (or string (setq s (concat "*" s))) ; Add * for headlines
  9155. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9156. (when (and string (integerp lines) (> lines 0))
  9157. (let ((slines (org-split-string s "\n")))
  9158. (when (< lines (length slines))
  9159. (setq s (mapconcat
  9160. 'identity
  9161. (reverse (nthcdr (- (length slines) lines)
  9162. (reverse slines))) "\n")))))
  9163. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9164. (defun org-make-link-string (link &optional description)
  9165. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9166. (unless (org-string-nw-p link) (error "Empty link"))
  9167. (let ((uri (cond ((string-match org-link-types-re link)
  9168. (concat (match-string 1 link)
  9169. (org-link-escape (substring link (match-end 1)))))
  9170. ;; For readability, url-encode internal links only
  9171. ;; when absolutely needed (i.e, when they contain
  9172. ;; square brackets). File links however, are
  9173. ;; encoded since, e.g., spaces are significant.
  9174. ((or (file-name-absolute-p link)
  9175. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9176. (org-link-escape link))
  9177. (t link)))
  9178. (description
  9179. (and (org-string-nw-p description)
  9180. ;; Remove brackets from description, as they are fatal.
  9181. (replace-regexp-in-string
  9182. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9183. (org-trim description)))))
  9184. (format "[[%s]%s]"
  9185. uri
  9186. (if description (format "[%s]" description) ""))))
  9187. (defconst org-link-escape-chars
  9188. ;;%20 %5B %5D %25
  9189. '(?\s ?\[ ?\] ?%)
  9190. "List of characters that should be escaped in a link when stored to Org.
  9191. This is the list that is used for internal purposes.")
  9192. (defun org-link-escape (text &optional table merge)
  9193. "Return percent escaped representation of TEXT.
  9194. TEXT is a string with the text to escape.
  9195. Optional argument TABLE is a list with characters that should be
  9196. escaped. When nil, `org-link-escape-chars' is used.
  9197. If optional argument MERGE is set, merge TABLE into
  9198. `org-link-escape-chars'."
  9199. (let ((characters-to-encode
  9200. (cond ((null table) org-link-escape-chars)
  9201. (merge (append org-link-escape-chars table))
  9202. (t table))))
  9203. (mapconcat
  9204. (lambda (c)
  9205. (if (or (memq c characters-to-encode)
  9206. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9207. (mapconcat (lambda (e) (format "%%%.2X" e))
  9208. (or (encode-coding-char c 'utf-8)
  9209. (error "Unable to percent escape character: %c" c))
  9210. "")
  9211. (char-to-string c)))
  9212. text "")))
  9213. (defun org-link-unescape (str)
  9214. "Unhex hexified Unicode parts in string STR.
  9215. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9216. reciprocal of `org-link-escape', which see."
  9217. (if (org-string-nw-p str)
  9218. (replace-regexp-in-string
  9219. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9220. str))
  9221. (defun org-link-unescape-compound (hex)
  9222. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9223. Note: this function also decodes single byte encodings like
  9224. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9225. (save-match-data
  9226. (let* ((bytes (cdr (split-string hex "%")))
  9227. (ret "")
  9228. (eat 0)
  9229. (sum 0))
  9230. (while bytes
  9231. (let* ((val (string-to-number (pop bytes) 16))
  9232. (shift-xor
  9233. (if (= 0 eat)
  9234. (cond
  9235. ((>= val 252) (cons 6 252))
  9236. ((>= val 248) (cons 5 248))
  9237. ((>= val 240) (cons 4 240))
  9238. ((>= val 224) (cons 3 224))
  9239. ((>= val 192) (cons 2 192))
  9240. (t (cons 0 0)))
  9241. (cons 6 128))))
  9242. (when (>= val 192) (setq eat (car shift-xor)))
  9243. (setq val (logxor val (cdr shift-xor)))
  9244. (setq sum (+ (lsh sum (car shift-xor)) val))
  9245. (when (> eat 0) (setq eat (- eat 1)))
  9246. (cond
  9247. ((= 0 eat) ;multi byte
  9248. (setq ret (concat ret (char-to-string sum)))
  9249. (setq sum 0))
  9250. ((not bytes) ; single byte(s)
  9251. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9252. ret)))
  9253. (defun org-link-unescape-single-byte-sequence (hex)
  9254. "Unhexify hex-encoded single byte character sequences."
  9255. (mapconcat (lambda (byte)
  9256. (char-to-string (string-to-number byte 16)))
  9257. (cdr (split-string hex "%")) ""))
  9258. (defun org-xor (a b)
  9259. "Exclusive or."
  9260. (if a (not b) b))
  9261. (defun org-fixup-message-id-for-http (s)
  9262. "Replace special characters in a message id, so it can be used in an http query."
  9263. (when (string-match "%" s)
  9264. (setq s (mapconcat (lambda (c)
  9265. (if (eq c ?%)
  9266. "%25"
  9267. (char-to-string c)))
  9268. s "")))
  9269. (while (string-match "<" s)
  9270. (setq s (replace-match "%3C" t t s)))
  9271. (while (string-match ">" s)
  9272. (setq s (replace-match "%3E" t t s)))
  9273. (while (string-match "@" s)
  9274. (setq s (replace-match "%40" t t s)))
  9275. s)
  9276. (defun org-link-prettify (link)
  9277. "Return a human-readable representation of LINK.
  9278. The car of LINK must be a raw link.
  9279. The cdr of LINK must be either a link description or nil."
  9280. (let ((desc (or (cadr link) "<no description>")))
  9281. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9282. "<" (car link) ">")))
  9283. ;;;###autoload
  9284. (defun org-insert-link-global ()
  9285. "Insert a link like Org mode does.
  9286. This command can be called in any mode to insert a link in Org syntax."
  9287. (interactive)
  9288. (org-load-modules-maybe)
  9289. (org-run-like-in-org-mode 'org-insert-link))
  9290. (defun org-insert-all-links (arg &optional pre post)
  9291. "Insert all links in `org-stored-links'.
  9292. When a universal prefix, do not delete the links from `org-stored-links'.
  9293. When `ARG' is a number, insert the last N link(s).
  9294. `PRE' and `POST' are optional arguments to define a string to
  9295. prepend or to append."
  9296. (interactive "P")
  9297. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9298. (links (copy-sequence org-stored-links))
  9299. (pr (or pre "- "))
  9300. (po (or post "\n"))
  9301. (cnt 1) l)
  9302. (if (null org-stored-links)
  9303. (message "No link to insert")
  9304. (while (and (or (listp arg) (>= arg cnt))
  9305. (setq l (if (listp arg)
  9306. (pop links)
  9307. (pop org-stored-links))))
  9308. (setq cnt (1+ cnt))
  9309. (insert pr)
  9310. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9311. (insert po)))))
  9312. (defun org-insert-last-stored-link (arg)
  9313. "Insert the last link stored in `org-stored-links'."
  9314. (interactive "p")
  9315. (org-insert-all-links arg "" "\n"))
  9316. (defun org-link-fontify-links-to-this-file ()
  9317. "Fontify links to the current file in `org-stored-links'."
  9318. (let ((f (buffer-file-name)) a b)
  9319. (setq a (mapcar (lambda(l)
  9320. (let ((ll (car l)))
  9321. (when (and (string-match "^file:\\(.+\\)::" ll)
  9322. (equal f (expand-file-name (match-string 1 ll))))
  9323. ll)))
  9324. org-stored-links))
  9325. (when (featurep 'org-id)
  9326. (setq b (mapcar (lambda(l)
  9327. (let ((ll (car l)))
  9328. (when (and (string-match "^id:\\(.+\\)$" ll)
  9329. (equal f (expand-file-name
  9330. (or (org-id-find-id-file
  9331. (match-string 1 ll)) ""))))
  9332. ll)))
  9333. org-stored-links)))
  9334. (mapcar (lambda(l)
  9335. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9336. (delq nil (append a b)))))
  9337. (defvar org--links-history nil)
  9338. (defun org-insert-link (&optional complete-file link-location default-description)
  9339. "Insert a link. At the prompt, enter the link.
  9340. Completion can be used to insert any of the link protocol prefixes in use.
  9341. The history can be used to select a link previously stored with
  9342. `org-store-link'. When the empty string is entered (i.e. if you just
  9343. press `RET' at the prompt), the link defaults to the most recently
  9344. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9345. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9346. You will also be prompted for a description, and if one is given, it will
  9347. be displayed in the buffer instead of the link.
  9348. If there is already a link at point, this command will allow you to edit
  9349. link and description parts.
  9350. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9351. file name can be
  9352. selected using completion. The path to the file will be relative to the
  9353. current directory if the file is in the current directory or a subdirectory.
  9354. Otherwise, the link will be the absolute path as completed in the minibuffer
  9355. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9356. option `org-link-file-path-type'.
  9357. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9358. absolute path even if the file is in
  9359. the current directory or below.
  9360. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9361. prefix negates `org-keep-stored-link-after-insertion'.
  9362. If `org-make-link-description-function' is non-nil, this function will be
  9363. called with the link target, and the result will be the default
  9364. link description.
  9365. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9366. the link location instead of reading one interactively.
  9367. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9368. as the default description."
  9369. (interactive "P")
  9370. (let* ((wcf (current-window-configuration))
  9371. (origbuf (current-buffer))
  9372. (region (when (org-region-active-p)
  9373. (buffer-substring (region-beginning) (region-end))))
  9374. (remove (and region (list (region-beginning) (region-end))))
  9375. (desc region)
  9376. (link link-location)
  9377. (abbrevs org-link-abbrev-alist-local)
  9378. entry all-prefixes auto-desc)
  9379. (cond
  9380. (link-location) ; specified by arg, just use it.
  9381. ((org-in-regexp org-bracket-link-regexp 1)
  9382. ;; We do have a link at point, and we are going to edit it.
  9383. (setq remove (list (match-beginning 0) (match-end 0)))
  9384. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9385. (setq link (read-string "Link: "
  9386. (org-link-unescape
  9387. (match-string-no-properties 1)))))
  9388. ((or (org-in-regexp org-angle-link-re)
  9389. (org-in-regexp org-plain-link-re))
  9390. ;; Convert to bracket link
  9391. (setq remove (list (match-beginning 0) (match-end 0))
  9392. link (read-string "Link: "
  9393. (org-unbracket-string "<" ">" (match-string 0)))))
  9394. ((member complete-file '((4) (16)))
  9395. ;; Completing read for file names.
  9396. (setq link (org-file-complete-link complete-file)))
  9397. (t
  9398. ;; Read link, with completion for stored links.
  9399. (org-link-fontify-links-to-this-file)
  9400. (org-switch-to-buffer-other-window "*Org Links*")
  9401. (with-current-buffer "*Org Links*"
  9402. (erase-buffer)
  9403. (insert "Insert a link.
  9404. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9405. (when org-stored-links
  9406. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9407. (insert (mapconcat 'org-link-prettify
  9408. (reverse org-stored-links) "\n")))
  9409. (goto-char (point-min)))
  9410. (let ((cw (selected-window)))
  9411. (select-window (get-buffer-window "*Org Links*" 'visible))
  9412. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9413. (unless (pos-visible-in-window-p (point-max))
  9414. (org-fit-window-to-buffer))
  9415. (and (window-live-p cw) (select-window cw)))
  9416. (setq all-prefixes (append (mapcar 'car abbrevs)
  9417. (mapcar 'car org-link-abbrev-alist)
  9418. (org-link-types)))
  9419. (unwind-protect
  9420. ;; Fake a link history, containing the stored links.
  9421. (let ((org--links-history
  9422. (append (mapcar #'car org-stored-links)
  9423. org-insert-link-history)))
  9424. (setq link
  9425. (org-completing-read
  9426. "Link: "
  9427. (append
  9428. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9429. (mapcar #'car org-stored-links))
  9430. nil nil nil
  9431. 'org--links-history
  9432. (caar org-stored-links)))
  9433. (unless (org-string-nw-p link) (user-error "No link selected"))
  9434. (dolist (l org-stored-links)
  9435. (when (equal link (cadr l))
  9436. (setq link (car l))
  9437. (setq auto-desc t)))
  9438. (when (or (member link all-prefixes)
  9439. (and (equal ":" (substring link -1))
  9440. (member (substring link 0 -1) all-prefixes)
  9441. (setq link (substring link 0 -1))))
  9442. (setq link (with-current-buffer origbuf
  9443. (org-link-try-special-completion link)))))
  9444. (set-window-configuration wcf)
  9445. (kill-buffer "*Org Links*"))
  9446. (setq entry (assoc link org-stored-links))
  9447. (or entry (push link org-insert-link-history))
  9448. (setq desc (or desc (nth 1 entry)))))
  9449. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9450. (not org-keep-stored-link-after-insertion))
  9451. (setq org-stored-links (delq (assoc link org-stored-links)
  9452. org-stored-links)))
  9453. (when (and (string-match org-plain-link-re link)
  9454. (not (string-match org-ts-regexp link)))
  9455. ;; URL-like link, normalize the use of angular brackets.
  9456. (setq link (org-unbracket-string "<" ">" link)))
  9457. ;; Check if we are linking to the current file with a search
  9458. ;; option If yes, simplify the link by using only the search
  9459. ;; option.
  9460. (when (and buffer-file-name
  9461. (let ((case-fold-search nil))
  9462. (string-match "\\`file:\\(.+?\\)::" link)))
  9463. (let ((path (match-string-no-properties 1 link))
  9464. (search (substring-no-properties link (match-end 0))))
  9465. (save-match-data
  9466. (when (equal (file-truename buffer-file-name) (file-truename path))
  9467. ;; We are linking to this same file, with a search option
  9468. (setq link search)))))
  9469. ;; Check if we can/should use a relative path. If yes, simplify the link
  9470. (let ((case-fold-search nil))
  9471. (when (string-match "\\`\\(file\\|docview\\):" link)
  9472. (let* ((type (match-string-no-properties 0 link))
  9473. (path (substring-no-properties link (match-end 0)))
  9474. (origpath path))
  9475. (cond
  9476. ((or (eq org-link-file-path-type 'absolute)
  9477. (equal complete-file '(16)))
  9478. (setq path (abbreviate-file-name (expand-file-name path))))
  9479. ((eq org-link-file-path-type 'noabbrev)
  9480. (setq path (expand-file-name path)))
  9481. ((eq org-link-file-path-type 'relative)
  9482. (setq path (file-relative-name path)))
  9483. (t
  9484. (save-match-data
  9485. (if (string-match (concat "^" (regexp-quote
  9486. (expand-file-name
  9487. (file-name-as-directory
  9488. default-directory))))
  9489. (expand-file-name path))
  9490. ;; We are linking a file with relative path name.
  9491. (setq path (substring (expand-file-name path)
  9492. (match-end 0)))
  9493. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9494. (setq link (concat type path))
  9495. (when (equal desc origpath)
  9496. (setq desc path)))))
  9497. (if org-make-link-description-function
  9498. (setq desc
  9499. (or (condition-case nil
  9500. (funcall org-make-link-description-function link desc)
  9501. (error (progn (message "Can't get link description from `%s'"
  9502. (symbol-name org-make-link-description-function))
  9503. (sit-for 2) nil)))
  9504. (read-string "Description: " default-description)))
  9505. (if default-description (setq desc default-description)
  9506. (setq desc (or (and auto-desc desc)
  9507. (read-string "Description: " desc)))))
  9508. (unless (string-match "\\S-" desc) (setq desc nil))
  9509. (when remove (apply 'delete-region remove))
  9510. (insert (org-make-link-string link desc))
  9511. ;; Redisplay so as the new link has proper invisible characters.
  9512. (sit-for 0)))
  9513. (defun org-link-try-special-completion (type)
  9514. "If there is completion support for link type TYPE, offer it."
  9515. (let ((fun (org-link-get-parameter type :complete)))
  9516. (if (functionp fun)
  9517. (funcall fun)
  9518. (read-string "Link (no completion support): " (concat type ":")))))
  9519. (defun org-file-complete-link (&optional arg)
  9520. "Create a file link using completion."
  9521. (let ((file (read-file-name "File: "))
  9522. (pwd (file-name-as-directory (expand-file-name ".")))
  9523. (pwd1 (file-name-as-directory (abbreviate-file-name
  9524. (expand-file-name ".")))))
  9525. (cond ((equal arg '(16))
  9526. (concat "file:"
  9527. (abbreviate-file-name (expand-file-name file))))
  9528. ((string-match
  9529. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9530. (concat "file:" (match-string 1 file)))
  9531. ((string-match
  9532. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9533. (expand-file-name file))
  9534. (concat "file:"
  9535. (match-string 1 (expand-file-name file))))
  9536. (t (concat "file:" file)))))
  9537. (defun org-completing-read (&rest args)
  9538. "Completing-read with SPACE being a normal character."
  9539. (let ((enable-recursive-minibuffers t)
  9540. (minibuffer-local-completion-map
  9541. (copy-keymap minibuffer-local-completion-map)))
  9542. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9543. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9544. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9545. 'org-time-stamp-inactive)
  9546. (apply #'completing-read args)))
  9547. ;;; Opening/following a link
  9548. (defvar org-link-search-failed nil)
  9549. (defvar org-open-link-functions nil
  9550. "Hook for functions finding a plain text link.
  9551. These functions must take a single argument, the link content.
  9552. They will be called for links that look like [[link text][description]]
  9553. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9554. like a filename (e.g. \"./blue.png\").
  9555. These functions will be called *before* Org attempts to resolve the
  9556. link by doing text searches in the current buffer - so if you want a
  9557. link \"[[target]]\" to still find \"<<target>>\", your function should
  9558. handle this as a special case.
  9559. When the function does handle the link, it must return a non-nil value.
  9560. If it decides that it is not responsible for this link, it must return
  9561. nil to indicate that that Org can continue with other options like
  9562. exact and fuzzy text search.")
  9563. (defun org-next-link (&optional search-backward)
  9564. "Move forward to the next link.
  9565. If the link is in hidden text, expose it."
  9566. (interactive "P")
  9567. (when (and org-link-search-failed (eq this-command last-command))
  9568. (goto-char (point-min))
  9569. (message "Link search wrapped back to beginning of buffer"))
  9570. (setq org-link-search-failed nil)
  9571. (let* ((pos (point))
  9572. (ct (org-context))
  9573. (a (assq :link ct))
  9574. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9575. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9576. ((looking-at org-any-link-re)
  9577. ;; Don't stay stuck at link without an org-link face
  9578. (forward-char (if search-backward -1 1))))
  9579. (if (funcall srch-fun org-any-link-re nil t)
  9580. (progn
  9581. (goto-char (match-beginning 0))
  9582. (when (outline-invisible-p) (org-show-context)))
  9583. (goto-char pos)
  9584. (setq org-link-search-failed t)
  9585. (message "No further link found"))))
  9586. (defun org-previous-link ()
  9587. "Move backward to the previous link.
  9588. If the link is in hidden text, expose it."
  9589. (interactive)
  9590. (funcall 'org-next-link t))
  9591. (defun org-translate-link (s)
  9592. "Translate a link string if a translation function has been defined."
  9593. (with-temp-buffer
  9594. (insert (org-trim s))
  9595. (org-trim (org-element-interpret-data (org-element-context)))))
  9596. (defun org-translate-link-from-planner (type path)
  9597. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9598. This is still an experimental function, your mileage may vary."
  9599. (cond
  9600. ((member type '("http" "https" "news" "ftp"))
  9601. ;; standard Internet links are the same.
  9602. nil)
  9603. ((and (equal type "irc") (string-match "^//" path))
  9604. ;; Planner has two / at the beginning of an irc link, we have 1.
  9605. ;; We should have zero, actually....
  9606. (setq path (substring path 1)))
  9607. ((and (equal type "lisp") (string-match "^/" path))
  9608. ;; Planner has a slash, we do not.
  9609. (setq type "elisp" path (substring path 1)))
  9610. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9611. ;; A typical message link. Planner has the id after the final slash,
  9612. ;; we separate it with a hash mark
  9613. (setq path (concat (match-string 1 path) "#"
  9614. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9615. (cons type path))
  9616. (defun org-find-file-at-mouse (ev)
  9617. "Open file link or URL at mouse."
  9618. (interactive "e")
  9619. (mouse-set-point ev)
  9620. (org-open-at-point 'in-emacs))
  9621. (defun org-open-at-mouse (ev)
  9622. "Open file link or URL at mouse.
  9623. See the docstring of `org-open-file' for details."
  9624. (interactive "e")
  9625. (mouse-set-point ev)
  9626. (when (eq major-mode 'org-agenda-mode)
  9627. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9628. (org-open-at-point))
  9629. (defvar org-window-config-before-follow-link nil
  9630. "The window configuration before following a link.
  9631. This is saved in case the need arises to restore it.")
  9632. ;;;###autoload
  9633. (defun org-open-at-point-global ()
  9634. "Follow a link or time-stamp like Org mode does.
  9635. This command can be called in any mode to follow an external link
  9636. or a time-stamp that has Org mode syntax. Its behavior is
  9637. undefined when called on internal links (e.g., fuzzy links).
  9638. Raise an error when there is nothing to follow. "
  9639. (interactive)
  9640. (cond ((org-in-regexp org-any-link-re)
  9641. (org-open-link-from-string (match-string-no-properties 0)))
  9642. ((or (org-in-regexp org-ts-regexp-both nil t)
  9643. (org-in-regexp org-tsr-regexp-both nil t))
  9644. (org-follow-timestamp-link))
  9645. (t (user-error "No link found"))))
  9646. ;;;###autoload
  9647. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9648. "Open a link in the string S, as if it was in Org mode."
  9649. (interactive "sLink: \nP")
  9650. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9651. (with-temp-buffer
  9652. (let ((org-inhibit-startup (not reference-buffer)))
  9653. (org-mode)
  9654. (insert s)
  9655. (goto-char (point-min))
  9656. (when reference-buffer
  9657. (setq org-link-abbrev-alist-local
  9658. (with-current-buffer reference-buffer
  9659. org-link-abbrev-alist-local)))
  9660. (org-open-at-point arg reference-buffer)))))
  9661. (defvar org-open-at-point-functions nil
  9662. "Hook that is run when following a link at point.
  9663. Functions in this hook must return t if they identify and follow
  9664. a link at point. If they don't find anything interesting at point,
  9665. they must return nil.")
  9666. (defvar org-link-search-inhibit-query nil)
  9667. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9668. (defun org--open-doi-link (path)
  9669. "Open a \"doi\" type link.
  9670. PATH is a the path to search for, as a string."
  9671. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9672. (defun org--open-elisp-link (path)
  9673. "Open a \"elisp\" type link.
  9674. PATH is the sexp to evaluate, as a string."
  9675. (let ((cmd path))
  9676. (if (or (and (org-string-nw-p
  9677. org-confirm-elisp-link-not-regexp)
  9678. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9679. (not org-confirm-elisp-link-function)
  9680. (funcall org-confirm-elisp-link-function
  9681. (format "Execute \"%s\" as elisp? "
  9682. (org-add-props cmd nil 'face 'org-warning))))
  9683. (message "%s => %s" cmd
  9684. (if (eq (string-to-char cmd) ?\()
  9685. (eval (read cmd))
  9686. (call-interactively (read cmd))))
  9687. (user-error "Abort"))))
  9688. (defun org--open-help-link (path)
  9689. "Open a \"help\" type link.
  9690. PATH is a symbol name, as a string."
  9691. (pcase (intern path)
  9692. ((and (pred fboundp) variable) (describe-function variable))
  9693. ((and (pred boundp) function) (describe-variable function))
  9694. (name (user-error "Unknown function or variable: %s" name))))
  9695. (defun org--open-shell-link (path)
  9696. "Open a \"shell\" type link.
  9697. PATH is the command to execute, as a string."
  9698. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9699. (cmd path))
  9700. (if (or (and (org-string-nw-p
  9701. org-confirm-shell-link-not-regexp)
  9702. (string-match
  9703. org-confirm-shell-link-not-regexp cmd))
  9704. (not org-confirm-shell-link-function)
  9705. (funcall org-confirm-shell-link-function
  9706. (format "Execute \"%s\" in shell? "
  9707. (org-add-props cmd nil
  9708. 'face 'org-warning))))
  9709. (progn
  9710. (message "Executing %s" cmd)
  9711. (shell-command cmd buf)
  9712. (when (featurep 'midnight)
  9713. (setq clean-buffer-list-kill-buffer-names
  9714. (cons (buffer-name buf)
  9715. clean-buffer-list-kill-buffer-names))))
  9716. (user-error "Abort"))))
  9717. (defun org-open-at-point (&optional arg reference-buffer)
  9718. "Open link, timestamp, footnote or tags at point.
  9719. When point is on a link, follow it. Normally, files will be
  9720. opened by an appropriate application. If the optional prefix
  9721. argument ARG is non-nil, Emacs will visit the file. With
  9722. a double prefix argument, try to open outside of Emacs, in the
  9723. application the system uses for this file type.
  9724. When point is on a timestamp, open the agenda at the day
  9725. specified.
  9726. When point is a footnote definition, move to the first reference
  9727. found. If it is on a reference, move to the associated
  9728. definition.
  9729. When point is on a headline, display a list of every link in the
  9730. entry, so it is possible to pick one, or all, of them. If point
  9731. is on a tag, call `org-tags-view' instead.
  9732. When optional argument REFERENCE-BUFFER is non-nil, it should
  9733. specify a buffer from where the link search should happen. This
  9734. is used internally by `org-open-link-from-string'.
  9735. On top of syntactically correct links, this function will open
  9736. the link at point in comments or comment blocks and the first
  9737. link in a property drawer line."
  9738. (interactive "P")
  9739. ;; On a code block, open block's results.
  9740. (unless (call-interactively 'org-babel-open-src-block-result)
  9741. (org-load-modules-maybe)
  9742. (setq org-window-config-before-follow-link (current-window-configuration))
  9743. (org-remove-occur-highlights nil nil t)
  9744. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9745. (let* ((context
  9746. ;; Only consider supported types, even if they are not
  9747. ;; the closest one.
  9748. (org-element-lineage
  9749. (org-element-context)
  9750. '(clock comment comment-block footnote-definition
  9751. footnote-reference headline inlinetask keyword link
  9752. node-property timestamp)
  9753. t))
  9754. (type (org-element-type context))
  9755. (value (org-element-property :value context)))
  9756. (cond
  9757. ((not context) (user-error "No link found"))
  9758. ;; Exception: open timestamps and links in properties
  9759. ;; drawers, keywords and comments.
  9760. ((memq type '(comment comment-block keyword node-property))
  9761. (call-interactively #'org-open-at-point-global))
  9762. ;; On a headline or an inlinetask, but not on a timestamp,
  9763. ;; a link, a footnote reference or on tags.
  9764. ((and (memq type '(headline inlinetask))
  9765. ;; Not on tags.
  9766. (let ((case-fold-search nil))
  9767. (save-excursion
  9768. (beginning-of-line)
  9769. (looking-at org-complex-heading-regexp))
  9770. (or (not (match-beginning 5))
  9771. (< (point) (match-beginning 5)))))
  9772. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9773. (links (car data))
  9774. (links-end (cdr data)))
  9775. (if links
  9776. (dolist (link (if (stringp links) (list links) links))
  9777. (search-forward link nil links-end)
  9778. (goto-char (match-beginning 0))
  9779. (org-open-at-point))
  9780. (require 'org-attach)
  9781. (org-attach-reveal 'if-exists))))
  9782. ;; On a clock line, make sure point is on the timestamp
  9783. ;; before opening it.
  9784. ((and (eq type 'clock)
  9785. value
  9786. (>= (point) (org-element-property :begin value))
  9787. (<= (point) (org-element-property :end value)))
  9788. (org-follow-timestamp-link))
  9789. ;; Do nothing on white spaces after an object.
  9790. ((>= (point)
  9791. (save-excursion
  9792. (goto-char (org-element-property :end context))
  9793. (skip-chars-backward " \t")
  9794. (point)))
  9795. (user-error "No link found"))
  9796. ((eq type 'timestamp) (org-follow-timestamp-link))
  9797. ;; On tags within a headline or an inlinetask.
  9798. ((and (memq type '(headline inlinetask))
  9799. (let ((case-fold-search nil))
  9800. (save-excursion (beginning-of-line)
  9801. (looking-at org-complex-heading-regexp))
  9802. (and (match-beginning 5)
  9803. (>= (point) (match-beginning 5)))))
  9804. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9805. ((eq type 'link)
  9806. ;; When link is located within the description of another
  9807. ;; link (e.g., an inline image), always open the parent
  9808. ;; link.
  9809. (let* ((link (let ((up (org-element-property :parent context)))
  9810. (if (eq (org-element-type up) 'link) up context)))
  9811. (type (org-element-property :type link))
  9812. (path (org-link-unescape (org-element-property :path link))))
  9813. ;; Switch back to REFERENCE-BUFFER needed when called in
  9814. ;; a temporary buffer through `org-open-link-from-string'.
  9815. (with-current-buffer (or reference-buffer (current-buffer))
  9816. (cond
  9817. ((equal type "file")
  9818. (if (string-match "[*?{]" (file-name-nondirectory path))
  9819. (dired path)
  9820. ;; Look into `org-link-parameters' in order to find
  9821. ;; a DEDICATED-FUNCTION to open file. The function
  9822. ;; will be applied on raw link instead of parsed
  9823. ;; link due to the limitation in `org-add-link-type'
  9824. ;; ("open" function called with a single argument).
  9825. ;; If no such function is found, fallback to
  9826. ;; `org-open-file'.
  9827. (let* ((option (org-element-property :search-option link))
  9828. (app (org-element-property :application link))
  9829. (dedicated-function
  9830. (org-link-get-parameter
  9831. (if app (concat type "+" app) type)
  9832. :follow)))
  9833. (if dedicated-function
  9834. (funcall dedicated-function
  9835. (concat path
  9836. (and option (concat "::" option))))
  9837. (apply #'org-open-file
  9838. path
  9839. (cond (arg)
  9840. ((equal app "emacs") 'emacs)
  9841. ((equal app "sys") 'system))
  9842. (cond ((not option) nil)
  9843. ((string-match-p "\\`[0-9]+\\'" option)
  9844. (list (string-to-number option)))
  9845. (t (list nil
  9846. (org-link-unescape option)))))))))
  9847. ((functionp (org-link-get-parameter type :follow))
  9848. (funcall (org-link-get-parameter type :follow) path))
  9849. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9850. (unless (run-hook-with-args-until-success
  9851. 'org-open-link-functions path)
  9852. (if (not arg) (org-mark-ring-push)
  9853. (switch-to-buffer-other-window
  9854. (org-get-buffer-for-internal-link (current-buffer))))
  9855. (let ((destination
  9856. (org-with-wide-buffer
  9857. (if (equal type "radio")
  9858. (org-search-radio-target
  9859. (org-element-property :path link))
  9860. (org-link-search
  9861. (if (member type '("custom-id" "coderef"))
  9862. (org-element-property :raw-link link)
  9863. path)
  9864. ;; Prevent fuzzy links from matching
  9865. ;; themselves.
  9866. (and (equal type "fuzzy")
  9867. (+ 2 (org-element-property :begin link)))))
  9868. (point))))
  9869. (unless (and (<= (point-min) destination)
  9870. (>= (point-max) destination))
  9871. (widen))
  9872. (goto-char destination))))
  9873. (t (browse-url-at-point))))))
  9874. ;; On a footnote reference or at a footnote definition's label.
  9875. ((or (eq type 'footnote-reference)
  9876. (and (eq type 'footnote-definition)
  9877. (save-excursion
  9878. ;; Do not validate action when point is on the
  9879. ;; spaces right after the footnote label, in
  9880. ;; order to be on par with behaviour on links.
  9881. (skip-chars-forward " \t")
  9882. (let ((begin
  9883. (org-element-property :contents-begin context)))
  9884. (if begin (< (point) begin)
  9885. (= (org-element-property :post-affiliated context)
  9886. (line-beginning-position)))))))
  9887. (org-footnote-action))
  9888. (t (user-error "No link found")))))
  9889. (run-hook-with-args 'org-follow-link-hook)))
  9890. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9891. "Offer links in the current entry and return the selected link.
  9892. If there is only one link, return it.
  9893. If NTH is an integer, return the NTH link found.
  9894. If ZERO is a string, check also this string for a link, and if
  9895. there is one, return it."
  9896. (with-current-buffer buffer
  9897. (org-with-wide-buffer
  9898. (goto-char marker)
  9899. (let ((cnt ?0)
  9900. have-zero end links link c)
  9901. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9902. (push (match-string 0 zero) links)
  9903. (setq cnt (1- cnt) have-zero t))
  9904. (save-excursion
  9905. (org-back-to-heading t)
  9906. (setq end (save-excursion (outline-next-heading) (point)))
  9907. (while (re-search-forward org-any-link-re end t)
  9908. (push (match-string 0) links))
  9909. (setq links (org-uniquify (reverse links))))
  9910. (cond
  9911. ((null links)
  9912. (message "No links"))
  9913. ((equal (length links) 1)
  9914. (setq link (car links)))
  9915. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9916. (setq link (nth (if have-zero nth (1- nth)) links)))
  9917. (t ; we have to select a link
  9918. (save-excursion
  9919. (save-window-excursion
  9920. (delete-other-windows)
  9921. (with-output-to-temp-buffer "*Select Link*"
  9922. (dolist (l links)
  9923. (cond
  9924. ((not (string-match org-bracket-link-regexp l))
  9925. (princ (format "[%c] %s\n" (cl-incf cnt)
  9926. (org-unbracket-string "<" ">" l))))
  9927. ((match-end 3)
  9928. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9929. (match-string 3 l) (match-string 1 l))))
  9930. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9931. (match-string 1 l)))))))
  9932. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9933. (message "Select link to open, RET to open all:")
  9934. (setq c (read-char-exclusive))
  9935. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9936. (when (equal c ?q) (user-error "Abort"))
  9937. (if (equal c ?\C-m)
  9938. (setq link links)
  9939. (setq nth (- c ?0))
  9940. (when have-zero (setq nth (1+ nth)))
  9941. (unless (and (integerp nth) (>= (length links) nth))
  9942. (user-error "Invalid link selection"))
  9943. (setq link (nth (1- nth) links)))))
  9944. (cons link end)))))
  9945. ;; TODO: These functions are deprecated since `org-open-at-point'
  9946. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9947. (defun org-open-file-with-system (path)
  9948. "Open file at PATH using the system way of opening it."
  9949. (org-open-file path 'system))
  9950. (defun org-open-file-with-emacs (path)
  9951. "Open file at PATH in Emacs."
  9952. (org-open-file path 'emacs))
  9953. ;;; File search
  9954. (defvar org-create-file-search-functions nil
  9955. "List of functions to construct the right search string for a file link.
  9956. These functions are called in turn with point at the location to
  9957. which the link should point.
  9958. A function in the hook should first test if it would like to
  9959. handle this file type, for example by checking the `major-mode'
  9960. or the file extension. If it decides not to handle this file, it
  9961. should just return nil to give other functions a chance. If it
  9962. does handle the file, it must return the search string to be used
  9963. when following the link. The search string will be part of the
  9964. file link, given after a double colon, and `org-open-at-point'
  9965. will automatically search for it. If special measures must be
  9966. taken to make the search successful, another function should be
  9967. added to the companion hook `org-execute-file-search-functions',
  9968. which see.
  9969. A function in this hook may also use `setq' to set the variable
  9970. `description' to provide a suggestion for the descriptive text to
  9971. be used for this link when it gets inserted into an Org buffer
  9972. with \\[org-insert-link].")
  9973. (defvar org-execute-file-search-functions nil
  9974. "List of functions to execute a file search triggered by a link.
  9975. Functions added to this hook must accept a single argument, the
  9976. search string that was part of the file link, the part after the
  9977. double colon. The function must first check if it would like to
  9978. handle this search, for example by checking the `major-mode' or
  9979. the file extension. If it decides not to handle this search, it
  9980. should just return nil to give other functions a chance. If it
  9981. does handle the search, it must return a non-nil value to keep
  9982. other functions from trying.
  9983. Each function can access the current prefix argument through the
  9984. variable `current-prefix-arg'. Note that a single prefix is used
  9985. to force opening a link in Emacs, so it may be good to only use a
  9986. numeric or double prefix to guide the search function.
  9987. In case this is needed, a function in this hook can also restore
  9988. the window configuration before `org-open-at-point' was called using:
  9989. (set-window-configuration org-window-config-before-follow-link)")
  9990. (defun org-search-radio-target (target)
  9991. "Search a radio target matching TARGET in current buffer.
  9992. White spaces are not significant."
  9993. (let ((re (format "<<<%s>>>"
  9994. (mapconcat #'regexp-quote
  9995. (org-split-string target "[ \t\n]+")
  9996. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9997. (origin (point)))
  9998. (goto-char (point-min))
  9999. (catch :radio-match
  10000. (while (re-search-forward re nil t)
  10001. (backward-char)
  10002. (let ((object (org-element-context)))
  10003. (when (eq (org-element-type object) 'radio-target)
  10004. (goto-char (org-element-property :begin object))
  10005. (org-show-context 'link-search)
  10006. (throw :radio-match nil))))
  10007. (goto-char origin)
  10008. (user-error "No match for radio target: %s" target))))
  10009. (defun org-link-search (s &optional avoid-pos stealth)
  10010. "Search for a search string S.
  10011. If S starts with \"#\", it triggers a custom ID search.
  10012. If S is enclosed within parenthesis, it initiates a coderef
  10013. search.
  10014. If S is surrounded by forward slashes, it is interpreted as
  10015. a regular expression. In Org mode files, this will create an
  10016. `org-occur' sparse tree. In ordinary files, `occur' will be used
  10017. to list matches. If the current buffer is in `dired-mode', grep
  10018. will be used to search in all files.
  10019. When AVOID-POS is given, ignore matches near that position.
  10020. When optional argument STEALTH is non-nil, do not modify
  10021. visibility around point, thus ignoring `org-show-context-detail'
  10022. variable.
  10023. Search is case-insensitive and ignores white spaces. Return type
  10024. of matched result, which is either `dedicated' or `fuzzy'."
  10025. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  10026. (let* ((case-fold-search t)
  10027. (origin (point))
  10028. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  10029. (starred (eq (string-to-char normalized) ?*))
  10030. (words (split-string (if starred (substring s 1) s)))
  10031. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  10032. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  10033. type)
  10034. (cond
  10035. ;; Check if there are any special search functions.
  10036. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  10037. ((eq (string-to-char s) ?#)
  10038. ;; Look for a custom ID S if S starts with "#".
  10039. (let* ((id (substring normalized 1))
  10040. (match (org-find-property "CUSTOM_ID" id)))
  10041. (if match (progn (goto-char match) (setf type 'dedicated))
  10042. (error "No match for custom ID: %s" id))))
  10043. ((string-match "\\`(\\(.*\\))\\'" normalized)
  10044. ;; Look for coderef targets if S is enclosed within parenthesis.
  10045. (let ((coderef (match-string-no-properties 1 normalized))
  10046. (re (substring s-single-re 1 -1)))
  10047. (goto-char (point-min))
  10048. (catch :coderef-match
  10049. (while (re-search-forward re nil t)
  10050. (let ((element (org-element-at-point)))
  10051. (when (and (memq (org-element-type element)
  10052. '(example-block src-block))
  10053. ;; Build proper regexp according to current
  10054. ;; block's label format.
  10055. (let ((label-fmt
  10056. (regexp-quote
  10057. (or (org-element-property :label-fmt element)
  10058. org-coderef-label-format))))
  10059. (save-excursion
  10060. (beginning-of-line)
  10061. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  10062. (format label-fmt coderef))))))
  10063. (setq type 'dedicated)
  10064. (goto-char (match-beginning 1))
  10065. (throw :coderef-match nil))))
  10066. (goto-char origin)
  10067. (error "No match for coderef: %s" coderef))))
  10068. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10069. ;; Look for a regular expression.
  10070. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10071. (match-string 1 s)))
  10072. ;; From here, we handle fuzzy links.
  10073. ;;
  10074. ;; Look for targets, only if not in a headline search.
  10075. ((and (not starred)
  10076. (let ((target (format "<<%s>>" s-multi-re)))
  10077. (catch :target-match
  10078. (goto-char (point-min))
  10079. (while (re-search-forward target nil t)
  10080. (backward-char)
  10081. (let ((context (org-element-context)))
  10082. (when (eq (org-element-type context) 'target)
  10083. (setq type 'dedicated)
  10084. (goto-char (org-element-property :begin context))
  10085. (throw :target-match t))))
  10086. nil))))
  10087. ;; Look for elements named after S, only if not in a headline
  10088. ;; search.
  10089. ((and (not starred)
  10090. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10091. (catch :name-match
  10092. (goto-char (point-min))
  10093. (while (re-search-forward name nil t)
  10094. (let ((element (org-element-at-point)))
  10095. (when (equal words
  10096. (split-string
  10097. (org-element-property :name element)))
  10098. (setq type 'dedicated)
  10099. (beginning-of-line)
  10100. (throw :name-match t))))
  10101. nil))))
  10102. ;; Regular text search. Prefer headlines in Org mode buffers.
  10103. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  10104. ;; statistics cookies and tags.
  10105. ((and (derived-mode-p 'org-mode)
  10106. (let ((title-re
  10107. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  10108. org-outline-regexp-bol
  10109. org-comment-string
  10110. (mapconcat #'regexp-quote words ".+")))
  10111. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  10112. (comment-re (format "\\`%s[ \t]+" org-comment-string)))
  10113. (goto-char (point-min))
  10114. (catch :found
  10115. (while (re-search-forward title-re nil t)
  10116. (when (equal words
  10117. (split-string
  10118. (replace-regexp-in-string
  10119. cookie-re ""
  10120. (replace-regexp-in-string
  10121. comment-re "" (org-get-heading t t)))))
  10122. (throw :found t)))
  10123. nil)))
  10124. (beginning-of-line)
  10125. (setq type 'dedicated))
  10126. ;; Offer to create non-existent headline depending on
  10127. ;; `org-link-search-must-match-exact-headline'.
  10128. ((and (derived-mode-p 'org-mode)
  10129. (not org-link-search-inhibit-query)
  10130. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10131. (yes-or-no-p "No match - create this as a new heading? "))
  10132. (goto-char (point-max))
  10133. (unless (bolp) (newline))
  10134. (org-insert-heading nil t t)
  10135. (insert s "\n")
  10136. (beginning-of-line 0))
  10137. ;; Only headlines are looked after. No need to process
  10138. ;; further: throw an error.
  10139. ((and (derived-mode-p 'org-mode)
  10140. (or starred org-link-search-must-match-exact-headline))
  10141. (goto-char origin)
  10142. (error "No match for fuzzy expression: %s" normalized))
  10143. ;; Regular text search.
  10144. ((catch :fuzzy-match
  10145. (goto-char (point-min))
  10146. (while (re-search-forward s-multi-re nil t)
  10147. ;; Skip match if it contains AVOID-POS or it is included in
  10148. ;; a link with a description but outside the description.
  10149. (unless (or (and avoid-pos
  10150. (<= (match-beginning 0) avoid-pos)
  10151. (> (match-end 0) avoid-pos))
  10152. (and (save-match-data
  10153. (org-in-regexp org-bracket-link-regexp))
  10154. (match-beginning 3)
  10155. (or (> (match-beginning 3) (point))
  10156. (<= (match-end 3) (point)))
  10157. (org-element-lineage
  10158. (save-match-data (org-element-context))
  10159. '(link) t)))
  10160. (goto-char (match-beginning 0))
  10161. (setq type 'fuzzy)
  10162. (throw :fuzzy-match t)))
  10163. nil))
  10164. ;; All failed. Throw an error.
  10165. (t (goto-char origin)
  10166. (error "No match for fuzzy expression: %s" normalized)))
  10167. ;; Disclose surroundings of match, if appropriate.
  10168. (when (and (derived-mode-p 'org-mode) (not stealth))
  10169. (org-show-context 'link-search))
  10170. type))
  10171. (defun org-get-buffer-for-internal-link (buffer)
  10172. "Return a buffer to be used for displaying the link target of internal links."
  10173. (cond
  10174. ((not org-display-internal-link-with-indirect-buffer)
  10175. buffer)
  10176. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10177. (message "Buffer is already a clone, not making another one")
  10178. ;; we also do not modify visibility in this case
  10179. buffer)
  10180. (t ; make a new indirect buffer for displaying the link
  10181. (let* ((bn (buffer-name buffer))
  10182. (ibn (concat bn "(Clone)"))
  10183. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10184. (with-current-buffer ib (org-overview))
  10185. ib))))
  10186. (defun org-do-occur (regexp &optional cleanup)
  10187. "Call the Emacs command `occur'.
  10188. If CLEANUP is non-nil, remove the printout of the regular expression
  10189. in the *Occur* buffer. This is useful if the regex is long and not useful
  10190. to read."
  10191. (occur regexp)
  10192. (when cleanup
  10193. (let ((cwin (selected-window)) win beg end)
  10194. (when (setq win (get-buffer-window "*Occur*"))
  10195. (select-window win))
  10196. (goto-char (point-min))
  10197. (when (re-search-forward "match[a-z]+" nil t)
  10198. (setq beg (match-end 0))
  10199. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10200. (setq end (1- (match-beginning 0)))))
  10201. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10202. (goto-char (point-min))
  10203. (select-window cwin))))
  10204. ;;; The mark ring for links jumps
  10205. (defvar org-mark-ring nil
  10206. "Mark ring for positions before jumps in Org mode.")
  10207. (defvar org-mark-ring-last-goto nil
  10208. "Last position in the mark ring used to go back.")
  10209. ;; Fill and close the ring
  10210. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10211. (dotimes (_ org-mark-ring-length)
  10212. (push (make-marker) org-mark-ring))
  10213. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10214. org-mark-ring)
  10215. (defun org-mark-ring-push (&optional pos buffer)
  10216. "Put the current position or POS into the mark ring and rotate it."
  10217. (interactive)
  10218. (setq pos (or pos (point)))
  10219. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10220. (move-marker (car org-mark-ring)
  10221. (or pos (point))
  10222. (or buffer (current-buffer)))
  10223. (message "%s"
  10224. (substitute-command-keys
  10225. "Position saved to mark ring, go back with \
  10226. `\\[org-mark-ring-goto]'.")))
  10227. (defun org-mark-ring-goto (&optional n)
  10228. "Jump to the previous position in the mark ring.
  10229. With prefix arg N, jump back that many stored positions. When
  10230. called several times in succession, walk through the entire ring.
  10231. Org mode commands jumping to a different position in the current file,
  10232. or to another Org file, automatically push the old position onto the ring."
  10233. (interactive "p")
  10234. (let (p m)
  10235. (if (eq last-command this-command)
  10236. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10237. (setq p org-mark-ring))
  10238. (setq org-mark-ring-last-goto p)
  10239. (setq m (car p))
  10240. (pop-to-buffer-same-window (marker-buffer m))
  10241. (goto-char m)
  10242. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10243. (defun org-add-angle-brackets (s)
  10244. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10245. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10246. s)
  10247. ;;; Following specific links
  10248. (defvar org-agenda-buffer-tmp-name)
  10249. (defvar org-agenda-start-on-weekday)
  10250. (defun org-follow-timestamp-link ()
  10251. "Open an agenda view for the time-stamp date/range at point."
  10252. (cond
  10253. ((org-at-date-range-p t)
  10254. (let ((org-agenda-start-on-weekday)
  10255. (t1 (match-string 1))
  10256. (t2 (match-string 2)) tt1 tt2)
  10257. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10258. tt2 (time-to-days (org-time-string-to-time t2)))
  10259. (let ((org-agenda-buffer-tmp-name
  10260. (format "*Org Agenda(a:%s)"
  10261. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10262. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10263. ((org-at-timestamp-p t)
  10264. (let ((org-agenda-buffer-tmp-name
  10265. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10266. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10267. (substring (match-string 1) 0 10)))
  10268. 1)))
  10269. (t (error "This should not happen"))))
  10270. ;;; Following file links
  10271. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10272. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10273. (declare-function mailcap-mime-info
  10274. "mailcap" (string &optional request no-decode))
  10275. (defvar org-wait nil)
  10276. (defun org-open-file (path &optional in-emacs line search)
  10277. "Open the file at PATH.
  10278. First, this expands any special file name abbreviations. Then the
  10279. configuration variable `org-file-apps' is checked if it contains an
  10280. entry for this file type, and if yes, the corresponding command is launched.
  10281. If no application is found, Emacs simply visits the file.
  10282. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10283. With a double \\[universal-argument] \\[universal-argument] \
  10284. prefix arg, Org tries to avoid opening in Emacs
  10285. and to use an external application to visit the file.
  10286. Optional LINE specifies a line to go to, optional SEARCH a string
  10287. to search for. If LINE or SEARCH is given, the file will be
  10288. opened in Emacs, unless an entry from org-file-apps that makes
  10289. use of groups in a regexp matches.
  10290. If you want to change the way frames are used when following a
  10291. link, please customize `org-link-frame-setup'.
  10292. If the file does not exist, an error is thrown."
  10293. (let* ((file (if (equal path "")
  10294. buffer-file-name
  10295. (substitute-in-file-name (expand-file-name path))))
  10296. (file-apps (append org-file-apps (org-default-apps)))
  10297. (apps (cl-remove-if
  10298. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10299. (apps-dlink (cl-remove-if-not
  10300. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10301. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10302. (dirp (unless remp (file-directory-p file)))
  10303. (file (if (and dirp org-open-directory-means-index-dot-org)
  10304. (concat (file-name-as-directory file) "index.org")
  10305. file))
  10306. (a-m-a-p (assq 'auto-mode apps))
  10307. (dfile (downcase file))
  10308. ;; Reconstruct the original link from the PATH, LINE and
  10309. ;; SEARCH args.
  10310. (link (cond (line (concat file "::" (number-to-string line)))
  10311. (search (concat file "::" search))
  10312. (t file)))
  10313. (dlink (downcase link))
  10314. (old-buffer (current-buffer))
  10315. (old-pos (point))
  10316. (old-mode major-mode)
  10317. (ext
  10318. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10319. (match-string 1 dfile)))
  10320. cmd link-match-data)
  10321. (cond
  10322. ((member in-emacs '((16) system))
  10323. (setq cmd (cdr (assq 'system apps))))
  10324. (in-emacs (setq cmd 'emacs))
  10325. (t
  10326. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10327. (and dirp (cdr (assq 'directory apps)))
  10328. ;; First, try matching against apps-dlink if we
  10329. ;; get a match here, store the match data for
  10330. ;; later.
  10331. (let ((match (assoc-default dlink apps-dlink
  10332. 'string-match)))
  10333. (if match
  10334. (progn (setq link-match-data (match-data))
  10335. match)
  10336. (progn (setq in-emacs (or in-emacs line search))
  10337. nil))) ; if we have no match in apps-dlink,
  10338. ; always open the file in emacs if line or search
  10339. ; is given (for backwards compatibility)
  10340. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10341. 'string-match)
  10342. (cdr (assoc ext apps))
  10343. (cdr (assq t apps))))))
  10344. (when (eq cmd 'system)
  10345. (setq cmd (cdr (assq 'system apps))))
  10346. (when (eq cmd 'default)
  10347. (setq cmd (cdr (assoc t apps))))
  10348. (when (eq cmd 'mailcap)
  10349. (require 'mailcap)
  10350. (mailcap-parse-mailcaps)
  10351. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10352. (command (mailcap-mime-info mime-type)))
  10353. (if (stringp command)
  10354. (setq cmd command)
  10355. (setq cmd 'emacs))))
  10356. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10357. (not (file-exists-p file))
  10358. (not org-open-non-existing-files))
  10359. (user-error "No such file: %s" file))
  10360. (cond
  10361. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10362. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10363. (while (string-match "['\"]%s['\"]" cmd)
  10364. (setq cmd (replace-match "%s" t t cmd)))
  10365. (setq cmd (replace-regexp-in-string
  10366. "%s"
  10367. (shell-quote-argument (convert-standard-filename file))
  10368. cmd
  10369. nil t))
  10370. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10371. (save-match-data
  10372. (let ((match-index 1)
  10373. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10374. (set-match-data link-match-data)
  10375. (while (<= match-index number-of-groups)
  10376. (let ((regex (concat "%" (number-to-string match-index)))
  10377. (replace-with (match-string match-index dlink)))
  10378. (while (string-match regex cmd)
  10379. (setq cmd (replace-match replace-with t t cmd))))
  10380. (setq match-index (+ match-index 1)))))
  10381. (save-window-excursion
  10382. (message "Running %s...done" cmd)
  10383. (start-process-shell-command cmd nil cmd)
  10384. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10385. ((or (stringp cmd)
  10386. (eq cmd 'emacs))
  10387. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10388. (widen)
  10389. (cond (line (org-goto-line line)
  10390. (when (derived-mode-p 'org-mode) (org-reveal)))
  10391. (search (org-link-search search))))
  10392. ((functionp cmd)
  10393. (save-match-data
  10394. (set-match-data link-match-data)
  10395. (condition-case nil
  10396. (funcall cmd file link)
  10397. ;; FIXME: Remove this check when most default installations
  10398. ;; of Emacs have at least Org 9.0.
  10399. ((debug wrong-number-of-arguments wrong-type-argument
  10400. invalid-function)
  10401. (user-error "Please see Org News for version 9.0 about \
  10402. `org-file-apps'--Lisp error: %S" cmd)))))
  10403. ((consp cmd)
  10404. ;; FIXME: Remove this check when most default installations of
  10405. ;; Emacs have at least Org 9.0.
  10406. ;; Heads-up instead of silently fall back to
  10407. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10408. ;; with sexp instead of a function for `cmd'.
  10409. (user-error "Please see Org News for version 9.0 about \
  10410. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10411. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10412. (and (derived-mode-p 'org-mode)
  10413. (eq old-mode 'org-mode)
  10414. (or (not (eq old-buffer (current-buffer)))
  10415. (not (eq old-pos (point))))
  10416. (org-mark-ring-push old-pos old-buffer))))
  10417. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10418. "This function returns non-nil if `entry' uses a regular
  10419. expression which should be matched against the whole link by
  10420. org-open-file.
  10421. It assumes that is the case when the entry uses a regular
  10422. expression which has at least one grouping construct and the
  10423. action is either a lisp form or a command string containing
  10424. `%1', i.e. using at least one subexpression match as a
  10425. parameter."
  10426. (let ((selector (car entry))
  10427. (action (cdr entry)))
  10428. (if (stringp selector)
  10429. (and (> (regexp-opt-depth selector) 0)
  10430. (or (and (stringp action)
  10431. (string-match "%[0-9]" action))
  10432. (consp action)))
  10433. nil)))
  10434. (defun org-default-apps ()
  10435. "Return the default applications for this operating system."
  10436. (cond
  10437. ((eq system-type 'darwin)
  10438. org-file-apps-defaults-macosx)
  10439. ((eq system-type 'windows-nt)
  10440. org-file-apps-defaults-windowsnt)
  10441. (t org-file-apps-defaults-gnu)))
  10442. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10443. "Convert extensions to regular expressions in the cars of LIST.
  10444. Also, weed out any non-string entries, because the return value is used
  10445. only for regexp matching.
  10446. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10447. point to the symbol `emacs', indicating that the file should
  10448. be opened in Emacs."
  10449. (append
  10450. (delq nil
  10451. (mapcar (lambda (x)
  10452. (unless (not (stringp (car x)))
  10453. (if (string-match "\\W" (car x))
  10454. x
  10455. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10456. list))
  10457. (when add-auto-mode
  10458. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10459. (defvar ange-ftp-name-format)
  10460. (defun org-file-remote-p (file)
  10461. "Test whether FILE specifies a location on a remote system.
  10462. Return non-nil if the location is indeed remote.
  10463. For example, the filename \"/user@host:/foo\" specifies a location
  10464. on the system \"/user@host:\"."
  10465. (cond ((fboundp 'file-remote-p)
  10466. (file-remote-p file))
  10467. ((fboundp 'tramp-handle-file-remote-p)
  10468. (tramp-handle-file-remote-p file))
  10469. ((and (boundp 'ange-ftp-name-format)
  10470. (string-match (car ange-ftp-name-format) file))
  10471. t)))
  10472. ;;;; Refiling
  10473. (defun org-get-org-file ()
  10474. "Read a filename, with default directory `org-directory'."
  10475. (let ((default (or org-default-notes-file remember-data-file)))
  10476. (read-file-name (format "File name [%s]: " default)
  10477. (file-name-as-directory org-directory)
  10478. default)))
  10479. (defun org-notes-order-reversed-p ()
  10480. "Check if the current file should receive notes in reversed order."
  10481. (cond
  10482. ((not org-reverse-note-order) nil)
  10483. ((eq t org-reverse-note-order) t)
  10484. ((not (listp org-reverse-note-order)) nil)
  10485. (t (catch 'exit
  10486. (dolist (entry org-reverse-note-order)
  10487. (when (string-match (car entry) buffer-file-name)
  10488. (throw 'exit (cdr entry))))))))
  10489. (defvar org-refile-target-table nil
  10490. "The list of refile targets, created by `org-refile'.")
  10491. (defvar org-agenda-new-buffers nil
  10492. "Buffers created to visit agenda files.")
  10493. (defvar org-refile-cache nil
  10494. "Cache for refile targets.")
  10495. (defvar org-refile-markers nil
  10496. "All the markers used for caching refile locations.")
  10497. (defun org-refile-marker (pos)
  10498. "Get a new refile marker, but only if caching is in use."
  10499. (if (not org-refile-use-cache)
  10500. pos
  10501. (let ((m (make-marker)))
  10502. (move-marker m pos)
  10503. (push m org-refile-markers)
  10504. m)))
  10505. (defun org-refile-cache-clear ()
  10506. "Clear the refile cache and disable all the markers."
  10507. (dolist (m org-refile-markers) (move-marker m nil))
  10508. (setq org-refile-markers nil)
  10509. (setq org-refile-cache nil)
  10510. (message "Refile cache has been cleared"))
  10511. (defun org-refile-cache-check-set (set)
  10512. "Check if all the markers in the cache still have live buffers."
  10513. (let (marker)
  10514. (catch 'exit
  10515. (while (and set (setq marker (nth 3 (pop set))))
  10516. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10517. (when (and marker (null (marker-buffer marker)))
  10518. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10519. (sit-for 3)
  10520. (throw 'exit nil)))
  10521. t)))
  10522. (defun org-refile-cache-put (set &rest identifiers)
  10523. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10524. (let* ((key (sha1 (prin1-to-string identifiers)))
  10525. (entry (assoc key org-refile-cache)))
  10526. (if entry
  10527. (setcdr entry set)
  10528. (push (cons key set) org-refile-cache))))
  10529. (defun org-refile-cache-get (&rest identifiers)
  10530. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10531. (cond
  10532. ((not org-refile-cache) nil)
  10533. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10534. (t
  10535. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10536. org-refile-cache))))
  10537. (and set (org-refile-cache-check-set set) set)))))
  10538. (defvar org-outline-path-cache nil
  10539. "Alist between buffer positions and outline paths.
  10540. It value is an alist (POSITION . PATH) where POSITION is the
  10541. buffer position at the beginning of an entry and PATH is a list
  10542. of strings describing the outline path for that entry, in reverse
  10543. order.")
  10544. (defun org-refile-get-targets (&optional default-buffer)
  10545. "Produce a table with refile targets."
  10546. (let ((case-fold-search nil)
  10547. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10548. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10549. targets tgs files desc descre)
  10550. (message "Getting targets...")
  10551. (with-current-buffer (or default-buffer (current-buffer))
  10552. (dolist (entry entries)
  10553. (setq files (car entry) desc (cdr entry))
  10554. (cond
  10555. ((null files) (setq files (list (current-buffer))))
  10556. ((eq files 'org-agenda-files)
  10557. (setq files (org-agenda-files 'unrestricted)))
  10558. ((and (symbolp files) (fboundp files))
  10559. (setq files (funcall files)))
  10560. ((and (symbolp files) (boundp files))
  10561. (setq files (symbol-value files))))
  10562. (when (stringp files) (setq files (list files)))
  10563. (cond
  10564. ((eq (car desc) :tag)
  10565. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10566. ((eq (car desc) :todo)
  10567. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10568. ((eq (car desc) :regexp)
  10569. (setq descre (cdr desc)))
  10570. ((eq (car desc) :level)
  10571. (setq descre (concat "^\\*\\{" (number-to-string
  10572. (if org-odd-levels-only
  10573. (1- (* 2 (cdr desc)))
  10574. (cdr desc)))
  10575. "\\}[ \t]")))
  10576. ((eq (car desc) :maxlevel)
  10577. (setq descre (concat "^\\*\\{1," (number-to-string
  10578. (if org-odd-levels-only
  10579. (1- (* 2 (cdr desc)))
  10580. (cdr desc)))
  10581. "\\}[ \t]")))
  10582. (t (error "Bad refiling target description %s" desc)))
  10583. (dolist (f files)
  10584. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10585. (or
  10586. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10587. (progn
  10588. (when (bufferp f)
  10589. (setq f (buffer-file-name (buffer-base-buffer f))))
  10590. (setq f (and f (expand-file-name f)))
  10591. (when (eq org-refile-use-outline-path 'file)
  10592. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10593. (org-with-wide-buffer
  10594. (goto-char (point-min))
  10595. (setq org-outline-path-cache nil)
  10596. (while (re-search-forward descre nil t)
  10597. (beginning-of-line)
  10598. (let ((case-fold-search nil))
  10599. (looking-at org-complex-heading-regexp))
  10600. (let ((begin (point))
  10601. (heading (match-string-no-properties 4)))
  10602. (unless (or (and
  10603. org-refile-target-verify-function
  10604. (not
  10605. (funcall org-refile-target-verify-function)))
  10606. (not heading))
  10607. (let ((re (format org-complex-heading-regexp-format
  10608. (regexp-quote heading)))
  10609. (target
  10610. (if (not org-refile-use-outline-path) heading
  10611. (mapconcat
  10612. #'org-protect-slash
  10613. (append
  10614. (pcase org-refile-use-outline-path
  10615. (`file (list (file-name-nondirectory
  10616. (buffer-file-name
  10617. (buffer-base-buffer)))))
  10618. (`full-file-path
  10619. (list (buffer-file-name
  10620. (buffer-base-buffer))))
  10621. (_ nil))
  10622. (org-get-outline-path t t))
  10623. "/"))))
  10624. (push (list target f re (org-refile-marker (point)))
  10625. tgs)))
  10626. (when (= (point) begin)
  10627. ;; Verification function has not moved point.
  10628. (end-of-line)))))))
  10629. (when org-refile-use-cache
  10630. (org-refile-cache-put tgs (buffer-file-name) descre))
  10631. (setq targets (append tgs targets))))))
  10632. (message "Getting targets...done")
  10633. (delete-dups (nreverse targets))))
  10634. (defun org-protect-slash (s)
  10635. (replace-regexp-in-string "/" "\\/" s nil t))
  10636. (defun org--get-outline-path-1 (&optional use-cache)
  10637. "Return outline path to current headline.
  10638. Outline path is a list of strings, in reverse order. When
  10639. optional argument USE-CACHE is non-nil, make use of a cache. See
  10640. `org-get-outline-path' for details.
  10641. Assume buffer is widened and point is on a headline."
  10642. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10643. (let ((p (point))
  10644. (heading (let ((case-fold-search nil))
  10645. (looking-at org-complex-heading-regexp)
  10646. (if (not (match-end 4)) ""
  10647. ;; Remove statistics cookies.
  10648. (org-trim
  10649. (org-link-display-format
  10650. (replace-regexp-in-string
  10651. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10652. (match-string-no-properties 4))))))))
  10653. (if (org-up-heading-safe)
  10654. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10655. (when use-cache
  10656. (push (cons p path) org-outline-path-cache))
  10657. path)
  10658. ;; This is a new root node. Since we assume we are moving
  10659. ;; forward, we can drop previous cache so as to limit number
  10660. ;; of associations there.
  10661. (let ((path (list heading)))
  10662. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10663. path)))))
  10664. (defun org-get-outline-path (&optional with-self use-cache)
  10665. "Return the outline path to the current entry.
  10666. An outline path is a list of ancestors for current headline, as
  10667. a list of strings. Statistics cookies are removed and links are
  10668. replaced with their description, if any, or their path otherwise.
  10669. When optional argument WITH-SELF is non-nil, the path also
  10670. includes the current headline.
  10671. When optional argument USE-CACHE is non-nil, cache outline paths
  10672. between calls to this function so as to avoid backtracking. This
  10673. argument is useful when planning to find more than one outline
  10674. path in the same document. In that case, there are two
  10675. conditions to satisfy:
  10676. - `org-outline-path-cache' is set to nil before starting the
  10677. process;
  10678. - outline paths are computed by increasing buffer positions."
  10679. (org-with-wide-buffer
  10680. (and (or (and with-self (org-back-to-heading t))
  10681. (org-up-heading-safe))
  10682. (reverse (org--get-outline-path-1 use-cache)))))
  10683. (defun org-format-outline-path (path &optional width prefix separator)
  10684. "Format the outline path PATH for display.
  10685. WIDTH is the maximum number of characters that is available.
  10686. PREFIX is a prefix to be included in the returned string,
  10687. such as the file name.
  10688. SEPARATOR is inserted between the different parts of the path,
  10689. the default is \"/\"."
  10690. (setq width (or width 79))
  10691. (setq path (delq nil path))
  10692. (unless (> width 0)
  10693. (user-error "Argument `width' must be positive"))
  10694. (setq separator (or separator "/"))
  10695. (let* ((org-odd-levels-only nil)
  10696. (fpath (concat
  10697. prefix (and prefix path separator)
  10698. (mapconcat
  10699. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10700. (cl-loop for head in path
  10701. for n from 0
  10702. collect (org-add-props
  10703. head nil 'face
  10704. (nth (% n org-n-level-faces) org-level-faces)))
  10705. separator))))
  10706. (when (> (length fpath) width)
  10707. (if (< width 7)
  10708. ;; It's unlikely that `width' will be this small, but don't
  10709. ;; waste characters by adding ".." if it is.
  10710. (setq fpath (substring fpath 0 width))
  10711. (setf (substring fpath (- width 2)) "..")))
  10712. fpath))
  10713. (defun org-display-outline-path (&optional file current separator just-return-string)
  10714. "Display the current outline path in the echo area.
  10715. If FILE is non-nil, prepend the output with the file name.
  10716. If CURRENT is non-nil, append the current heading to the output.
  10717. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10718. the different parts of the path and defaults to \"/\".
  10719. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10720. (interactive "P")
  10721. (let* (case-fold-search
  10722. (bfn (buffer-file-name (buffer-base-buffer)))
  10723. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10724. res)
  10725. (when current (setq path (append path
  10726. (save-excursion
  10727. (org-back-to-heading t)
  10728. (when (looking-at org-complex-heading-regexp)
  10729. (list (match-string 4)))))))
  10730. (setq res
  10731. (org-format-outline-path
  10732. path
  10733. (1- (frame-width))
  10734. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10735. separator))
  10736. (if just-return-string
  10737. (org-no-properties res)
  10738. (org-unlogged-message "%s" res))))
  10739. (defvar org-refile-history nil
  10740. "History for refiling operations.")
  10741. (defvar org-after-refile-insert-hook nil
  10742. "Hook run after `org-refile' has inserted its stuff at the new location.
  10743. Note that this is still *before* the stuff will be removed from
  10744. the *old* location.")
  10745. (defvar org-capture-last-stored-marker)
  10746. (defvar org-refile-keep nil
  10747. "Non-nil means `org-refile' will copy instead of refile.")
  10748. (defun org-copy ()
  10749. "Like `org-refile', but copy."
  10750. (interactive)
  10751. (let ((org-refile-keep t))
  10752. (funcall 'org-refile nil nil nil "Copy")))
  10753. (defun org-refile (&optional arg default-buffer rfloc msg)
  10754. "Move the entry or entries at point to another heading.
  10755. The list of target headings is compiled using the information in
  10756. `org-refile-targets', which see.
  10757. At the target location, the entry is filed as a subitem of the
  10758. target heading. Depending on `org-reverse-note-order', the new
  10759. subitem will either be the first or the last subitem.
  10760. If there is an active region, all entries in that region will be
  10761. refiled. However, the region must fulfill the requirement that
  10762. the first heading sets the top-level of the moved text.
  10763. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10764. location
  10765. and not actually move anything.
  10766. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10767. location where the last
  10768. refiling operation has put the subtree.
  10769. With a numeric prefix argument of `2', refile to the running clock.
  10770. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10771. being set to t and copy to the target location, don't move it.
  10772. Beware that keeping refiled entries may result in duplicated ID
  10773. properties.
  10774. RFLOC can be a refile location obtained in a different way.
  10775. MSG is a string to replace \"Refile\" in the default prompt with
  10776. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10777. See also `org-refile-use-outline-path'.
  10778. If you are using target caching (see `org-refile-use-cache'), you
  10779. have to clear the target cache in order to find new targets.
  10780. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10781. prefix argument (`C-u C-u C-u C-c C-w')."
  10782. (interactive "P")
  10783. (if (member arg '(0 (64)))
  10784. (org-refile-cache-clear)
  10785. (let* ((actionmsg (cond (msg msg)
  10786. ((equal arg 3) "Refile (and keep)")
  10787. (t "Refile")))
  10788. (regionp (org-region-active-p))
  10789. (region-start (and regionp (region-beginning)))
  10790. (region-end (and regionp (region-end)))
  10791. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10792. pos it nbuf file level reversed)
  10793. (setq last-command nil)
  10794. (when regionp
  10795. (goto-char region-start)
  10796. (or (bolp) (goto-char (point-at-bol)))
  10797. (setq region-start (point))
  10798. (unless (or (org-kill-is-subtree-p
  10799. (buffer-substring region-start region-end))
  10800. (prog1 org-refile-active-region-within-subtree
  10801. (let ((s (point-at-eol)))
  10802. (org-toggle-heading)
  10803. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10804. (user-error "The region is not a (sequence of) subtree(s)")))
  10805. (if (equal arg '(16))
  10806. (org-refile-goto-last-stored)
  10807. (when (or
  10808. (and (equal arg 2)
  10809. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10810. (prog1
  10811. (setq it (list (or org-clock-heading "running clock")
  10812. (buffer-file-name
  10813. (marker-buffer org-clock-hd-marker))
  10814. ""
  10815. (marker-position org-clock-hd-marker)))
  10816. (setq arg nil)))
  10817. (setq it
  10818. (or rfloc
  10819. (let (heading-text)
  10820. (save-excursion
  10821. (unless (and arg (listp arg))
  10822. (org-back-to-heading t)
  10823. (setq heading-text
  10824. (replace-regexp-in-string
  10825. org-bracket-link-regexp
  10826. "\\3"
  10827. (or (nth 4 (org-heading-components))
  10828. ""))))
  10829. (org-refile-get-location
  10830. (cond ((and arg (listp arg)) "Goto")
  10831. (regionp (concat actionmsg " region to"))
  10832. (t (concat actionmsg " subtree \""
  10833. heading-text "\" to")))
  10834. default-buffer
  10835. (and (not (equal '(4) arg))
  10836. org-refile-allow-creating-parent-nodes)))))))
  10837. (setq file (nth 1 it)
  10838. pos (nth 3 it))
  10839. (when (and (not arg)
  10840. pos
  10841. (equal (buffer-file-name) file)
  10842. (if regionp
  10843. (and (>= pos region-start)
  10844. (<= pos region-end))
  10845. (and (>= pos (point))
  10846. (< pos (save-excursion
  10847. (org-end-of-subtree t t))))))
  10848. (error "Cannot refile to position inside the tree or region"))
  10849. (setq nbuf (or (find-buffer-visiting file)
  10850. (find-file-noselect file)))
  10851. (if (and arg (not (equal arg 3)))
  10852. (progn
  10853. (pop-to-buffer-same-window nbuf)
  10854. (goto-char pos)
  10855. (org-show-context 'org-goto))
  10856. (if regionp
  10857. (progn
  10858. (org-kill-new (buffer-substring region-start region-end))
  10859. (org-save-markers-in-region region-start region-end))
  10860. (org-copy-subtree 1 nil t))
  10861. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10862. (find-file-noselect file)))
  10863. (setq reversed (org-notes-order-reversed-p))
  10864. (org-with-wide-buffer
  10865. (if pos
  10866. (progn
  10867. (goto-char pos)
  10868. (looking-at org-outline-regexp)
  10869. (setq level (org-get-valid-level (funcall outline-level) 1))
  10870. (goto-char
  10871. (if reversed
  10872. (or (outline-next-heading) (point-max))
  10873. (or (save-excursion (org-get-next-sibling))
  10874. (org-end-of-subtree t t)
  10875. (point-max)))))
  10876. (setq level 1)
  10877. (if (not reversed)
  10878. (goto-char (point-max))
  10879. (goto-char (point-min))
  10880. (or (outline-next-heading) (goto-char (point-max)))))
  10881. (unless (bolp) (newline))
  10882. (org-paste-subtree level nil nil t)
  10883. (when org-log-refile
  10884. (org-add-log-setup 'refile nil nil org-log-refile)
  10885. (unless (eq org-log-refile 'note)
  10886. (save-excursion (org-add-log-note))))
  10887. (and org-auto-align-tags
  10888. (let ((org-loop-over-headlines-in-active-region nil))
  10889. (org-set-tags nil t)))
  10890. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10891. :last-refile)))
  10892. (when bookmark-name
  10893. (with-demoted-errors
  10894. (bookmark-set bookmark-name))))
  10895. ;; If we are refiling for capture, make sure that the
  10896. ;; last-capture pointers point here
  10897. (when (bound-and-true-p org-capture-is-refiling)
  10898. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10899. :last-capture-marker)))
  10900. (when bookmark-name
  10901. (with-demoted-errors
  10902. (bookmark-set bookmark-name))))
  10903. (move-marker org-capture-last-stored-marker (point)))
  10904. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10905. (run-hooks 'org-after-refile-insert-hook)))
  10906. (unless org-refile-keep
  10907. (if regionp
  10908. (delete-region (point) (+ (point) (- region-end region-start)))
  10909. (delete-region
  10910. (and (org-back-to-heading t) (point))
  10911. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10912. (when (featurep 'org-inlinetask)
  10913. (org-inlinetask-remove-END-maybe))
  10914. (setq org-markers-to-move nil)
  10915. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10916. (defun org-refile-goto-last-stored ()
  10917. "Go to the location where the last refile was stored."
  10918. (interactive)
  10919. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10920. (message "This is the location of the last refile"))
  10921. (defun org-refile--get-location (refloc tbl)
  10922. "When user refile to REFLOC, find the associated target in TBL.
  10923. Also check `org-refile-target-table'."
  10924. (car (delq
  10925. nil
  10926. (mapcar
  10927. (lambda (r) (or (assoc r tbl)
  10928. (assoc r org-refile-target-table)))
  10929. (list (replace-regexp-in-string "/$" "" refloc)
  10930. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10931. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10932. "Prompt the user for a refile location, using PROMPT.
  10933. PROMPT should not be suffixed with a colon and a space, because
  10934. this function appends the default value from
  10935. `org-refile-history' automatically, if that is not empty."
  10936. (let ((org-refile-targets org-refile-targets)
  10937. (org-refile-use-outline-path org-refile-use-outline-path))
  10938. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10939. (unless org-refile-target-table
  10940. (user-error "No refile targets"))
  10941. (let* ((cbuf (current-buffer))
  10942. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10943. (cfunc (if (and org-refile-use-outline-path
  10944. org-outline-path-complete-in-steps)
  10945. #'org-olpath-completing-read
  10946. #'completing-read))
  10947. (extra (if org-refile-use-outline-path "/" ""))
  10948. (cbnex (concat (buffer-name) extra))
  10949. (filename (and cfn (expand-file-name cfn)))
  10950. (tbl (mapcar
  10951. (lambda (x)
  10952. (if (and (not (member org-refile-use-outline-path
  10953. '(file full-file-path)))
  10954. (not (equal filename (nth 1 x))))
  10955. (cons (concat (car x) extra " ("
  10956. (file-name-nondirectory (nth 1 x)) ")")
  10957. (cdr x))
  10958. (cons (concat (car x) extra) (cdr x))))
  10959. org-refile-target-table))
  10960. (completion-ignore-case t)
  10961. cdef
  10962. (prompt (concat prompt
  10963. (or (and (car org-refile-history)
  10964. (concat " (default " (car org-refile-history) ")"))
  10965. (and (assoc cbnex tbl) (setq cdef cbnex)
  10966. (concat " (default " cbnex ")"))) ": "))
  10967. pa answ parent-target child parent old-hist)
  10968. (setq old-hist org-refile-history)
  10969. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10970. nil 'org-refile-history (or cdef (car org-refile-history))))
  10971. (if (setq pa (org-refile--get-location answ tbl))
  10972. (progn
  10973. (org-refile-check-position pa)
  10974. (when (or (not org-refile-history)
  10975. (not (eq old-hist org-refile-history))
  10976. (not (equal (car pa) (car org-refile-history))))
  10977. (setq org-refile-history
  10978. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10979. org-refile-history
  10980. (cdr org-refile-history))))
  10981. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10982. (pop org-refile-history)))
  10983. pa)
  10984. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10985. (progn
  10986. (setq parent (match-string 1 answ)
  10987. child (match-string 2 answ))
  10988. (setq parent-target (org-refile--get-location parent tbl))
  10989. (when (and parent-target
  10990. (or (eq new-nodes t)
  10991. (and (eq new-nodes 'confirm)
  10992. (y-or-n-p (format "Create new node \"%s\"? "
  10993. child)))))
  10994. (org-refile-new-child parent-target child)))
  10995. (user-error "Invalid target location")))))
  10996. (declare-function org-string-nw-p "org-macs" (s))
  10997. (defun org-refile-check-position (refile-pointer)
  10998. "Check if the refile pointer matches the headline to which it points."
  10999. (let* ((file (nth 1 refile-pointer))
  11000. (re (nth 2 refile-pointer))
  11001. (pos (nth 3 refile-pointer))
  11002. buffer)
  11003. (if (and (not (markerp pos)) (not file))
  11004. (user-error "Please indicate a target file in the refile path")
  11005. (when (org-string-nw-p re)
  11006. (setq buffer (if (markerp pos)
  11007. (marker-buffer pos)
  11008. (or (find-buffer-visiting file)
  11009. (find-file-noselect file))))
  11010. (with-current-buffer buffer
  11011. (org-with-wide-buffer
  11012. (goto-char pos)
  11013. (beginning-of-line 1)
  11014. (unless (looking-at-p re)
  11015. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  11016. (defun org-refile-new-child (parent-target child)
  11017. "Use refile target PARENT-TARGET to add new CHILD below it."
  11018. (unless parent-target
  11019. (error "Cannot find parent for new node"))
  11020. (let ((file (nth 1 parent-target))
  11021. (pos (nth 3 parent-target))
  11022. level)
  11023. (with-current-buffer (or (find-buffer-visiting file)
  11024. (find-file-noselect file))
  11025. (org-with-wide-buffer
  11026. (if pos
  11027. (goto-char pos)
  11028. (goto-char (point-max))
  11029. (unless (bolp) (newline)))
  11030. (when (looking-at org-outline-regexp)
  11031. (setq level (funcall outline-level))
  11032. (org-end-of-subtree t t))
  11033. (org-back-over-empty-lines)
  11034. (insert "\n" (make-string
  11035. (if pos (org-get-valid-level level 1) 1) ?*)
  11036. " " child "\n")
  11037. (beginning-of-line 0)
  11038. (list (concat (car parent-target) "/" child) file "" (point))))))
  11039. (defun org-olpath-completing-read (prompt collection &rest args)
  11040. "Read an outline path like a file name."
  11041. (let ((thetable collection))
  11042. (apply #'completing-read
  11043. prompt
  11044. (lambda (string predicate &optional flag)
  11045. (cond
  11046. ((eq flag nil) (try-completion string thetable))
  11047. ((eq flag t)
  11048. (let ((l (length string)))
  11049. (mapcar (lambda (x)
  11050. (let ((r (substring x l))
  11051. (f (if (string-match " ([^)]*)$" x)
  11052. (match-string 0 x)
  11053. "")))
  11054. (if (string-match "/" r)
  11055. (concat string (substring r 0 (match-end 0)) f)
  11056. x)))
  11057. (all-completions string thetable predicate))))
  11058. ;; Exact match?
  11059. ((eq flag 'lambda) (assoc string thetable))))
  11060. args)))
  11061. ;;;; Dynamic blocks
  11062. (defun org-find-dblock (name)
  11063. "Find the first dynamic block with name NAME in the buffer.
  11064. If not found, stay at current position and return nil."
  11065. (let ((case-fold-search t) pos)
  11066. (save-excursion
  11067. (goto-char (point-min))
  11068. (setq pos (and (re-search-forward
  11069. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11070. (match-beginning 0))))
  11071. (when pos (goto-char pos))
  11072. pos))
  11073. (defun org-create-dblock (plist)
  11074. "Create a dynamic block section, with parameters taken from PLIST.
  11075. PLIST must contain a :name entry which is used as the name of the block."
  11076. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11077. (end-of-line 1)
  11078. (newline))
  11079. (let ((col (current-column))
  11080. (name (plist-get plist :name)))
  11081. (insert "#+BEGIN: " name)
  11082. (while plist
  11083. (if (eq (car plist) :name)
  11084. (setq plist (cddr plist))
  11085. (insert " " (prin1-to-string (pop plist)))))
  11086. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11087. (beginning-of-line -2)))
  11088. (defun org-prepare-dblock ()
  11089. "Prepare dynamic block for refresh.
  11090. This empties the block, puts the cursor at the insert position and returns
  11091. the property list including an extra property :name with the block name."
  11092. (unless (looking-at org-dblock-start-re)
  11093. (user-error "Not at a dynamic block"))
  11094. (let* ((begdel (1+ (match-end 0)))
  11095. (name (org-no-properties (match-string 1)))
  11096. (params (append (list :name name)
  11097. (read (concat "(" (match-string 3) ")")))))
  11098. (save-excursion
  11099. (beginning-of-line 1)
  11100. (skip-chars-forward " \t")
  11101. (setq params (plist-put params :indentation-column (current-column))))
  11102. (unless (re-search-forward org-dblock-end-re nil t)
  11103. (error "Dynamic block not terminated"))
  11104. (setq params
  11105. (append params
  11106. (list :content (buffer-substring
  11107. begdel (match-beginning 0)))))
  11108. (delete-region begdel (match-beginning 0))
  11109. (goto-char begdel)
  11110. (open-line 1)
  11111. params))
  11112. (defun org-map-dblocks (&optional command)
  11113. "Apply COMMAND to all dynamic blocks in the current buffer.
  11114. If COMMAND is not given, use `org-update-dblock'."
  11115. (let ((cmd (or command 'org-update-dblock)))
  11116. (save-excursion
  11117. (goto-char (point-min))
  11118. (while (re-search-forward org-dblock-start-re nil t)
  11119. (goto-char (match-beginning 0))
  11120. (save-excursion
  11121. (condition-case nil
  11122. (funcall cmd)
  11123. (error (message "Error during update of dynamic block"))))
  11124. (unless (re-search-forward org-dblock-end-re nil t)
  11125. (error "Dynamic block not terminated"))))))
  11126. (defun org-dblock-update (&optional arg)
  11127. "User command for updating dynamic blocks.
  11128. Update the dynamic block at point. With prefix ARG, update all dynamic
  11129. blocks in the buffer."
  11130. (interactive "P")
  11131. (if arg
  11132. (org-update-all-dblocks)
  11133. (or (looking-at org-dblock-start-re)
  11134. (org-beginning-of-dblock))
  11135. (org-update-dblock)))
  11136. (defun org-update-dblock ()
  11137. "Update the dynamic block at point.
  11138. This means to empty the block, parse for parameters and then call
  11139. the correct writing function."
  11140. (interactive)
  11141. (save-excursion
  11142. (let* ((win (selected-window))
  11143. (pos (point))
  11144. (line (org-current-line))
  11145. (params (org-prepare-dblock))
  11146. (name (plist-get params :name))
  11147. (indent (plist-get params :indentation-column))
  11148. (cmd (intern (concat "org-dblock-write:" name))))
  11149. (message "Updating dynamic block `%s' at line %d..." name line)
  11150. (funcall cmd params)
  11151. (message "Updating dynamic block `%s' at line %d...done" name line)
  11152. (goto-char pos)
  11153. (when (and indent (> indent 0))
  11154. (setq indent (make-string indent ?\ ))
  11155. (save-excursion
  11156. (select-window win)
  11157. (org-beginning-of-dblock)
  11158. (forward-line 1)
  11159. (while (not (looking-at org-dblock-end-re))
  11160. (insert indent)
  11161. (beginning-of-line 2))
  11162. (when (looking-at org-dblock-end-re)
  11163. (and (looking-at "[ \t]+")
  11164. (replace-match ""))
  11165. (insert indent)))))))
  11166. (defun org-beginning-of-dblock ()
  11167. "Find the beginning of the dynamic block at point.
  11168. Error if there is no such block at point."
  11169. (let ((pos (point))
  11170. beg)
  11171. (end-of-line 1)
  11172. (if (and (re-search-backward org-dblock-start-re nil t)
  11173. (setq beg (match-beginning 0))
  11174. (re-search-forward org-dblock-end-re nil t)
  11175. (> (match-end 0) pos))
  11176. (goto-char beg)
  11177. (goto-char pos)
  11178. (error "Not in a dynamic block"))))
  11179. (defun org-update-all-dblocks ()
  11180. "Update all dynamic blocks in the buffer.
  11181. This function can be used in a hook."
  11182. (interactive)
  11183. (when (derived-mode-p 'org-mode)
  11184. (org-map-dblocks 'org-update-dblock)))
  11185. ;;;; Completion
  11186. (declare-function org-export-backend-options "ox" (cl-x) t)
  11187. (defun org-get-export-keywords ()
  11188. "Return a list of all currently understood export keywords.
  11189. Export keywords include options, block names, attributes and
  11190. keywords relative to each registered export back-end."
  11191. (let (keywords)
  11192. (dolist (backend
  11193. (bound-and-true-p org-export-registered-backends)
  11194. (delq nil keywords))
  11195. ;; Back-end name (for keywords, like #+LATEX:)
  11196. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11197. (dolist (option-entry (org-export-backend-options backend))
  11198. ;; Back-end options.
  11199. (push (nth 1 option-entry) keywords)))))
  11200. (defconst org-options-keywords
  11201. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11202. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11203. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11204. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11205. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11206. (defcustom org-structure-template-alist
  11207. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11208. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11209. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11210. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11211. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11212. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11213. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11214. ("L" "#+LaTeX: ")
  11215. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11216. ("H" "#+HTML: ")
  11217. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11218. ("A" "#+ASCII: ")
  11219. ("i" "#+INDEX: ?")
  11220. ("I" "#+INCLUDE: %file ?"))
  11221. "Structure completion elements.
  11222. This is a list of abbreviation keys and values. The value gets inserted
  11223. if you type `<' followed by the key and then press the completion key,
  11224. usually `TAB'. %file will be replaced by a file name after prompting
  11225. for the file using completion. The cursor will be placed at the position
  11226. of the `?' in the template.
  11227. There are two templates for each key, the first uses the original Org syntax,
  11228. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11229. the default when the /org-mtags.el/ module has been loaded. See also the
  11230. variable `org-mtags-prefer-muse-templates'."
  11231. :group 'org-completion
  11232. :type '(repeat
  11233. (list
  11234. (string :tag "Key")
  11235. (string :tag "Template")))
  11236. :version "26.1"
  11237. :package-version '(Org . "8.3"))
  11238. (defun org-try-structure-completion ()
  11239. "Try to complete a structure template before point.
  11240. This looks for strings like \"<e\" on an otherwise empty line and
  11241. expands them."
  11242. (let ((l (buffer-substring (point-at-bol) (point)))
  11243. a)
  11244. (when (and (looking-at "[ \t]*$")
  11245. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11246. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11247. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11248. (match-beginning 1)) a)
  11249. t)))
  11250. (defun org-complete-expand-structure-template (start cell)
  11251. "Expand a structure template."
  11252. (let ((rpl (nth 1 cell))
  11253. (ind ""))
  11254. (delete-region start (point))
  11255. (when (string-match "\\`[ \t]*#\\+" rpl)
  11256. (cond
  11257. ((bolp))
  11258. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11259. (setq ind (buffer-substring (point-at-bol) (point))))
  11260. (t (newline))))
  11261. (setq start (point))
  11262. (when (string-match "%file" rpl)
  11263. (setq rpl (replace-match
  11264. (concat
  11265. "\""
  11266. (save-match-data
  11267. (abbreviate-file-name (read-file-name "Include file: ")))
  11268. "\"")
  11269. t t rpl)))
  11270. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11271. (concat "\n" ind)))
  11272. (insert rpl)
  11273. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11274. ;;;; TODO, DEADLINE, Comments
  11275. (defun org-toggle-comment ()
  11276. "Change the COMMENT state of an entry."
  11277. (interactive)
  11278. (save-excursion
  11279. (org-back-to-heading)
  11280. (let ((case-fold-search nil))
  11281. (looking-at org-complex-heading-regexp))
  11282. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11283. (skip-chars-forward " \t")
  11284. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11285. (if (org-in-commented-heading-p t)
  11286. (delete-region (point)
  11287. (progn (search-forward " " (line-end-position) 'move)
  11288. (skip-chars-forward " \t")
  11289. (point)))
  11290. (insert org-comment-string)
  11291. (unless (eolp) (insert " ")))))
  11292. (defvar org-last-todo-state-is-todo nil
  11293. "This is non-nil when the last TODO state change led to a TODO state.
  11294. If the last change removed the TODO tag or switched to DONE, then
  11295. this is nil.")
  11296. (defvar org-setting-tags nil) ; dynamically skipped
  11297. (defvar org-todo-setup-filter-hook nil
  11298. "Hook for functions that pre-filter todo specs.
  11299. Each function takes a todo spec and returns either nil or the spec
  11300. transformed into canonical form." )
  11301. (defvar org-todo-get-default-hook nil
  11302. "Hook for functions that get a default item for todo.
  11303. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11304. nil or a string to be used for the todo mark." )
  11305. (defvar org-agenda-headline-snapshot-before-repeat)
  11306. (defun org-current-effective-time ()
  11307. "Return current time adjusted for `org-extend-today-until' variable."
  11308. (let* ((ct (org-current-time))
  11309. (dct (decode-time ct))
  11310. (ct1
  11311. (cond
  11312. (org-use-last-clock-out-time-as-effective-time
  11313. (or (org-clock-get-last-clock-out-time) ct))
  11314. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11315. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11316. (t ct))))
  11317. ct1))
  11318. (defun org-todo-yesterday (&optional arg)
  11319. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11320. (interactive "P")
  11321. (if (eq major-mode 'org-agenda-mode)
  11322. (apply 'org-agenda-todo-yesterday arg)
  11323. (let* ((org-use-effective-time t)
  11324. (hour (nth 2 (decode-time (org-current-time))))
  11325. (org-extend-today-until (1+ hour)))
  11326. (org-todo arg))))
  11327. (defvar org-block-entry-blocking ""
  11328. "First entry preventing the TODO state change.")
  11329. (defun org-cancel-repeater ()
  11330. "Cancel a repeater by setting its numeric value to zero."
  11331. (interactive)
  11332. (save-excursion
  11333. (org-back-to-heading t)
  11334. (let ((bound1 (point))
  11335. (bound0 (save-excursion (outline-next-heading) (point))))
  11336. (when (and (re-search-forward
  11337. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11338. org-deadline-time-regexp "\\)\\|\\("
  11339. org-ts-regexp "\\)")
  11340. bound0 t)
  11341. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11342. bound1 t))
  11343. (replace-match "0" t nil nil 1)))))
  11344. (defvar org-state)
  11345. (defvar org-blocked-by-checkboxes)
  11346. (defun org-todo (&optional arg)
  11347. "Change the TODO state of an item.
  11348. The state of an item is given by a keyword at the start of the heading,
  11349. like
  11350. *** TODO Write paper
  11351. *** DONE Call mom
  11352. The different keywords are specified in the variable `org-todo-keywords'.
  11353. By default the available states are \"TODO\" and \"DONE\". So, for this
  11354. example: when the item starts with TODO, it is changed to DONE.
  11355. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11356. DONE are present, add TODO at the beginning of the heading.
  11357. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11358. state.
  11359. With numeric prefix ARG, switch to that state.
  11360. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11361. next set of TODO \
  11362. keywords (nextset).
  11363. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11364. prefix, circumvent any state blocking.
  11365. With a numeric prefix arg of 0, inhibit note taking for the change.
  11366. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11367. When called through ELisp, arg is also interpreted in the following way:
  11368. `none' -> empty state
  11369. \"\" -> switch to empty state
  11370. `done' -> switch to DONE
  11371. `nextset' -> switch to the next set of keywords
  11372. `previousset' -> switch to the previous set of keywords
  11373. \"WAITING\" -> switch to the specified keyword, but only if it
  11374. really is a member of `org-todo-keywords'."
  11375. (interactive "P")
  11376. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11377. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11378. 'region-start-level 'region))
  11379. org-loop-over-headlines-in-active-region)
  11380. (org-map-entries
  11381. `(org-todo ,arg)
  11382. org-loop-over-headlines-in-active-region
  11383. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11384. (when (equal arg '(16)) (setq arg 'nextset))
  11385. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11386. (let ((org-blocker-hook org-blocker-hook)
  11387. commentp
  11388. case-fold-search)
  11389. (when (equal arg '(64))
  11390. (setq arg nil org-blocker-hook nil))
  11391. (when (and org-blocker-hook
  11392. (or org-inhibit-blocking
  11393. (org-entry-get nil "NOBLOCKING")))
  11394. (setq org-blocker-hook nil))
  11395. (save-excursion
  11396. (catch 'exit
  11397. (org-back-to-heading t)
  11398. (when (org-in-commented-heading-p t)
  11399. (org-toggle-comment)
  11400. (setq commentp t))
  11401. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11402. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11403. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11404. (let* ((match-data (match-data))
  11405. (startpos (point-at-bol))
  11406. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11407. (org-log-done org-log-done)
  11408. (org-log-repeat org-log-repeat)
  11409. (org-todo-log-states org-todo-log-states)
  11410. (org-inhibit-logging
  11411. (if (equal arg 0)
  11412. (progn (setq arg nil) 'note) org-inhibit-logging))
  11413. (this (match-string 1))
  11414. (hl-pos (match-beginning 0))
  11415. (head (org-get-todo-sequence-head this))
  11416. (ass (assoc head org-todo-kwd-alist))
  11417. (interpret (nth 1 ass))
  11418. (done-word (nth 3 ass))
  11419. (final-done-word (nth 4 ass))
  11420. (org-last-state (or this ""))
  11421. (completion-ignore-case t)
  11422. (member (member this org-todo-keywords-1))
  11423. (tail (cdr member))
  11424. (org-state (cond
  11425. ((and org-todo-key-trigger
  11426. (or (and (equal arg '(4))
  11427. (eq org-use-fast-todo-selection 'prefix))
  11428. (and (not arg) org-use-fast-todo-selection
  11429. (not (eq org-use-fast-todo-selection
  11430. 'prefix)))))
  11431. ;; Use fast selection.
  11432. (org-fast-todo-selection))
  11433. ((and (equal arg '(4))
  11434. (or (not org-use-fast-todo-selection)
  11435. (not org-todo-key-trigger)))
  11436. ;; Read a state with completion.
  11437. (completing-read
  11438. "State: " (mapcar #'list org-todo-keywords-1)
  11439. nil t))
  11440. ((eq arg 'right)
  11441. (if this
  11442. (if tail (car tail) nil)
  11443. (car org-todo-keywords-1)))
  11444. ((eq arg 'left)
  11445. (unless (equal member org-todo-keywords-1)
  11446. (if this
  11447. (nth (- (length org-todo-keywords-1)
  11448. (length tail) 2)
  11449. org-todo-keywords-1)
  11450. (org-last org-todo-keywords-1))))
  11451. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11452. (setq arg nil))) ;hack to fall back to cycling
  11453. (arg
  11454. ;; User or caller requests a specific state.
  11455. (cond
  11456. ((equal arg "") nil)
  11457. ((eq arg 'none) nil)
  11458. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11459. ((eq arg 'nextset)
  11460. (or (car (cdr (member head org-todo-heads)))
  11461. (car org-todo-heads)))
  11462. ((eq arg 'previousset)
  11463. (let ((org-todo-heads (reverse org-todo-heads)))
  11464. (or (car (cdr (member head org-todo-heads)))
  11465. (car org-todo-heads))))
  11466. ((car (member arg org-todo-keywords-1)))
  11467. ((stringp arg)
  11468. (user-error "State `%s' not valid in this file" arg))
  11469. ((nth (1- (prefix-numeric-value arg))
  11470. org-todo-keywords-1))))
  11471. ((null member) (or head (car org-todo-keywords-1)))
  11472. ((equal this final-done-word) nil) ;-> make empty
  11473. ((null tail) nil) ;-> first entry
  11474. ((memq interpret '(type priority))
  11475. (if (eq this-command last-command)
  11476. (car tail)
  11477. (if (> (length tail) 0)
  11478. (or done-word (car org-done-keywords))
  11479. nil)))
  11480. (t
  11481. (car tail))))
  11482. (org-state (or
  11483. (run-hook-with-args-until-success
  11484. 'org-todo-get-default-hook org-state org-last-state)
  11485. org-state))
  11486. (next (if org-state (concat " " org-state " ") " "))
  11487. (change-plist (list :type 'todo-state-change :from this :to org-state
  11488. :position startpos))
  11489. dolog now-done-p)
  11490. (when org-blocker-hook
  11491. (let (org-blocked-by-checkboxes block-reason)
  11492. (setq org-last-todo-state-is-todo
  11493. (not (member this org-done-keywords)))
  11494. (unless (save-excursion
  11495. (save-match-data
  11496. (org-with-wide-buffer
  11497. (run-hook-with-args-until-failure
  11498. 'org-blocker-hook change-plist))))
  11499. (setq block-reason (if org-blocked-by-checkboxes
  11500. "contained checkboxes"
  11501. (format "\"%s\"" org-block-entry-blocking)))
  11502. (if (called-interactively-p 'interactive)
  11503. (user-error "TODO state change from %s to %s blocked (by %s)"
  11504. this org-state block-reason)
  11505. ;; Fail silently.
  11506. (message "TODO state change from %s to %s blocked (by %s)"
  11507. this org-state block-reason)
  11508. (throw 'exit nil)))))
  11509. (store-match-data match-data)
  11510. (replace-match next t t)
  11511. (cond ((equal this org-state)
  11512. (message "TODO state was already %s" (org-trim next)))
  11513. ((pos-visible-in-window-p hl-pos)
  11514. (message "TODO state changed to %s" (org-trim next))))
  11515. (unless head
  11516. (setq head (org-get-todo-sequence-head org-state)
  11517. ass (assoc head org-todo-kwd-alist)
  11518. interpret (nth 1 ass)
  11519. done-word (nth 3 ass)
  11520. final-done-word (nth 4 ass)))
  11521. (when (memq arg '(nextset previousset))
  11522. (message "Keyword-Set %d/%d: %s"
  11523. (- (length org-todo-sets) -1
  11524. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11525. (length org-todo-sets)
  11526. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11527. (setq org-last-todo-state-is-todo
  11528. (not (member org-state org-done-keywords)))
  11529. (setq now-done-p (and (member org-state org-done-keywords)
  11530. (not (member this org-done-keywords))))
  11531. (and logging (org-local-logging logging))
  11532. (when (and (or org-todo-log-states org-log-done)
  11533. (not (eq org-inhibit-logging t))
  11534. (not (memq arg '(nextset previousset))))
  11535. ;; We need to look at recording a time and note.
  11536. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11537. (nth 2 (assoc this org-todo-log-states))))
  11538. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11539. (setq dolog 'time))
  11540. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11541. (and org-state
  11542. (member org-state org-not-done-keywords)
  11543. (not (member this org-not-done-keywords))))
  11544. ;; This is now a todo state and was not one before
  11545. ;; If there was a CLOSED time stamp, get rid of it.
  11546. (org-add-planning-info nil nil 'closed))
  11547. (when (and now-done-p org-log-done)
  11548. ;; It is now done, and it was not done before.
  11549. (org-add-planning-info 'closed (org-current-effective-time))
  11550. (when (and (not dolog) (eq 'note org-log-done))
  11551. (org-add-log-setup 'done org-state this 'note)))
  11552. (when (and org-state dolog)
  11553. ;; This is a non-nil state, and we need to log it.
  11554. (org-add-log-setup 'state org-state this dolog)))
  11555. ;; Fixup tag positioning.
  11556. (org-todo-trigger-tag-changes org-state)
  11557. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11558. (when org-provide-todo-statistics
  11559. (org-update-parent-todo-statistics))
  11560. (run-hooks 'org-after-todo-state-change-hook)
  11561. (when (and arg (not (member org-state org-done-keywords)))
  11562. (setq head (org-get-todo-sequence-head org-state)))
  11563. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11564. ;; Do we need to trigger a repeat?
  11565. (when now-done-p
  11566. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11567. ;; This is for the agenda, take a snapshot of the headline.
  11568. (save-match-data
  11569. (setq org-agenda-headline-snapshot-before-repeat
  11570. (org-get-heading))))
  11571. (org-auto-repeat-maybe org-state))
  11572. ;; Fixup cursor location if close to the keyword.
  11573. (when (and (outline-on-heading-p)
  11574. (not (bolp))
  11575. (save-excursion (beginning-of-line 1)
  11576. (looking-at org-todo-line-regexp))
  11577. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11578. (goto-char (or (match-end 2) (match-end 1)))
  11579. (and (looking-at " ") (just-one-space)))
  11580. (when org-trigger-hook
  11581. (save-excursion
  11582. (run-hook-with-args 'org-trigger-hook change-plist)))
  11583. (when commentp (org-toggle-comment))))))))
  11584. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11585. "Block turning an entry into a TODO, using the hierarchy.
  11586. This checks whether the current task should be blocked from state
  11587. changes. Such blocking occurs when:
  11588. 1. The task has children which are not all in a completed state.
  11589. 2. A task has a parent with the property :ORDERED:, and there
  11590. are siblings prior to the current task with incomplete
  11591. status.
  11592. 3. The parent of the task is blocked because it has siblings that should
  11593. be done first, or is child of a block grandparent TODO entry."
  11594. (if (not org-enforce-todo-dependencies)
  11595. t ; if locally turned off don't block
  11596. (catch 'dont-block
  11597. ;; If this is not a todo state change, or if this entry is already DONE,
  11598. ;; do not block
  11599. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11600. (member (plist-get change-plist :from)
  11601. (cons 'done org-done-keywords))
  11602. (member (plist-get change-plist :to)
  11603. (cons 'todo org-not-done-keywords))
  11604. (not (plist-get change-plist :to)))
  11605. (throw 'dont-block t))
  11606. ;; If this task has children, and any are undone, it's blocked
  11607. (save-excursion
  11608. (org-back-to-heading t)
  11609. (let ((this-level (funcall outline-level)))
  11610. (outline-next-heading)
  11611. (let ((child-level (funcall outline-level)))
  11612. (while (and (not (eobp))
  11613. (> child-level this-level))
  11614. ;; this todo has children, check whether they are all
  11615. ;; completed
  11616. (when (and (not (org-entry-is-done-p))
  11617. (org-entry-is-todo-p))
  11618. (setq org-block-entry-blocking (org-get-heading))
  11619. (throw 'dont-block nil))
  11620. (outline-next-heading)
  11621. (setq child-level (funcall outline-level))))))
  11622. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11623. ;; any previous siblings are undone, it's blocked
  11624. (save-excursion
  11625. (org-back-to-heading t)
  11626. (let* ((pos (point))
  11627. (parent-pos (and (org-up-heading-safe) (point)))
  11628. (case-fold-search nil))
  11629. (unless parent-pos (throw 'dont-block t)) ; no parent
  11630. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11631. (forward-line 1)
  11632. (re-search-forward org-not-done-heading-regexp pos t))
  11633. (setq org-block-entry-blocking (match-string 0))
  11634. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11635. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11636. (while t
  11637. (goto-char parent-pos)
  11638. (unless (looking-at org-not-done-heading-regexp)
  11639. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11640. (setq pos (point))
  11641. (setq parent-pos (and (org-up-heading-safe) (point)))
  11642. (unless parent-pos (throw 'dont-block t)) ; no parent
  11643. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11644. (forward-line 1)
  11645. (re-search-forward org-not-done-heading-regexp pos t)
  11646. (setq org-block-entry-blocking (org-get-heading)))
  11647. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11648. (defcustom org-track-ordered-property-with-tag nil
  11649. "Should the ORDERED property also be shown as a tag?
  11650. The ORDERED property decides if an entry should require subtasks to be
  11651. completed in sequence. Since a property is not very visible, setting
  11652. this option means that toggling the ORDERED property with the command
  11653. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11654. not relevant for the behavior, but it makes things more visible.
  11655. Note that toggling the tag with tags commands will not change the property
  11656. and therefore not influence behavior!
  11657. This can be t, meaning the tag ORDERED should be used, It can also be a
  11658. string to select a different tag for this task."
  11659. :group 'org-todo
  11660. :type '(choice
  11661. (const :tag "No tracking" nil)
  11662. (const :tag "Track with ORDERED tag" t)
  11663. (string :tag "Use other tag")))
  11664. (defun org-toggle-ordered-property ()
  11665. "Toggle the ORDERED property of the current entry.
  11666. For better visibility, you can track the value of this property with a tag.
  11667. See variable `org-track-ordered-property-with-tag'."
  11668. (interactive)
  11669. (let* ((t1 org-track-ordered-property-with-tag)
  11670. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11671. (save-excursion
  11672. (org-back-to-heading)
  11673. (if (org-entry-get nil "ORDERED")
  11674. (progn
  11675. (org-delete-property "ORDERED")
  11676. (and tag (org-toggle-tag tag 'off))
  11677. (message "Subtasks can be completed in arbitrary order"))
  11678. (org-entry-put nil "ORDERED" "t")
  11679. (and tag (org-toggle-tag tag 'on))
  11680. (message "Subtasks must be completed in sequence")))))
  11681. (defun org-block-todo-from-checkboxes (change-plist)
  11682. "Block turning an entry into a TODO, using checkboxes.
  11683. This checks whether the current task should be blocked from state
  11684. changes because there are unchecked boxes in this entry."
  11685. (if (not org-enforce-todo-checkbox-dependencies)
  11686. t ; if locally turned off don't block
  11687. (catch 'dont-block
  11688. ;; If this is not a todo state change, or if this entry is already DONE,
  11689. ;; do not block
  11690. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11691. (member (plist-get change-plist :from)
  11692. (cons 'done org-done-keywords))
  11693. (member (plist-get change-plist :to)
  11694. (cons 'todo org-not-done-keywords))
  11695. (not (plist-get change-plist :to)))
  11696. (throw 'dont-block t))
  11697. ;; If this task has checkboxes that are not checked, it's blocked
  11698. (save-excursion
  11699. (org-back-to-heading t)
  11700. (let ((beg (point)) end)
  11701. (outline-next-heading)
  11702. (setq end (point))
  11703. (goto-char beg)
  11704. (when (org-list-search-forward
  11705. (concat (org-item-beginning-re)
  11706. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11707. "\\[[- ]\\]")
  11708. end t)
  11709. (when (boundp 'org-blocked-by-checkboxes)
  11710. (setq org-blocked-by-checkboxes t))
  11711. (throw 'dont-block nil))))
  11712. t))) ; do not block
  11713. (defun org-entry-blocked-p ()
  11714. "Non-nil if entry at point is blocked."
  11715. (and (not (org-entry-get nil "NOBLOCKING"))
  11716. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11717. (not (run-hook-with-args-until-failure
  11718. 'org-blocker-hook
  11719. (list :type 'todo-state-change
  11720. :position (point)
  11721. :from 'todo
  11722. :to 'done)))))
  11723. (defun org-update-statistics-cookies (all)
  11724. "Update the statistics cookie, either from TODO or from checkboxes.
  11725. This should be called with the cursor in a line with a statistics
  11726. cookie. When called with a \\[universal-argument] prefix, update
  11727. all statistics cookies in the buffer."
  11728. (interactive "P")
  11729. (if all
  11730. (progn
  11731. (org-update-checkbox-count 'all)
  11732. (org-map-entries 'org-update-parent-todo-statistics))
  11733. (if (not (org-at-heading-p))
  11734. (org-update-checkbox-count)
  11735. (let ((pos (point-marker))
  11736. end l1 l2)
  11737. (ignore-errors (org-back-to-heading t))
  11738. (if (not (org-at-heading-p))
  11739. (org-update-checkbox-count)
  11740. (setq l1 (org-outline-level))
  11741. (setq end (save-excursion
  11742. (outline-next-heading)
  11743. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11744. (point)))
  11745. (if (and (save-excursion
  11746. (re-search-forward
  11747. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11748. (not (save-excursion (re-search-forward
  11749. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11750. (org-update-checkbox-count)
  11751. (if (and l2 (> l2 l1))
  11752. (progn
  11753. (goto-char end)
  11754. (org-update-parent-todo-statistics))
  11755. (goto-char pos)
  11756. (beginning-of-line 1)
  11757. (while (re-search-forward
  11758. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11759. (point-at-eol) t)
  11760. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11761. (goto-char pos)
  11762. (move-marker pos nil)))))
  11763. (defvar org-entry-property-inherited-from) ;; defined below
  11764. (defun org-update-parent-todo-statistics ()
  11765. "Update any statistics cookie in the parent of the current headline.
  11766. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11767. the entire subtree and this will travel up the hierarchy and update
  11768. statistics everywhere."
  11769. (let* ((prop (save-excursion (org-up-heading-safe)
  11770. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11771. (recursive (or (not org-hierarchical-todo-statistics)
  11772. (and prop (string-match "\\<recursive\\>" prop))))
  11773. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11774. 0))
  11775. (first t)
  11776. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11777. level ltoggle l1 new ndel
  11778. (cnt-all 0) (cnt-done 0) is-percent kwd
  11779. checkbox-beg cookie-present)
  11780. (catch 'exit
  11781. (save-excursion
  11782. (beginning-of-line 1)
  11783. (setq ltoggle (funcall outline-level))
  11784. ;; Three situations are to consider:
  11785. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11786. ;; to the top-level ancestor on the headline;
  11787. ;; 2. If parent has "recursive" property, repeat up to the
  11788. ;; headline setting that property, taking inheritance into
  11789. ;; account;
  11790. ;; 3. Else, move up to direct parent and proceed only once.
  11791. (while (and (setq level (org-up-heading-safe))
  11792. (or recursive first)
  11793. (>= (point) lim))
  11794. (setq first nil cookie-present nil)
  11795. (unless (and level
  11796. (not (string-match
  11797. "\\<checkbox\\>"
  11798. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11799. "")))))
  11800. (throw 'exit nil))
  11801. (while (re-search-forward box-re (point-at-eol) t)
  11802. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11803. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11804. (save-match-data
  11805. (unless (outline-next-heading) (throw 'exit nil))
  11806. (while (and (looking-at org-complex-heading-regexp)
  11807. (> (setq l1 (length (match-string 1))) level))
  11808. (setq kwd (and (or recursive (= l1 ltoggle))
  11809. (match-string 2)))
  11810. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11811. (and (eq org-provide-todo-statistics t)
  11812. (or (member kwd org-done-keywords)))
  11813. (and (listp org-provide-todo-statistics)
  11814. (stringp (car org-provide-todo-statistics))
  11815. (or (member kwd org-provide-todo-statistics)
  11816. (member kwd org-done-keywords)))
  11817. (and (listp org-provide-todo-statistics)
  11818. (listp (car org-provide-todo-statistics))
  11819. (or (member kwd (car org-provide-todo-statistics))
  11820. (and (member kwd org-done-keywords)
  11821. (member kwd (cadr org-provide-todo-statistics))))))
  11822. (setq cnt-all (1+ cnt-all))
  11823. (and (eq org-provide-todo-statistics t)
  11824. kwd
  11825. (setq cnt-all (1+ cnt-all))))
  11826. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11827. (member kwd org-done-keywords))
  11828. (and (listp org-provide-todo-statistics)
  11829. (listp (car org-provide-todo-statistics))
  11830. (member kwd org-done-keywords)
  11831. (member kwd (cadr org-provide-todo-statistics)))
  11832. (and (listp org-provide-todo-statistics)
  11833. (stringp (car org-provide-todo-statistics))
  11834. (member kwd org-done-keywords)))
  11835. (setq cnt-done (1+ cnt-done)))
  11836. (outline-next-heading)))
  11837. (setq new
  11838. (if is-percent
  11839. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11840. (max 1 cnt-all)))
  11841. (format "[%d/%d]" cnt-done cnt-all))
  11842. ndel (- (match-end 0) checkbox-beg))
  11843. (goto-char checkbox-beg)
  11844. (insert new)
  11845. (delete-region (point) (+ (point) ndel))
  11846. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11847. (when cookie-present
  11848. (run-hook-with-args 'org-after-todo-statistics-hook
  11849. cnt-done (- cnt-all cnt-done))))))
  11850. (run-hooks 'org-todo-statistics-hook)))
  11851. (defvar org-after-todo-statistics-hook nil
  11852. "Hook that is called after a TODO statistics cookie has been updated.
  11853. Each function is called with two arguments: the number of not-done entries
  11854. and the number of done entries.
  11855. For example, the following function, when added to this hook, will switch
  11856. an entry to DONE when all children are done, and back to TODO when new
  11857. entries are set to a TODO status. Note that this hook is only called
  11858. when there is a statistics cookie in the headline!
  11859. (defun org-summary-todo (n-done n-not-done)
  11860. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11861. (let (org-log-done org-log-states) ; turn off logging
  11862. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11863. ")
  11864. (defvar org-todo-statistics-hook nil
  11865. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11866. This hook runs even if there is no statistics cookie present, in which case
  11867. `org-after-todo-statistics-hook' would not run.")
  11868. (defun org-todo-trigger-tag-changes (state)
  11869. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11870. (let ((l org-todo-state-tags-triggers)
  11871. changes)
  11872. (when (or (not state) (equal state ""))
  11873. (setq changes (append changes (cdr (assoc "" l)))))
  11874. (when (and (stringp state) (> (length state) 0))
  11875. (setq changes (append changes (cdr (assoc state l)))))
  11876. (when (member state org-not-done-keywords)
  11877. (setq changes (append changes (cdr (assq 'todo l)))))
  11878. (when (member state org-done-keywords)
  11879. (setq changes (append changes (cdr (assq 'done l)))))
  11880. (dolist (c changes)
  11881. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11882. (defun org-local-logging (value)
  11883. "Get logging settings from a property VALUE."
  11884. ;; Directly set the variables, they are already local.
  11885. (setq org-log-done nil
  11886. org-log-repeat nil
  11887. org-todo-log-states nil)
  11888. (dolist (w (org-split-string value))
  11889. (let (a)
  11890. (cond
  11891. ((setq a (assoc w org-startup-options))
  11892. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11893. (set (nth 1 a) (nth 2 a))))
  11894. ((setq a (org-extract-log-state-settings w))
  11895. (and (member (car a) org-todo-keywords-1)
  11896. (push a org-todo-log-states)))))))
  11897. (defun org-get-todo-sequence-head (kwd)
  11898. "Return the head of the TODO sequence to which KWD belongs.
  11899. If KWD is not set, check if there is a text property remembering the
  11900. right sequence."
  11901. (let (p)
  11902. (cond
  11903. ((not kwd)
  11904. (or (get-text-property (point-at-bol) 'org-todo-head)
  11905. (progn
  11906. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11907. nil (point-at-eol)))
  11908. (get-text-property p 'org-todo-head))))
  11909. ((not (member kwd org-todo-keywords-1))
  11910. (car org-todo-keywords-1))
  11911. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11912. (defun org-fast-todo-selection ()
  11913. "Fast TODO keyword selection with single keys.
  11914. Returns the new TODO keyword, or nil if no state change should occur."
  11915. (let* ((fulltable org-todo-key-alist)
  11916. (done-keywords org-done-keywords) ;; needed for the faces.
  11917. (maxlen (apply 'max (mapcar
  11918. (lambda (x)
  11919. (if (stringp (car x)) (string-width (car x)) 0))
  11920. fulltable)))
  11921. (expert nil)
  11922. (fwidth (+ maxlen 3 1 3))
  11923. (ncol (/ (- (window-width) 4) fwidth))
  11924. tg cnt e c tbl
  11925. groups ingroup)
  11926. (save-excursion
  11927. (save-window-excursion
  11928. (if expert
  11929. (set-buffer (get-buffer-create " *Org todo*"))
  11930. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11931. (erase-buffer)
  11932. (setq-local org-done-keywords done-keywords)
  11933. (setq tbl fulltable cnt 0)
  11934. (while (setq e (pop tbl))
  11935. (cond
  11936. ((equal e '(:startgroup))
  11937. (push '() groups) (setq ingroup t)
  11938. (unless (= cnt 0)
  11939. (setq cnt 0)
  11940. (insert "\n"))
  11941. (insert "{ "))
  11942. ((equal e '(:endgroup))
  11943. (setq ingroup nil cnt 0)
  11944. (insert "}\n"))
  11945. ((equal e '(:newline))
  11946. (unless (= cnt 0)
  11947. (setq cnt 0)
  11948. (insert "\n")
  11949. (setq e (car tbl))
  11950. (while (equal (car tbl) '(:newline))
  11951. (insert "\n")
  11952. (setq tbl (cdr tbl)))))
  11953. (t
  11954. (setq tg (car e) c (cdr e))
  11955. (when ingroup (push tg (car groups)))
  11956. (setq tg (org-add-props tg nil 'face
  11957. (org-get-todo-face tg)))
  11958. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11959. (insert "[" c "] " tg (make-string
  11960. (- fwidth 4 (length tg)) ?\ ))
  11961. (when (= (setq cnt (1+ cnt)) ncol)
  11962. (insert "\n")
  11963. (when ingroup (insert " "))
  11964. (setq cnt 0)))))
  11965. (insert "\n")
  11966. (goto-char (point-min))
  11967. (unless expert (org-fit-window-to-buffer))
  11968. (message "[a-z..]:Set [SPC]:clear")
  11969. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11970. (cond
  11971. ((or (= c ?\C-g)
  11972. (and (= c ?q) (not (rassoc c fulltable))))
  11973. (setq quit-flag t))
  11974. ((= c ?\ ) nil)
  11975. ((setq e (rassoc c fulltable) tg (car e))
  11976. tg)
  11977. (t (setq quit-flag t)))))))
  11978. (defun org-entry-is-todo-p ()
  11979. (member (org-get-todo-state) org-not-done-keywords))
  11980. (defun org-entry-is-done-p ()
  11981. (member (org-get-todo-state) org-done-keywords))
  11982. (defun org-get-todo-state ()
  11983. "Return the TODO keyword of the current subtree."
  11984. (save-excursion
  11985. (org-back-to-heading t)
  11986. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11987. (match-end 2)
  11988. (match-string 2))))
  11989. (defun org-at-date-range-p (&optional inactive-ok)
  11990. "Non-nil if point is inside a date range.
  11991. When optional argument INACTIVE-OK is non-nil, also consider
  11992. inactive time ranges.
  11993. When this function returns a non-nil value, match data is set
  11994. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11995. on INACTIVE-OK."
  11996. (interactive)
  11997. (save-excursion
  11998. (catch 'exit
  11999. (let ((pos (point)))
  12000. (skip-chars-backward "^[<\r\n")
  12001. (skip-chars-backward "<[")
  12002. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  12003. (>= (match-end 0) pos)
  12004. (throw 'exit t))
  12005. (skip-chars-backward "^<[\r\n")
  12006. (skip-chars-backward "<[")
  12007. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  12008. (>= (match-end 0) pos)
  12009. (throw 'exit t)))
  12010. nil)))
  12011. (defun org-get-repeat (&optional tagline)
  12012. "Check if there is a deadline/schedule with repeater in this entry."
  12013. (save-match-data
  12014. (save-excursion
  12015. (org-back-to-heading t)
  12016. (and (re-search-forward (if tagline
  12017. (concat tagline "\\s-*" org-repeat-re)
  12018. org-repeat-re)
  12019. (org-entry-end-position) t)
  12020. (match-string-no-properties 1)))))
  12021. (defvar org-last-changed-timestamp)
  12022. (defvar org-last-inserted-timestamp)
  12023. (defvar org-log-post-message)
  12024. (defvar org-log-note-purpose)
  12025. (defvar org-log-note-how nil)
  12026. (defvar org-log-note-extra)
  12027. (defun org-auto-repeat-maybe (done-word)
  12028. "Check if the current headline contains a repeated time-stamp.
  12029. If yes, set TODO state back to what it was and change the base date
  12030. of repeating deadline/scheduled time stamps to new date.
  12031. This function is run automatically after each state change to a DONE state."
  12032. (let* ((repeat (org-get-repeat))
  12033. (aa (assoc org-last-state org-todo-kwd-alist))
  12034. (interpret (nth 1 aa))
  12035. (head (nth 2 aa))
  12036. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  12037. (msg "Entry repeats: ")
  12038. (org-log-done nil)
  12039. (org-todo-log-states nil))
  12040. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  12041. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  12042. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  12043. org-todo-repeat-to-state)))
  12044. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  12045. to-state)
  12046. ((eq interpret 'type) org-last-state)
  12047. (head)
  12048. (t 'none))))
  12049. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  12050. (org-entry-put nil "LAST_REPEAT" (format-time-string
  12051. (org-time-stamp-format t t))))
  12052. (when org-log-repeat
  12053. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  12054. (memq 'org-add-log-note post-command-hook))
  12055. ;; We are already setup for some record.
  12056. (when (eq org-log-repeat 'note)
  12057. ;; Make sure we take a note, not only a time stamp.
  12058. (setq org-log-note-how 'note))
  12059. ;; Set up for taking a record.
  12060. (org-add-log-setup 'state
  12061. (or done-word (car org-done-keywords))
  12062. org-last-state
  12063. org-log-repeat)))
  12064. (org-back-to-heading t)
  12065. (org-add-planning-info nil nil 'closed)
  12066. (let ((end (save-excursion (outline-next-heading) (point)))
  12067. (planning-re (regexp-opt
  12068. (list org-scheduled-string org-deadline-string))))
  12069. (while (re-search-forward org-ts-regexp end t)
  12070. (let* ((ts (match-string 0))
  12071. (planning? (org-at-planning-p))
  12072. (type (if (not planning?) "Plain:"
  12073. (save-excursion
  12074. (re-search-backward
  12075. planning-re (line-beginning-position) t)
  12076. (match-string 0)))))
  12077. (cond
  12078. ;; Ignore fake time-stamps (e.g., within comments).
  12079. ((and (not planning?)
  12080. (not (org-at-property-p))
  12081. (not (eq 'timestamp
  12082. (org-element-type (save-excursion
  12083. (backward-char)
  12084. (org-element-context)))))))
  12085. ;; Time-stamps without a repeater are usually skipped.
  12086. ;; However, a SCHEDULED time-stamp without one is
  12087. ;; removed, as it is considered as no longer relevant.
  12088. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12089. (when (equal type org-scheduled-string)
  12090. (org-remove-timestamp-with-keyword type)))
  12091. (t
  12092. (let ((n (string-to-number (match-string 2 ts)))
  12093. (what (match-string 3 ts)))
  12094. (when (equal what "w") (setq n (* n 7) what "d"))
  12095. (when (and (equal what "h")
  12096. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12097. ts)))
  12098. (user-error
  12099. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12100. has been set"
  12101. n))
  12102. ;; Preparation, see if we need to modify the start
  12103. ;; date for the change.
  12104. (when (match-end 1)
  12105. (let ((time (save-match-data (org-time-string-to-time ts))))
  12106. (cond
  12107. ((equal (match-string 1 ts) ".")
  12108. ;; Shift starting date to today
  12109. (org-timestamp-change
  12110. (- (org-today) (time-to-days time))
  12111. 'day))
  12112. ((equal (match-string 1 ts) "+")
  12113. (let ((nshiftmax 10)
  12114. (nshift 0))
  12115. (while (or (= nshift 0)
  12116. (not (time-less-p (current-time) time)))
  12117. (when (= (cl-incf nshift) nshiftmax)
  12118. (or (y-or-n-p
  12119. (format "%d repeater intervals were not \
  12120. enough to shift date past today. Continue? "
  12121. nshift))
  12122. (user-error "Abort")))
  12123. (org-timestamp-change n (cdr (assoc what whata)))
  12124. (org-at-timestamp-p t)
  12125. (setq ts (match-string 1))
  12126. (setq time
  12127. (save-match-data
  12128. (org-time-string-to-time ts)))))
  12129. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12130. ;; Rematch, so that we have everything in place
  12131. ;; for the real shift.
  12132. (org-at-timestamp-p t)
  12133. (setq ts (match-string 1))
  12134. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12135. ts)))))
  12136. (save-excursion
  12137. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12138. (setq msg
  12139. (concat
  12140. msg type " " org-last-changed-timestamp " "))))))))
  12141. (setq org-log-post-message msg)
  12142. (message "%s" msg))))
  12143. (defun org-show-todo-tree (arg)
  12144. "Make a compact tree which shows all headlines marked with TODO.
  12145. The tree will show the lines where the regexp matches, and all higher
  12146. headlines above the match.
  12147. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12148. With a numeric prefix N, construct a sparse tree for the Nth element
  12149. of `org-todo-keywords-1'."
  12150. (interactive "P")
  12151. (let ((case-fold-search nil)
  12152. (kwd-re
  12153. (cond ((null arg) org-not-done-regexp)
  12154. ((equal arg '(4))
  12155. (let ((kwd
  12156. (completing-read "Keyword (or KWD1|KWD2|...): "
  12157. (mapcar #'list org-todo-keywords-1))))
  12158. (concat "\\("
  12159. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12160. "\\)\\>")))
  12161. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12162. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12163. org-todo-keywords-1)))
  12164. (t (user-error "Invalid prefix argument: %s" arg)))))
  12165. (message "%d TODO entries found"
  12166. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12167. (defun org--deadline-or-schedule (arg type time)
  12168. "Insert DEADLINE or SCHEDULE information in current entry.
  12169. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  12170. `org-schedule' for information about ARG and TIME arguments."
  12171. (let* ((deadline? (eq type 'deadline))
  12172. (keyword (if deadline? org-deadline-string org-scheduled-string))
  12173. (log (if deadline? org-log-redeadline org-log-reschedule))
  12174. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  12175. (old-date-time (and old-date (org-time-string-to-time old-date)))
  12176. ;; Save repeater cookie from either TIME or current scheduled
  12177. ;; time stamp. We are going to insert it back at the end of
  12178. ;; the process.
  12179. (repeater (or (and (org-string-nw-p time)
  12180. ;; We use `org-repeat-re' because we need
  12181. ;; to tell the difference between a real
  12182. ;; repeater and a time delta, e.g. "+2d".
  12183. (string-match org-repeat-re time)
  12184. (match-string 1 time))
  12185. (and (org-string-nw-p old-date)
  12186. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  12187. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  12188. old-date)
  12189. (match-string 1 old-date)))))
  12190. (pcase arg
  12191. (`(4)
  12192. (when (and old-date log)
  12193. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  12194. nil old-date log))
  12195. (org-remove-timestamp-with-keyword keyword)
  12196. (message (if deadline? "Item no longer has a deadline."
  12197. "Item is no longer scheduled.")))
  12198. (`(16)
  12199. (save-excursion
  12200. (org-back-to-heading t)
  12201. (let ((regexp (if deadline? org-deadline-time-regexp
  12202. org-scheduled-time-regexp)))
  12203. (if (not (re-search-forward regexp (line-end-position 2) t))
  12204. (user-error (if deadline? "No deadline information to update"
  12205. "No scheduled information to update"))
  12206. (let* ((rpl0 (match-string 1))
  12207. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  12208. (msg (if deadline? "Warn starting from" "Delay until")))
  12209. (replace-match
  12210. (concat keyword
  12211. " <" rpl
  12212. (format " -%dd"
  12213. (abs (- (time-to-days
  12214. (save-match-data
  12215. (org-read-date
  12216. nil t nil msg old-date-time)))
  12217. (time-to-days old-date-time))))
  12218. ">") t t))))))
  12219. (_
  12220. (org-add-planning-info type time 'closed)
  12221. (when (and old-date
  12222. log
  12223. (not (equal old-date org-last-inserted-timestamp)))
  12224. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  12225. org-last-inserted-timestamp
  12226. old-date
  12227. log))
  12228. (when repeater
  12229. (save-excursion
  12230. (org-back-to-heading t)
  12231. (when (re-search-forward
  12232. (concat keyword " " org-last-inserted-timestamp)
  12233. (line-end-position 2)
  12234. t)
  12235. (goto-char (1- (match-end 0)))
  12236. (insert " " repeater)
  12237. (setq org-last-inserted-timestamp
  12238. (concat (substring org-last-inserted-timestamp 0 -1)
  12239. " " repeater
  12240. (substring org-last-inserted-timestamp -1))))))
  12241. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12242. org-last-inserted-timestamp)))))
  12243. (defun org-deadline (arg &optional time)
  12244. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12245. With one universal prefix argument, remove any deadline from the item.
  12246. With two universal prefix arguments, prompt for a warning delay.
  12247. With argument TIME, set the deadline at the corresponding date. TIME
  12248. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12249. (interactive "P")
  12250. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12251. (org-map-entries
  12252. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12253. nil
  12254. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12255. 'region-start-level
  12256. 'region)
  12257. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12258. (org--deadline-or-schedule arg 'deadline time)))
  12259. (defun org-schedule (arg &optional time)
  12260. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12261. With one universal prefix argument, remove any scheduling date from the item.
  12262. With two universal prefix arguments, prompt for a delay cookie.
  12263. With argument TIME, scheduled at the corresponding date. TIME can
  12264. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12265. (interactive "P")
  12266. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12267. (org-map-entries
  12268. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12269. nil
  12270. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12271. 'region-start-level
  12272. 'region)
  12273. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12274. (org--deadline-or-schedule arg 'scheduled time)))
  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. ;; Note associated to a clock is to be located right after
  12603. ;; the clock. Do not move point.
  12604. (unless (eq org-log-note-purpose 'clock-out)
  12605. (goto-char (org-log-beginning t)))
  12606. ;; Make sure point is at the beginning of an empty line.
  12607. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12608. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12609. ;; In an existing list, add a new item at the top level.
  12610. ;; Otherwise, indent line like a regular one.
  12611. (let ((itemp (org-in-item-p)))
  12612. (if itemp
  12613. (indent-line-to
  12614. (let ((struct (save-excursion
  12615. (goto-char itemp) (org-list-struct))))
  12616. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12617. (org-indent-line)))
  12618. (insert (org-list-bullet-string "-") (pop lines))
  12619. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12620. (dolist (line lines)
  12621. (insert "\n")
  12622. (indent-line-to ind)
  12623. (insert line)))
  12624. (message "Note stored")
  12625. (org-back-to-heading t)
  12626. (org-cycle-hide-drawers 'children))
  12627. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12628. ;; from within `org-add-log-note' because `buffer-undo-list'
  12629. ;; is then modified outside of `org-with-remote-undo'.
  12630. (when (eq this-command 'org-agenda-todo)
  12631. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12632. ;; Don't add undo information when called from `org-agenda-todo'.
  12633. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12634. (set-window-configuration org-log-note-window-configuration)
  12635. (with-current-buffer (marker-buffer org-log-note-return-to)
  12636. (goto-char org-log-note-return-to))
  12637. (move-marker org-log-note-return-to nil)
  12638. (when org-log-post-message (message "%s" org-log-post-message))))
  12639. (defun org-remove-empty-drawer-at (pos)
  12640. "Remove an empty drawer at position POS.
  12641. POS may also be a marker."
  12642. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12643. (org-with-wide-buffer
  12644. (goto-char pos)
  12645. (let ((drawer (org-element-at-point)))
  12646. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12647. (not (org-element-property :contents-begin drawer)))
  12648. (delete-region (org-element-property :begin drawer)
  12649. (progn (goto-char (org-element-property :end drawer))
  12650. (skip-chars-backward " \r\t\n")
  12651. (forward-line)
  12652. (point))))))))
  12653. (defvar org-ts-type nil)
  12654. (defun org-sparse-tree (&optional arg type)
  12655. "Create a sparse tree, prompt for the details.
  12656. This command can create sparse trees. You first need to select the type
  12657. of match used to create the tree:
  12658. t Show all TODO entries.
  12659. T Show entries with a specific TODO keyword.
  12660. m Show entries selected by a tags/property match.
  12661. p Enter a property name and its value (both with completion on existing
  12662. names/values) and show entries with that property.
  12663. r Show entries matching a regular expression (`/' can be used as well).
  12664. b Show deadlines and scheduled items before a date.
  12665. a Show deadlines and scheduled items after a date.
  12666. d Show deadlines due within `org-deadline-warning-days'.
  12667. D Show deadlines and scheduled items between a date range."
  12668. (interactive "P")
  12669. (setq type (or type org-sparse-tree-default-date-type))
  12670. (setq org-ts-type type)
  12671. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12672. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12673. \[c]ycle through date types: %s"
  12674. (cl-case type
  12675. (all "all timestamps")
  12676. (scheduled "only scheduled")
  12677. (deadline "only deadline")
  12678. (active "only active timestamps")
  12679. (inactive "only inactive timestamps")
  12680. (closed "with a closed time-stamp")
  12681. (otherwise "scheduled/deadline")))
  12682. (let ((answer (read-char-exclusive)))
  12683. (cl-case answer
  12684. (?c
  12685. (org-sparse-tree
  12686. arg
  12687. (cadr
  12688. (memq type '(nil all scheduled deadline active inactive closed)))))
  12689. (?d (call-interactively 'org-check-deadlines))
  12690. (?b (call-interactively 'org-check-before-date))
  12691. (?a (call-interactively 'org-check-after-date))
  12692. (?D (call-interactively 'org-check-dates-range))
  12693. (?t (call-interactively 'org-show-todo-tree))
  12694. (?T (org-show-todo-tree '(4)))
  12695. (?m (call-interactively 'org-match-sparse-tree))
  12696. ((?p ?P)
  12697. (let* ((kwd (completing-read
  12698. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12699. (value (completing-read
  12700. "Value: " (mapcar #'list (org-property-values kwd)))))
  12701. (unless (string-match "\\`{.*}\\'" value)
  12702. (setq value (concat "\"" value "\"")))
  12703. (org-match-sparse-tree arg (concat kwd "=" value))))
  12704. ((?r ?R ?/) (call-interactively 'org-occur))
  12705. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12706. (defvar-local org-occur-highlights nil
  12707. "List of overlays used for occur matches.")
  12708. (defvar-local org-occur-parameters nil
  12709. "Parameters of the active org-occur calls.
  12710. This is a list, each call to org-occur pushes as cons cell,
  12711. containing the regular expression and the callback, onto the list.
  12712. The list can contain several entries if `org-occur' has been called
  12713. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12714. will only contain one set of parameters. When the highlights are
  12715. removed (for example with `C-c C-c', or with the next edit (depending
  12716. on `org-remove-highlights-with-change'), this variable is emptied
  12717. as well.")
  12718. (defun org-occur (regexp &optional keep-previous callback)
  12719. "Make a compact tree which shows all matches of REGEXP.
  12720. The tree will show the lines where the regexp matches, and any other context
  12721. defined in `org-show-context-detail', which see.
  12722. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12723. done by a previous call to `org-occur' will be kept, to allow stacking of
  12724. calls to this command.
  12725. Optional argument CALLBACK can be a function of no argument. In this case,
  12726. it is called with point at the end of the match, match data being set
  12727. accordingly. Current match is shown only if the return value is non-nil.
  12728. The function must neither move point nor alter narrowing."
  12729. (interactive "sRegexp: \nP")
  12730. (when (equal regexp "")
  12731. (user-error "Regexp cannot be empty"))
  12732. (unless keep-previous
  12733. (org-remove-occur-highlights nil nil t))
  12734. (push (cons regexp callback) org-occur-parameters)
  12735. (let ((cnt 0))
  12736. (save-excursion
  12737. (goto-char (point-min))
  12738. (when (or (not keep-previous) ; do not want to keep
  12739. (not org-occur-highlights)) ; no previous matches
  12740. ;; hide everything
  12741. (org-overview))
  12742. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12743. (isearch-no-upper-case-p regexp t)
  12744. org-occur-case-fold-search)))
  12745. (while (re-search-forward regexp nil t)
  12746. (when (or (not callback)
  12747. (save-match-data (funcall callback)))
  12748. (setq cnt (1+ cnt))
  12749. (when org-highlight-sparse-tree-matches
  12750. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12751. (org-show-context 'occur-tree)))))
  12752. (when org-remove-highlights-with-change
  12753. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12754. nil 'local))
  12755. (unless org-sparse-tree-open-archived-trees
  12756. (org-hide-archived-subtrees (point-min) (point-max)))
  12757. (run-hooks 'org-occur-hook)
  12758. (when (called-interactively-p 'interactive)
  12759. (message "%d match(es) for regexp %s" cnt regexp))
  12760. cnt))
  12761. (defun org-occur-next-match (&optional n _reset)
  12762. "Function for `next-error-function' to find sparse tree matches.
  12763. N is the number of matches to move, when negative move backwards.
  12764. This function always goes back to the starting point when no
  12765. match is found."
  12766. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12767. (search-func (if (< n 0)
  12768. 'previous-single-char-property-change
  12769. 'next-single-char-property-change))
  12770. (n (abs n))
  12771. (pos (point))
  12772. p1)
  12773. (catch 'exit
  12774. (while (setq p1 (funcall search-func (point) 'org-type))
  12775. (when (equal p1 limit)
  12776. (goto-char pos)
  12777. (user-error "No more matches"))
  12778. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12779. (setq n (1- n))
  12780. (when (= n 0)
  12781. (goto-char p1)
  12782. (throw 'exit (point))))
  12783. (goto-char p1))
  12784. (goto-char p1)
  12785. (user-error "No more matches"))))
  12786. (defun org-show-context (&optional key)
  12787. "Make sure point and context are visible.
  12788. Optional argument KEY, when non-nil, is a symbol. See
  12789. `org-show-context-detail' for allowed values and how much is to
  12790. be shown."
  12791. (org-show-set-visibility
  12792. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12793. ((cdr (assq key org-show-context-detail)))
  12794. (t (cdr (assq 'default org-show-context-detail))))))
  12795. (defun org-show-set-visibility (detail)
  12796. "Set visibility around point according to DETAIL.
  12797. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12798. `tree', `canonical' or t. See `org-show-context-detail' for more
  12799. information."
  12800. ;; Show current heading and possibly its entry, following headline
  12801. ;; or all children.
  12802. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12803. (org-flag-heading nil)
  12804. (org-show-entry)
  12805. ;; If point is hidden within a drawer or a block, make sure to
  12806. ;; expose it.
  12807. (dolist (o (overlays-at (point)))
  12808. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12809. (delete-overlay o)))
  12810. (unless (org-before-first-heading-p)
  12811. (org-with-limited-levels
  12812. (cl-case detail
  12813. ((tree canonical t) (org-show-children))
  12814. ((nil minimal ancestors))
  12815. (t (save-excursion
  12816. (outline-next-heading)
  12817. (org-flag-heading nil)))))))
  12818. ;; Show all siblings.
  12819. (when (eq detail 'lineage) (org-show-siblings))
  12820. ;; Show ancestors, possibly with their children.
  12821. (when (memq detail '(ancestors lineage tree canonical t))
  12822. (save-excursion
  12823. (while (org-up-heading-safe)
  12824. (org-flag-heading nil)
  12825. (when (memq detail '(canonical t)) (org-show-entry))
  12826. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12827. (defvar org-reveal-start-hook nil
  12828. "Hook run before revealing a location.")
  12829. (defun org-reveal (&optional siblings)
  12830. "Show current entry, hierarchy above it, and the following headline.
  12831. This can be used to show a consistent set of context around
  12832. locations exposed with `org-show-context'.
  12833. With optional argument SIBLINGS, on each level of the hierarchy all
  12834. siblings are shown. This repairs the tree structure to what it would
  12835. look like when opened with hierarchical calls to `org-cycle'.
  12836. With a \\[universal-argument] \\[universal-argument] prefix, \
  12837. go to the parent and show the entire tree."
  12838. (interactive "P")
  12839. (run-hooks 'org-reveal-start-hook)
  12840. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12841. ((equal siblings '(16))
  12842. (save-excursion
  12843. (when (org-up-heading-safe)
  12844. (org-show-subtree)
  12845. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12846. (t (org-show-set-visibility 'lineage))))
  12847. (defun org-highlight-new-match (beg end)
  12848. "Highlight from BEG to END and mark the highlight is an occur headline."
  12849. (let ((ov (make-overlay beg end)))
  12850. (overlay-put ov 'face 'secondary-selection)
  12851. (overlay-put ov 'org-type 'org-occur)
  12852. (push ov org-occur-highlights)))
  12853. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12854. "Remove the occur highlights from the buffer.
  12855. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12856. from the `before-change-functions' in the current buffer."
  12857. (interactive)
  12858. (unless org-inhibit-highlight-removal
  12859. (mapc #'delete-overlay org-occur-highlights)
  12860. (setq org-occur-highlights nil)
  12861. (setq org-occur-parameters nil)
  12862. (unless noremove
  12863. (remove-hook 'before-change-functions
  12864. 'org-remove-occur-highlights 'local))))
  12865. ;;;; Priorities
  12866. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12867. "Regular expression matching the priority indicator.")
  12868. (defvar org-remove-priority-next-time nil)
  12869. (defun org-priority-up ()
  12870. "Increase the priority of the current item."
  12871. (interactive)
  12872. (org-priority 'up))
  12873. (defun org-priority-down ()
  12874. "Decrease the priority of the current item."
  12875. (interactive)
  12876. (org-priority 'down))
  12877. (defun org-priority (&optional action _show)
  12878. "Change the priority of an item.
  12879. ACTION can be `set', `up', `down', or a character."
  12880. (interactive "P")
  12881. (if (equal action '(4))
  12882. (org-show-priority)
  12883. (unless org-enable-priority-commands
  12884. (user-error "Priority commands are disabled"))
  12885. (setq action (or action 'set))
  12886. (let (current new news have remove)
  12887. (save-excursion
  12888. (org-back-to-heading t)
  12889. (when (looking-at org-priority-regexp)
  12890. (setq current (string-to-char (match-string 2))
  12891. have t))
  12892. (cond
  12893. ((eq action 'remove)
  12894. (setq remove t new ?\ ))
  12895. ((or (eq action 'set)
  12896. (integerp action))
  12897. (if (not (eq action 'set))
  12898. (setq new action)
  12899. (message "Priority %c-%c, SPC to remove: "
  12900. org-highest-priority org-lowest-priority)
  12901. (save-match-data
  12902. (setq new (read-char-exclusive))))
  12903. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12904. (= (upcase org-lowest-priority) org-lowest-priority))
  12905. (setq new (upcase new)))
  12906. (cond ((equal new ?\ ) (setq remove t))
  12907. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12908. (user-error "Priority must be between `%c' and `%c'"
  12909. org-highest-priority org-lowest-priority))))
  12910. ((eq action 'up)
  12911. (setq new (if have
  12912. (1- current) ; normal cycling
  12913. ;; last priority was empty
  12914. (if (eq last-command this-command)
  12915. org-lowest-priority ; wrap around empty to lowest
  12916. ;; default
  12917. (if org-priority-start-cycle-with-default
  12918. org-default-priority
  12919. (1- org-default-priority))))))
  12920. ((eq action 'down)
  12921. (setq new (if have
  12922. (1+ current) ; normal cycling
  12923. ;; last priority was empty
  12924. (if (eq last-command this-command)
  12925. org-highest-priority ; wrap around empty to highest
  12926. ;; default
  12927. (if org-priority-start-cycle-with-default
  12928. org-default-priority
  12929. (1+ org-default-priority))))))
  12930. (t (user-error "Invalid action")))
  12931. (when (or (< (upcase new) org-highest-priority)
  12932. (> (upcase new) org-lowest-priority))
  12933. (if (and (memq action '(up down))
  12934. (not have) (not (eq last-command this-command)))
  12935. ;; `new' is from default priority
  12936. (error
  12937. "The default can not be set, see `org-default-priority' why")
  12938. ;; normal cycling: `new' is beyond highest/lowest priority
  12939. ;; and is wrapped around to the empty priority
  12940. (setq remove t)))
  12941. (setq news (format "%c" new))
  12942. (if have
  12943. (if remove
  12944. (replace-match "" t t nil 1)
  12945. (replace-match news t t nil 2))
  12946. (if remove
  12947. (user-error "No priority cookie found in line")
  12948. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12949. (if (match-end 2)
  12950. (progn
  12951. (goto-char (match-end 2))
  12952. (insert " [#" news "]"))
  12953. (goto-char (match-beginning 3))
  12954. (insert "[#" news "] "))))
  12955. (org-set-tags nil 'align))
  12956. (if remove
  12957. (message "Priority removed")
  12958. (message "Priority of current item set to %s" news)))))
  12959. (defun org-show-priority ()
  12960. "Show the priority of the current item.
  12961. This priority is composed of the main priority given with the [#A] cookies,
  12962. and by additional input from the age of a schedules or deadline entry."
  12963. (interactive)
  12964. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12965. (org-get-at-bol 'priority)
  12966. (save-excursion
  12967. (save-match-data
  12968. (beginning-of-line)
  12969. (and (looking-at org-heading-regexp)
  12970. (org-get-priority (match-string 0))))))))
  12971. (message "Priority is %d" (if pri pri -1000))))
  12972. (defun org-get-priority (s)
  12973. "Find priority cookie and return priority."
  12974. (save-match-data
  12975. (if (functionp org-get-priority-function)
  12976. (funcall org-get-priority-function)
  12977. (if (not (string-match org-priority-regexp s))
  12978. (* 1000 (- org-lowest-priority org-default-priority))
  12979. (* 1000 (- org-lowest-priority
  12980. (string-to-char (match-string 2 s))))))))
  12981. ;;;; Tags
  12982. (defvar org-agenda-archives-mode)
  12983. (defvar org-map-continue-from nil
  12984. "Position from where mapping should continue.
  12985. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12986. (defvar org-scanner-tags nil
  12987. "The current tag list while the tags scanner is running.")
  12988. (defvar org-trust-scanner-tags nil
  12989. "Should `org-get-tags-at' use the tags for the scanner.
  12990. This is for internal dynamical scoping only.
  12991. When this is non-nil, the function `org-get-tags-at' will return the value
  12992. of `org-scanner-tags' instead of building the list by itself. This
  12993. can lead to large speed-ups when the tags scanner is used in a file with
  12994. many entries, and when the list of tags is retrieved, for example to
  12995. obtain a list of properties. Building the tags list for each entry in such
  12996. a file becomes an N^2 operation - but with this variable set, it scales
  12997. as N.")
  12998. (defvar org--matcher-tags-todo-only nil)
  12999. (defun org-scan-tags (action matcher todo-only &optional start-level)
  13000. "Scan headline tags with inheritance and produce output ACTION.
  13001. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  13002. or `agenda' to produce an entry list for an agenda view. It can also be
  13003. a Lisp form or a function that should be called at each matched headline, in
  13004. this case the return value is a list of all return values from these calls.
  13005. MATCHER is a function accepting three arguments, returning
  13006. a non-nil value whenever a given set of tags qualifies a headline
  13007. for inclusion. See `org-make-tags-matcher' for more information.
  13008. As a special case, it can also be set to t (respectively nil) in
  13009. order to match all (respectively none) headline.
  13010. When TODO-ONLY is non-nil, only lines with a not-done TODO
  13011. keyword are included in the output.
  13012. START-LEVEL can be a string with asterisks, reducing the scope to
  13013. headlines matching this string."
  13014. (require 'org-agenda)
  13015. (let* ((re (concat "^"
  13016. (if start-level
  13017. ;; Get the correct level to match
  13018. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  13019. org-outline-regexp)
  13020. " *\\(\\<\\("
  13021. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  13022. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  13023. (props (list 'face 'default
  13024. 'done-face 'org-agenda-done
  13025. 'undone-face 'default
  13026. 'mouse-face 'highlight
  13027. 'org-not-done-regexp org-not-done-regexp
  13028. 'org-todo-regexp org-todo-regexp
  13029. 'org-complex-heading-regexp org-complex-heading-regexp
  13030. 'help-echo
  13031. (format "mouse-2 or RET jump to org file %s"
  13032. (abbreviate-file-name
  13033. (or (buffer-file-name (buffer-base-buffer))
  13034. (buffer-name (buffer-base-buffer)))))))
  13035. (org-map-continue-from nil)
  13036. lspos tags tags-list
  13037. (tags-alist (list (cons 0 org-file-tags)))
  13038. (llast 0) rtn rtn1 level category i txt
  13039. todo marker entry priority
  13040. ts-date ts-date-type ts-date-pair)
  13041. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  13042. (setq action (list 'lambda nil action)))
  13043. (save-excursion
  13044. (goto-char (point-min))
  13045. (when (eq action 'sparse-tree)
  13046. (org-overview)
  13047. (org-remove-occur-highlights))
  13048. (while (let (case-fold-search)
  13049. (re-search-forward re nil t))
  13050. (setq org-map-continue-from nil)
  13051. (catch :skip
  13052. (setq todo
  13053. ;; TODO: is the 1-2 difference a bug?
  13054. (when (match-end 1) (match-string-no-properties 2))
  13055. tags (when (match-end 4) (match-string-no-properties 4)))
  13056. (goto-char (setq lspos (match-beginning 0)))
  13057. (setq level (org-reduced-level (org-outline-level))
  13058. category (org-get-category))
  13059. (when (eq action 'agenda)
  13060. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13061. ts-date (car ts-date-pair)
  13062. ts-date-type (cdr ts-date-pair)))
  13063. (setq i llast llast level)
  13064. ;; remove tag lists from same and sublevels
  13065. (while (>= i level)
  13066. (when (setq entry (assoc i tags-alist))
  13067. (setq tags-alist (delete entry tags-alist)))
  13068. (setq i (1- i)))
  13069. ;; add the next tags
  13070. (when tags
  13071. (setq tags (org-split-string tags ":")
  13072. tags-alist
  13073. (cons (cons level tags) tags-alist)))
  13074. ;; compile tags for current headline
  13075. (setq tags-list
  13076. (if org-use-tag-inheritance
  13077. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13078. tags)
  13079. org-scanner-tags tags-list)
  13080. (when org-use-tag-inheritance
  13081. (setcdr (car tags-alist)
  13082. (mapcar (lambda (x)
  13083. (setq x (copy-sequence x))
  13084. (org-add-prop-inherited x))
  13085. (cdar tags-alist))))
  13086. (when (and tags org-use-tag-inheritance
  13087. (or (not (eq t org-use-tag-inheritance))
  13088. org-tags-exclude-from-inheritance))
  13089. ;; Selective inheritance, remove uninherited ones.
  13090. (setcdr (car tags-alist)
  13091. (org-remove-uninherited-tags (cdar tags-alist))))
  13092. (when (and
  13093. ;; eval matcher only when the todo condition is OK
  13094. (and (or (not todo-only) (member todo org-not-done-keywords))
  13095. (if (functionp matcher)
  13096. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13097. (funcall matcher todo tags-list level))
  13098. matcher))
  13099. ;; Call the skipper, but return t if it does not
  13100. ;; skip, so that the `and' form continues evaluating.
  13101. (progn
  13102. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13103. t)
  13104. ;; Check if timestamps are deselecting this entry
  13105. (or (not todo-only)
  13106. (and (member todo org-not-done-keywords)
  13107. (or (not org-agenda-tags-todo-honor-ignore-options)
  13108. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13109. ;; select this headline
  13110. (cond
  13111. ((eq action 'sparse-tree)
  13112. (and org-highlight-sparse-tree-matches
  13113. (org-get-heading) (match-end 0)
  13114. (org-highlight-new-match
  13115. (match-beginning 1) (match-end 1)))
  13116. (org-show-context 'tags-tree))
  13117. ((eq action 'agenda)
  13118. (setq txt (org-agenda-format-item
  13119. ""
  13120. (concat
  13121. (if (eq org-tags-match-list-sublevels 'indented)
  13122. (make-string (1- level) ?.) "")
  13123. (org-get-heading))
  13124. (make-string level ?\s)
  13125. category
  13126. tags-list)
  13127. priority (org-get-priority txt))
  13128. (goto-char lspos)
  13129. (setq marker (org-agenda-new-marker))
  13130. (org-add-props txt props
  13131. 'org-marker marker 'org-hd-marker marker 'org-category category
  13132. 'todo-state todo
  13133. 'ts-date ts-date
  13134. 'priority priority
  13135. 'type (concat "tagsmatch" ts-date-type))
  13136. (push txt rtn))
  13137. ((functionp action)
  13138. (setq org-map-continue-from nil)
  13139. (save-excursion
  13140. (setq rtn1 (funcall action))
  13141. (push rtn1 rtn)))
  13142. (t (user-error "Invalid action")))
  13143. ;; if we are to skip sublevels, jump to end of subtree
  13144. (unless org-tags-match-list-sublevels
  13145. (org-end-of-subtree t)
  13146. (backward-char 1))))
  13147. ;; Get the correct position from where to continue
  13148. (if org-map-continue-from
  13149. (goto-char org-map-continue-from)
  13150. (and (= (point) lspos) (end-of-line 1)))))
  13151. (when (and (eq action 'sparse-tree)
  13152. (not org-sparse-tree-open-archived-trees))
  13153. (org-hide-archived-subtrees (point-min) (point-max)))
  13154. (nreverse rtn)))
  13155. (defun org-remove-uninherited-tags (tags)
  13156. "Remove all tags that are not inherited from the list TAGS."
  13157. (cond
  13158. ((eq org-use-tag-inheritance t)
  13159. (if org-tags-exclude-from-inheritance
  13160. (org-delete-all org-tags-exclude-from-inheritance tags)
  13161. tags))
  13162. ((not org-use-tag-inheritance) nil)
  13163. ((stringp org-use-tag-inheritance)
  13164. (delq nil (mapcar
  13165. (lambda (x)
  13166. (if (and (string-match org-use-tag-inheritance x)
  13167. (not (member x org-tags-exclude-from-inheritance)))
  13168. x nil))
  13169. tags)))
  13170. ((listp org-use-tag-inheritance)
  13171. (delq nil (mapcar
  13172. (lambda (x)
  13173. (if (member x org-use-tag-inheritance) x nil))
  13174. tags)))))
  13175. (defun org-match-sparse-tree (&optional todo-only match)
  13176. "Create a sparse tree according to tags string MATCH.
  13177. MATCH is a string with match syntax. It can contain a selection
  13178. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13179. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13180. those. See the manual for details.
  13181. If optional argument TODO-ONLY is non-nil, only select lines that
  13182. are also TODO tasks."
  13183. (interactive "P")
  13184. (org-agenda-prepare-buffers (list (current-buffer)))
  13185. (let ((org--matcher-tags-todo-only todo-only))
  13186. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13187. org--matcher-tags-todo-only)))
  13188. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13189. (defvar org-cached-props nil)
  13190. (defun org-cached-entry-get (pom property)
  13191. (if (or (eq t org-use-property-inheritance)
  13192. (and (stringp org-use-property-inheritance)
  13193. (let ((case-fold-search t))
  13194. (string-match-p org-use-property-inheritance property)))
  13195. (and (listp org-use-property-inheritance)
  13196. (member-ignore-case property org-use-property-inheritance)))
  13197. ;; Caching is not possible, check it directly.
  13198. (org-entry-get pom property 'inherit)
  13199. ;; Get all properties, so we can do complicated checks easily.
  13200. (cdr (assoc-string property
  13201. (or org-cached-props
  13202. (setq org-cached-props (org-entry-properties pom)))
  13203. t))))
  13204. (defun org-global-tags-completion-table (&optional files)
  13205. "Return the list of all tags in all agenda buffer/files.
  13206. Optional FILES argument is a list of files which can be used
  13207. instead of the agenda files."
  13208. (save-excursion
  13209. (org-uniquify
  13210. (delq nil
  13211. (apply #'append
  13212. (mapcar
  13213. (lambda (file)
  13214. (set-buffer (find-file-noselect file))
  13215. (mapcar (lambda (x)
  13216. (and (stringp (car-safe x))
  13217. (list (car-safe x))))
  13218. (or org-current-tag-alist (org-get-buffer-tags))))
  13219. (if (car-safe files) files
  13220. (org-agenda-files))))))))
  13221. (defun org-make-tags-matcher (match)
  13222. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13223. Returns a cons of the selection string MATCH and a function
  13224. implementing the matcher.
  13225. The matcher is to be called at an Org entry, with point on the
  13226. headline, and returns non-nil if the entry matches the selection
  13227. string MATCH. It must be called with three arguments: the TODO
  13228. keyword at the entry (or nil if none), the list of all tags at
  13229. the entry including inherited ones and the reduced level of the
  13230. headline. Additionally, the category of the entry, if any, must
  13231. be specified as the text property `org-category' on the headline.
  13232. This function sets the variable `org--matcher-tags-todo-only' to
  13233. a non-nil value if the matcher restricts matching to TODO
  13234. entries, otherwise it is not touched.
  13235. See also `org-scan-tags'."
  13236. (unless match
  13237. ;; Get a new match request, with completion against the global
  13238. ;; tags table and the local tags in current buffer.
  13239. (let ((org-last-tags-completion-table
  13240. (org-uniquify
  13241. (delq nil (append (org-get-buffer-tags)
  13242. (org-global-tags-completion-table))))))
  13243. (setq match
  13244. (completing-read
  13245. "Match: "
  13246. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13247. (let ((match0 match)
  13248. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13249. (start 0)
  13250. tagsmatch todomatch tagsmatcher todomatcher)
  13251. ;; Expand group tags.
  13252. (setq match (org-tags-expand match))
  13253. ;; Check if there is a TODO part of this match, which would be the
  13254. ;; part after a "/". To make sure that this slash is not part of
  13255. ;; a property value to be matched against, we also check that
  13256. ;; there is no / after that slash. First, find the last slash.
  13257. (let ((s 0))
  13258. (while (string-match "/+" match s)
  13259. (setq start (match-beginning 0))
  13260. (setq s (match-end 0))))
  13261. (if (and (string-match "/+" match start)
  13262. (not (string-match-p "\"" match start)))
  13263. ;; Match contains also a TODO-matching request.
  13264. (progn
  13265. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13266. (setq todomatch (substring match (match-end 0)))
  13267. (when (string-prefix-p "!" todomatch)
  13268. (setq org--matcher-tags-todo-only t)
  13269. (setq todomatch (substring todomatch 1)))
  13270. (when (string-match "\\`\\s-*\\'" todomatch)
  13271. (setq todomatch nil)))
  13272. ;; Only matching tags.
  13273. (setq tagsmatch match)
  13274. (setq todomatch nil))
  13275. ;; Make the tags matcher.
  13276. (when (org-string-nw-p tagsmatch)
  13277. (let ((orlist nil)
  13278. (orterms (org-split-string tagsmatch "|"))
  13279. term)
  13280. (while (setq term (pop orterms))
  13281. (while (and (equal (substring term -1) "\\") orterms)
  13282. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13283. (while (string-match re term)
  13284. (let* ((rest (substring term (match-end 0)))
  13285. (minus (and (match-end 1)
  13286. (equal (match-string 1 term) "-")))
  13287. (tag (save-match-data
  13288. (replace-regexp-in-string
  13289. "\\\\-" "-" (match-string 2 term))))
  13290. (regexp (eq (string-to-char tag) ?{))
  13291. (levelp (match-end 4))
  13292. (propp (match-end 5))
  13293. (mm
  13294. (cond
  13295. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13296. (levelp
  13297. `(,(org-op-to-function (match-string 3 term))
  13298. level
  13299. ,(string-to-number (match-string 4 term))))
  13300. (propp
  13301. (let* ((gv (pcase (upcase (match-string 5 term))
  13302. ("CATEGORY"
  13303. '(get-text-property (point) 'org-category))
  13304. ("TODO" 'todo)
  13305. (p `(org-cached-entry-get nil ,p))))
  13306. (pv (match-string 7 term))
  13307. (regexp (eq (string-to-char pv) ?{))
  13308. (strp (eq (string-to-char pv) ?\"))
  13309. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13310. (po (org-op-to-function (match-string 6 term)
  13311. (if timep 'time strp))))
  13312. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13313. (when timep (setq pv (org-matcher-time pv)))
  13314. (cond ((and regexp (eq po 'org<>))
  13315. `(not (string-match ,pv (or ,gv ""))))
  13316. (regexp `(string-match ,pv (or ,gv "")))
  13317. (strp `(,po (or ,gv "") ,pv))
  13318. (t
  13319. `(,po
  13320. (string-to-number (or ,gv ""))
  13321. ,(string-to-number pv))))))
  13322. (t `(member ,tag tags-list)))))
  13323. (push (if minus `(not ,mm) mm) tagsmatcher)
  13324. (setq term rest)))
  13325. (push `(and ,@tagsmatcher) orlist)
  13326. (setq tagsmatcher nil))
  13327. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13328. ;; Make the TODO matcher.
  13329. (when (org-string-nw-p todomatch)
  13330. (let ((orlist nil))
  13331. (dolist (term (org-split-string todomatch "|"))
  13332. (while (string-match re term)
  13333. (let* ((minus (and (match-end 1)
  13334. (equal (match-string 1 term) "-")))
  13335. (kwd (match-string 2 term))
  13336. (regexp (eq (string-to-char kwd) ?{))
  13337. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13338. `(equal todo ,kwd))))
  13339. (push (if minus `(not ,mm) mm) todomatcher))
  13340. (setq term (substring term (match-end 0))))
  13341. (push (if (> (length todomatcher) 1)
  13342. (cons 'and todomatcher)
  13343. (car todomatcher))
  13344. orlist)
  13345. (setq todomatcher nil))
  13346. (setq todomatcher (cons 'or orlist))))
  13347. ;; Return the string and function of the matcher. If no
  13348. ;; tags-specific or todo-specific matcher exists, match
  13349. ;; everything.
  13350. (let ((matcher (if (and tagsmatcher todomatcher)
  13351. `(and ,tagsmatcher ,todomatcher)
  13352. (or tagsmatcher todomatcher t))))
  13353. (when org--matcher-tags-todo-only
  13354. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13355. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13356. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13357. "Expand group tags in MATCH.
  13358. This replaces every group tag in MATCH with a regexp tag search.
  13359. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13360. will be replaced like this:
  13361. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13362. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13363. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13364. Replacing by a regexp preserves the structure of the match.
  13365. E.g., this expansion
  13366. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13367. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13368. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13369. A group tag in MATCH can contain regular expressions of its own.
  13370. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13371. will be replaced like this:
  13372. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13373. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13374. assumed to be a single group tag, and the function will return
  13375. the list of tags in this group.
  13376. When DOWNCASE is non-nil, expand downcased TAGS."
  13377. (if org-group-tags
  13378. (let* ((case-fold-search t)
  13379. (stable org-mode-syntax-table)
  13380. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13381. (taggroups (if downcased
  13382. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13383. taggroups)
  13384. taggroups))
  13385. (taggroups-keys (mapcar #'car taggroups))
  13386. (return-match (if downcased (downcase match) match))
  13387. (count 0)
  13388. (work-already-expanded tags-already-expanded)
  13389. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13390. ;; @ and _ are allowed as word-components in tags.
  13391. (modify-syntax-entry ?@ "w" stable)
  13392. (modify-syntax-entry ?_ "w" stable)
  13393. ;; Temporarily replace regexp-expressions in the match-expression.
  13394. (while (string-match "{.+?}" return-match)
  13395. (cl-incf count)
  13396. (push (match-string 0 return-match) regexps-in-match)
  13397. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13398. (while (and taggroups-keys
  13399. (with-syntax-table stable
  13400. (string-match
  13401. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13402. (regexp-opt taggroups-keys) "\\>\\)")
  13403. return-match)))
  13404. (let* ((dir (match-string 1 return-match))
  13405. (tag (match-string 2 return-match))
  13406. (tag (if downcased (downcase tag) tag)))
  13407. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13408. (member tag work-already-expanded))
  13409. (setq tags-in-group (assoc tag taggroups))
  13410. (push tag work-already-expanded)
  13411. ;; Recursively expand each tag in the group, if the tag hasn't
  13412. ;; already been expanded. Restore the match-data after all recursive calls.
  13413. (save-match-data
  13414. (let (tags-expanded)
  13415. (dolist (x (cdr tags-in-group))
  13416. (if (and (member x taggroups-keys)
  13417. (not (member x work-already-expanded)))
  13418. (setq tags-expanded
  13419. (delete-dups
  13420. (append
  13421. (org-tags-expand x t downcased
  13422. work-already-expanded)
  13423. tags-expanded)))
  13424. (setq tags-expanded
  13425. (append (list x) tags-expanded)))
  13426. (setq work-already-expanded
  13427. (delete-dups
  13428. (append tags-expanded
  13429. work-already-expanded))))
  13430. (setq tags-in-group
  13431. (delete-dups (cons (car tags-in-group)
  13432. tags-expanded)))))
  13433. ;; Filter tag-regexps from tags.
  13434. (setq regexp-in-group-escaped
  13435. (delq nil (mapcar (lambda (x)
  13436. (if (stringp x)
  13437. (and (equal "{" (substring x 0 1))
  13438. (equal "}" (substring x -1))
  13439. x)
  13440. x))
  13441. tags-in-group))
  13442. regexp-in-group
  13443. (mapcar (lambda (x)
  13444. (substring x 1 -1))
  13445. regexp-in-group-escaped)
  13446. tags-in-group
  13447. (delq nil (mapcar (lambda (x)
  13448. (if (stringp x)
  13449. (and (not (equal "{" (substring x 0 1)))
  13450. (not (equal "}" (substring x -1)))
  13451. x)
  13452. x))
  13453. tags-in-group)))
  13454. ;; If single-as-list, do no more in the while-loop.
  13455. (if (not single-as-list)
  13456. (progn
  13457. (when regexp-in-group
  13458. (setq regexp-in-group
  13459. (concat "\\|"
  13460. (mapconcat 'identity regexp-in-group
  13461. "\\|"))))
  13462. (setq tags-in-group
  13463. (concat dir
  13464. "{\\<"
  13465. (regexp-opt tags-in-group)
  13466. "\\>"
  13467. regexp-in-group
  13468. "}"))
  13469. (when (stringp tags-in-group)
  13470. (org-add-props tags-in-group '(grouptag t)))
  13471. (setq return-match
  13472. (replace-match tags-in-group t t return-match)))
  13473. (setq tags-in-group
  13474. (append regexp-in-group-escaped tags-in-group))))
  13475. (setq taggroups-keys (delete tag taggroups-keys))))
  13476. ;; Add the regular expressions back into the match-expression again.
  13477. (while regexps-in-match
  13478. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13479. (pop regexps-in-match)
  13480. return-match t t))
  13481. (cl-decf count))
  13482. (if single-as-list
  13483. (if tags-in-group tags-in-group (list return-match))
  13484. return-match))
  13485. (if single-as-list
  13486. (list (if downcased (downcase match) match))
  13487. match)))
  13488. (defun org-op-to-function (op &optional stringp)
  13489. "Turn an operator into the appropriate function."
  13490. (setq op
  13491. (cond
  13492. ((equal op "<" ) '(< string< org-time<))
  13493. ((equal op ">" ) '(> org-string> org-time>))
  13494. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13495. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13496. ((member op '("=" "==")) '(= string= org-time=))
  13497. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13498. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13499. (defun org<> (a b) (not (= a b)))
  13500. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13501. (defun org-string>= (a b) (not (string< a b)))
  13502. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13503. (defun org-string<> (a b) (not (string= 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) (<= a b)))
  13507. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13508. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13509. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13510. (defun org-2ft (s)
  13511. "Convert S to a floating point time.
  13512. If S is already a number, just return it. If it is a string, parse
  13513. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13514. (cond
  13515. ((numberp s) s)
  13516. ((stringp s)
  13517. (condition-case nil
  13518. (float-time (apply 'encode-time (org-parse-time-string s)))
  13519. (error 0.)))
  13520. (t 0.)))
  13521. (defun org-time-today ()
  13522. "Time in seconds today at 0:00.
  13523. Returns the float number of seconds since the beginning of the
  13524. epoch to the beginning of today (00:00)."
  13525. (float-time (apply 'encode-time
  13526. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13527. (defun org-matcher-time (s)
  13528. "Interpret a time comparison value."
  13529. (save-match-data
  13530. (cond
  13531. ((string= s "<now>") (float-time))
  13532. ((string= s "<today>") (org-time-today))
  13533. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13534. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13535. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13536. (+ (org-time-today)
  13537. (* (string-to-number (match-string 1 s))
  13538. (cdr (assoc (match-string 2 s)
  13539. '(("d" . 86400.0) ("w" . 604800.0)
  13540. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13541. (t (org-2ft s)))))
  13542. (defun org-match-any-p (re list)
  13543. "Does re match any element of list?"
  13544. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13545. (delq nil list))
  13546. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13547. (defvar org-tags-overlay (make-overlay 1 1))
  13548. (delete-overlay org-tags-overlay)
  13549. (defun org-get-local-tags-at (&optional pos)
  13550. "Get a list of tags defined in the current headline."
  13551. (org-get-tags-at pos 'local))
  13552. (defun org-get-local-tags ()
  13553. "Get a list of tags defined in the current headline."
  13554. (org-get-tags-at nil 'local))
  13555. (defun org-get-tags-at (&optional pos local)
  13556. "Get a list of all headline tags applicable at POS.
  13557. POS defaults to point. If tags are inherited, the list contains
  13558. the targets in the same sequence as the headlines appear, i.e.
  13559. the tags of the current headline come last.
  13560. When LOCAL is non-nil, only return tags from the current headline,
  13561. ignore inherited ones."
  13562. (interactive)
  13563. (if (and org-trust-scanner-tags
  13564. (or (not pos) (equal pos (point)))
  13565. (not local))
  13566. org-scanner-tags
  13567. (let (tags ltags lastpos parent)
  13568. (save-excursion
  13569. (save-restriction
  13570. (widen)
  13571. (goto-char (or pos (point)))
  13572. (save-match-data
  13573. (catch 'done
  13574. (condition-case nil
  13575. (progn
  13576. (org-back-to-heading t)
  13577. (while (not (equal lastpos (point)))
  13578. (setq lastpos (point))
  13579. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13580. (setq ltags (org-split-string
  13581. (match-string-no-properties 1) ":"))
  13582. (when parent
  13583. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13584. (setq tags (append
  13585. (if parent
  13586. (org-remove-uninherited-tags ltags)
  13587. ltags)
  13588. tags)))
  13589. (or org-use-tag-inheritance (throw 'done t))
  13590. (when local (throw 'done t))
  13591. (or (org-up-heading-safe) (error nil))
  13592. (setq parent t)))
  13593. (error nil)))))
  13594. (if local
  13595. tags
  13596. (reverse (delete-dups
  13597. (reverse (append
  13598. (org-remove-uninherited-tags
  13599. org-file-tags)
  13600. tags)))))))))
  13601. (defun org-add-prop-inherited (s)
  13602. (add-text-properties 0 (length s) '(inherited t) s)
  13603. s)
  13604. (defun org-toggle-tag (tag &optional onoff)
  13605. "Toggle the tag TAG for the current line.
  13606. If ONOFF is `on' or `off', don't toggle but set to this state."
  13607. (let (res current)
  13608. (save-excursion
  13609. (org-back-to-heading t)
  13610. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13611. (point-at-eol) t)
  13612. (progn
  13613. (setq current (match-string 1))
  13614. (replace-match ""))
  13615. (setq current ""))
  13616. (setq current (nreverse (org-split-string current ":")))
  13617. (cond
  13618. ((eq onoff 'on)
  13619. (setq res t)
  13620. (or (member tag current) (push tag current)))
  13621. ((eq onoff 'off)
  13622. (or (not (member tag current)) (setq current (delete tag current))))
  13623. (t (if (member tag current)
  13624. (setq current (delete tag current))
  13625. (setq res t)
  13626. (push tag current))))
  13627. (end-of-line 1)
  13628. (if current
  13629. (progn
  13630. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13631. (org-set-tags nil t))
  13632. (delete-horizontal-space))
  13633. (run-hooks 'org-after-tags-change-hook))
  13634. res))
  13635. (defun org--align-tags-here (to-col)
  13636. "Align tags on the current headline to TO-COL.
  13637. Assume point is on a headline."
  13638. (let ((pos (point)))
  13639. (beginning-of-line)
  13640. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13641. (>= pos (match-beginning 2)))
  13642. ;; No tags or point within tags: do not align.
  13643. (goto-char pos)
  13644. (goto-char (match-beginning 1))
  13645. (let ((shift (max (- (if (>= to-col 0) to-col
  13646. (- (abs to-col) (string-width (match-string 2))))
  13647. (current-column))
  13648. 1)))
  13649. (replace-match (make-string shift ?\s) nil nil nil 1)
  13650. ;; Preserve initial position, if possible. In any case, stop
  13651. ;; before tags.
  13652. (when (< pos (point)) (goto-char pos))))))
  13653. (defun org-set-tags-command (&optional arg just-align)
  13654. "Call the set-tags command for the current entry."
  13655. (interactive "P")
  13656. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13657. (org-set-tags arg just-align)
  13658. (save-excursion
  13659. (unless (and (org-region-active-p)
  13660. org-loop-over-headlines-in-active-region)
  13661. (org-back-to-heading t))
  13662. (org-set-tags arg just-align))))
  13663. (defun org-set-tags-to (data)
  13664. "Set the tags of the current entry to DATA, replacing the current tags.
  13665. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13666. If DATA is nil or the empty string, any tags will be removed."
  13667. (interactive "sTags: ")
  13668. (setq data
  13669. (cond
  13670. ((eq data nil) "")
  13671. ((equal data "") "")
  13672. ((stringp data)
  13673. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13674. ":"))
  13675. ((listp data)
  13676. (concat ":" (mapconcat 'identity data ":") ":"))))
  13677. (when data
  13678. (save-excursion
  13679. (org-back-to-heading t)
  13680. (when (let ((case-fold-search nil))
  13681. (looking-at org-complex-heading-regexp))
  13682. (if (match-end 5)
  13683. (progn
  13684. (goto-char (match-beginning 5))
  13685. (insert data)
  13686. (delete-region (point) (point-at-eol))
  13687. (org-set-tags nil 'align))
  13688. (goto-char (point-at-eol))
  13689. (insert " " data)
  13690. (org-set-tags nil 'align)))
  13691. (beginning-of-line 1)
  13692. (when (looking-at ".*?\\([ \t]+\\)$")
  13693. (delete-region (match-beginning 1) (match-end 1))))))
  13694. (defun org-align-all-tags ()
  13695. "Align the tags in all headings."
  13696. (interactive)
  13697. (save-excursion
  13698. (or (ignore-errors (org-back-to-heading t))
  13699. (outline-next-heading))
  13700. (if (org-at-heading-p)
  13701. (org-set-tags t)
  13702. (message "No headings"))))
  13703. (defvar org-indent-indentation-per-level)
  13704. (defun org-set-tags (&optional arg just-align)
  13705. "Set the tags for the current headline.
  13706. With prefix ARG, realign all tags in headings in the current buffer.
  13707. When JUST-ALIGN is non-nil, only align tags."
  13708. (interactive "P")
  13709. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13710. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13711. 'region-start-level
  13712. 'region))
  13713. org-loop-over-headlines-in-active-region)
  13714. (org-map-entries
  13715. ;; We don't use ARG and JUST-ALIGN here because these args
  13716. ;; are not useful when looping over headlines.
  13717. #'org-set-tags
  13718. org-loop-over-headlines-in-active-region
  13719. cl
  13720. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13721. (let ((org-setting-tags t))
  13722. (if arg
  13723. (save-excursion
  13724. (goto-char (point-min))
  13725. (while (re-search-forward org-outline-regexp-bol nil t)
  13726. (org-set-tags nil t)
  13727. (end-of-line))
  13728. (message "All tags realigned to column %d" org-tags-column))
  13729. (let* ((current (org-get-tags-string))
  13730. (tags
  13731. (if just-align current
  13732. ;; Get a new set of tags from the user.
  13733. (save-excursion
  13734. (let* ((seen)
  13735. (table
  13736. (setq
  13737. org-last-tags-completion-table
  13738. ;; Uniquify tags in alists, yet preserve
  13739. ;; structure (i.e., keywords).
  13740. (delq nil
  13741. (mapcar
  13742. (lambda (pair)
  13743. (let ((head (car pair)))
  13744. (cond ((symbolp head) pair)
  13745. ((member head seen) nil)
  13746. (t (push head seen)
  13747. pair))))
  13748. (append
  13749. (or org-current-tag-alist
  13750. (org-get-buffer-tags))
  13751. (and
  13752. org-complete-tags-always-offer-all-agenda-tags
  13753. (org-global-tags-completion-table
  13754. (org-agenda-files))))))))
  13755. (current-tags (org-split-string current ":"))
  13756. (inherited-tags
  13757. (nreverse (nthcdr (length current-tags)
  13758. (nreverse (org-get-tags-at))))))
  13759. (replace-regexp-in-string
  13760. "\\([-+&]+\\|,\\)"
  13761. ":"
  13762. (if (or (eq t org-use-fast-tag-selection)
  13763. (and org-use-fast-tag-selection
  13764. (delq nil (mapcar #'cdr table))))
  13765. (org-fast-tag-selection
  13766. current-tags inherited-tags table
  13767. (and org-fast-tag-selection-include-todo
  13768. org-todo-key-alist))
  13769. (let ((org-add-colon-after-tag-completion
  13770. (< 1 (length table))))
  13771. (org-trim
  13772. (completing-read
  13773. "Tags: "
  13774. #'org-tags-completion-function
  13775. nil nil current 'org-tags-history))))))))))
  13776. (when org-tags-sort-function
  13777. (setq tags
  13778. (mapconcat
  13779. #'identity
  13780. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13781. org-tags-sort-function)
  13782. ":")))
  13783. (if (or (string= ":" tags)
  13784. (string= "::" tags))
  13785. (setq tags ""))
  13786. (if (not (org-string-nw-p tags)) (setq tags "")
  13787. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13788. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13789. ;; Insert new tags at the correct column.
  13790. (unless (equal current tags)
  13791. (save-excursion
  13792. (beginning-of-line)
  13793. (let ((case-fold-search nil))
  13794. (looking-at org-complex-heading-regexp))
  13795. ;; Remove current tags, if any.
  13796. (when (match-end 5) (replace-match "" nil nil nil 5))
  13797. ;; Insert new tags, if any. Otherwise, remove trailing
  13798. ;; white spaces.
  13799. (end-of-line)
  13800. (if (not (equal tags ""))
  13801. ;; When text is being inserted on an invisible
  13802. ;; region boundary, it can be inadvertently sucked
  13803. ;; into invisibility.
  13804. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13805. (skip-chars-backward " \t")
  13806. (delete-region (point) (line-end-position)))))
  13807. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13808. ;; is on.
  13809. (unless (equal tags "")
  13810. (let* ((level (save-excursion
  13811. (beginning-of-line)
  13812. (skip-chars-forward "\\*")))
  13813. (offset (if (bound-and-true-p org-indent-mode)
  13814. (* (1- org-indent-indentation-per-level)
  13815. (1- level))
  13816. 0))
  13817. (tags-column
  13818. (+ org-tags-column
  13819. (if (> org-tags-column 0) (- offset) offset))))
  13820. (org--align-tags-here tags-column))))
  13821. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13822. (defun org-change-tag-in-region (beg end tag off)
  13823. "Add or remove TAG for each entry in the region.
  13824. This works in the agenda, and also in an Org buffer."
  13825. (interactive
  13826. (list (region-beginning) (region-end)
  13827. (let ((org-last-tags-completion-table
  13828. (if (derived-mode-p 'org-mode)
  13829. (org-uniquify
  13830. (delq nil (append (org-get-buffer-tags)
  13831. (org-global-tags-completion-table))))
  13832. (org-global-tags-completion-table))))
  13833. (completing-read
  13834. "Tag: " 'org-tags-completion-function nil nil nil
  13835. 'org-tags-history))
  13836. (progn
  13837. (message "[s]et or [r]emove? ")
  13838. (equal (read-char-exclusive) ?r))))
  13839. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13840. (let ((agendap (equal major-mode 'org-agenda-mode))
  13841. l1 l2 m buf pos newhead (cnt 0))
  13842. (goto-char end)
  13843. (setq l2 (1- (org-current-line)))
  13844. (goto-char beg)
  13845. (setq l1 (org-current-line))
  13846. (cl-loop for l from l1 to l2 do
  13847. (org-goto-line l)
  13848. (setq m (get-text-property (point) 'org-hd-marker))
  13849. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13850. (and agendap m))
  13851. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13852. pos (if agendap m (point)))
  13853. (with-current-buffer buf
  13854. (save-excursion
  13855. (save-restriction
  13856. (goto-char pos)
  13857. (setq cnt (1+ cnt))
  13858. (org-toggle-tag tag (if off 'off 'on))
  13859. (setq newhead (org-get-heading)))))
  13860. (and agendap (org-agenda-change-all-lines newhead m))))
  13861. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13862. (defun org-tags-completion-function (string _predicate &optional flag)
  13863. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13864. (confirm (lambda (x) (stringp (car x)))))
  13865. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13866. (setq s1 (match-string 1 string)
  13867. s2 (match-string 2 string))
  13868. (setq s1 "" s2 string))
  13869. (cond
  13870. ((eq flag nil)
  13871. ;; try completion
  13872. (setq rtn (try-completion s2 ctable confirm))
  13873. (when (stringp rtn)
  13874. (setq rtn
  13875. (concat s1 s2 (substring rtn (length s2))
  13876. (if (and org-add-colon-after-tag-completion
  13877. (assoc rtn ctable))
  13878. ":" ""))))
  13879. rtn)
  13880. ((eq flag t)
  13881. ;; all-completions
  13882. (all-completions s2 ctable confirm))
  13883. ((eq flag 'lambda)
  13884. ;; exact match?
  13885. (assoc s2 ctable)))))
  13886. (defun org-fast-tag-insert (kwd tags face &optional end)
  13887. "Insert KDW, and the TAGS, the latter with face FACE.
  13888. Also insert END."
  13889. (insert (format "%-12s" (concat kwd ":"))
  13890. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13891. (or end "")))
  13892. (defun org-fast-tag-show-exit (flag)
  13893. (save-excursion
  13894. (org-goto-line 3)
  13895. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13896. (replace-match ""))
  13897. (when flag
  13898. (end-of-line 1)
  13899. (org-move-to-column (- (window-width) 19) t)
  13900. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13901. (defun org-set-current-tags-overlay (current prefix)
  13902. "Add an overlay to CURRENT tag with PREFIX."
  13903. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13904. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13905. (org-overlay-display org-tags-overlay (concat prefix s))))
  13906. (defvar org-last-tag-selection-key nil)
  13907. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13908. "Fast tag selection with single keys.
  13909. CURRENT is the current list of tags in the headline, INHERITED is the
  13910. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13911. possibly with grouping information. TODO-TABLE is a similar table with
  13912. TODO keywords, should these have keys assigned to them.
  13913. If the keys are nil, a-z are automatically assigned.
  13914. Returns the new tags string, or nil to not change the current settings."
  13915. (let* ((fulltable (append table todo-table))
  13916. (maxlen (apply 'max (mapcar
  13917. (lambda (x)
  13918. (if (stringp (car x)) (string-width (car x)) 0))
  13919. fulltable)))
  13920. (buf (current-buffer))
  13921. (expert (eq org-fast-tag-selection-single-key 'expert))
  13922. (buffer-tags nil)
  13923. (fwidth (+ maxlen 3 1 3))
  13924. (ncol (/ (- (window-width) 4) fwidth))
  13925. (i-face 'org-done)
  13926. (c-face 'org-todo)
  13927. tg cnt e c char c1 c2 ntable tbl rtn
  13928. ov-start ov-end ov-prefix
  13929. (exit-after-next org-fast-tag-selection-single-key)
  13930. (done-keywords org-done-keywords)
  13931. groups ingroup intaggroup)
  13932. (save-excursion
  13933. (beginning-of-line 1)
  13934. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13935. (setq ov-start (match-beginning 1)
  13936. ov-end (match-end 1)
  13937. ov-prefix "")
  13938. (setq ov-start (1- (point-at-eol))
  13939. ov-end (1+ ov-start))
  13940. (skip-chars-forward "^\n\r")
  13941. (setq ov-prefix
  13942. (concat
  13943. (buffer-substring (1- (point)) (point))
  13944. (if (> (current-column) org-tags-column)
  13945. " "
  13946. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13947. (move-overlay org-tags-overlay ov-start ov-end)
  13948. (save-window-excursion
  13949. (if expert
  13950. (set-buffer (get-buffer-create " *Org tags*"))
  13951. (delete-other-windows)
  13952. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13953. (org-switch-to-buffer-other-window " *Org tags*"))
  13954. (erase-buffer)
  13955. (setq-local org-done-keywords done-keywords)
  13956. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13957. (org-fast-tag-insert "Current" current c-face "\n\n")
  13958. (org-fast-tag-show-exit exit-after-next)
  13959. (org-set-current-tags-overlay current ov-prefix)
  13960. (setq tbl fulltable char ?a cnt 0)
  13961. (while (setq e (pop tbl))
  13962. (cond
  13963. ((eq (car e) :startgroup)
  13964. (push '() groups) (setq ingroup t)
  13965. (unless (zerop cnt)
  13966. (setq cnt 0)
  13967. (insert "\n"))
  13968. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13969. ((eq (car e) :endgroup)
  13970. (setq ingroup nil cnt 0)
  13971. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13972. ((eq (car e) :startgrouptag)
  13973. (setq intaggroup t)
  13974. (unless (zerop cnt)
  13975. (setq cnt 0)
  13976. (insert "\n"))
  13977. (insert "[ "))
  13978. ((eq (car e) :endgrouptag)
  13979. (setq intaggroup nil cnt 0)
  13980. (insert "]\n"))
  13981. ((equal e '(:newline))
  13982. (unless (zerop cnt)
  13983. (setq cnt 0)
  13984. (insert "\n")
  13985. (setq e (car tbl))
  13986. (while (equal (car tbl) '(:newline))
  13987. (insert "\n")
  13988. (setq tbl (cdr tbl)))))
  13989. ((equal e '(:grouptags)) (insert " : "))
  13990. (t
  13991. (setq tg (copy-sequence (car e)) c2 nil)
  13992. (if (cdr e)
  13993. (setq c (cdr e))
  13994. ;; automatically assign a character.
  13995. (setq c1 (string-to-char
  13996. (downcase (substring
  13997. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13998. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13999. (while (or (rassoc char ntable) (rassoc char table))
  14000. (setq char (1+ char)))
  14001. (setq c2 c1))
  14002. (setq c (or c2 char)))
  14003. (when ingroup (push tg (car groups)))
  14004. (setq tg (org-add-props tg nil 'face
  14005. (cond
  14006. ((not (assoc tg table))
  14007. (org-get-todo-face tg))
  14008. ((member tg current) c-face)
  14009. ((member tg inherited) i-face))))
  14010. (when (equal (caar tbl) :grouptags)
  14011. (org-add-props tg nil 'face 'org-tag-group))
  14012. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  14013. (insert "[" c "] " tg (make-string
  14014. (- fwidth 4 (length tg)) ?\ ))
  14015. (push (cons tg c) ntable)
  14016. (when (= (cl-incf cnt) ncol)
  14017. (insert "\n")
  14018. (when (or ingroup intaggroup) (insert " "))
  14019. (setq cnt 0)))))
  14020. (setq ntable (nreverse ntable))
  14021. (insert "\n")
  14022. (goto-char (point-min))
  14023. (unless expert (org-fit-window-to-buffer))
  14024. (setq rtn
  14025. (catch 'exit
  14026. (while t
  14027. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  14028. (if (not groups) "no " "")
  14029. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  14030. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  14031. (setq org-last-tag-selection-key c)
  14032. (cond
  14033. ((= c ?\r) (throw 'exit t))
  14034. ((= c ?!)
  14035. (setq groups (not groups))
  14036. (goto-char (point-min))
  14037. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  14038. ((= c ?\C-c)
  14039. (if (not expert)
  14040. (org-fast-tag-show-exit
  14041. (setq exit-after-next (not exit-after-next)))
  14042. (setq expert nil)
  14043. (delete-other-windows)
  14044. (set-window-buffer (split-window-vertically) " *Org tags*")
  14045. (org-switch-to-buffer-other-window " *Org tags*")
  14046. (org-fit-window-to-buffer)))
  14047. ((or (= c ?\C-g)
  14048. (and (= c ?q) (not (rassoc c ntable))))
  14049. (delete-overlay org-tags-overlay)
  14050. (setq quit-flag t))
  14051. ((= c ?\ )
  14052. (setq current nil)
  14053. (when exit-after-next (setq exit-after-next 'now)))
  14054. ((= c ?\t)
  14055. (condition-case nil
  14056. (setq tg (completing-read
  14057. "Tag: "
  14058. (or buffer-tags
  14059. (with-current-buffer buf
  14060. (setq buffer-tags
  14061. (org-get-buffer-tags))))))
  14062. (quit (setq tg "")))
  14063. (when (string-match "\\S-" tg)
  14064. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14065. (if (member tg current)
  14066. (setq current (delete tg current))
  14067. (push tg current)))
  14068. (when exit-after-next (setq exit-after-next 'now)))
  14069. ((setq e (rassoc c todo-table) tg (car e))
  14070. (with-current-buffer buf
  14071. (save-excursion (org-todo tg)))
  14072. (when exit-after-next (setq exit-after-next 'now)))
  14073. ((setq e (rassoc c ntable) tg (car e))
  14074. (if (member tg current)
  14075. (setq current (delete tg current))
  14076. (cl-loop for g in groups do
  14077. (when (member tg g)
  14078. (dolist (x g) (setq current (delete x current)))))
  14079. (push tg current))
  14080. (when exit-after-next (setq exit-after-next 'now))))
  14081. ;; Create a sorted list
  14082. (setq current
  14083. (sort current
  14084. (lambda (a b)
  14085. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14086. (when (eq exit-after-next 'now) (throw 'exit t))
  14087. (goto-char (point-min))
  14088. (beginning-of-line 2)
  14089. (delete-region (point) (point-at-eol))
  14090. (org-fast-tag-insert "Current" current c-face)
  14091. (org-set-current-tags-overlay current ov-prefix)
  14092. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14093. (setq tg (match-string 1))
  14094. (add-text-properties
  14095. (match-beginning 1) (match-end 1)
  14096. (list 'face
  14097. (cond
  14098. ((member tg current) c-face)
  14099. ((member tg inherited) i-face)
  14100. (t (get-text-property (match-beginning 1) 'face))))))
  14101. (goto-char (point-min)))))
  14102. (delete-overlay org-tags-overlay)
  14103. (if rtn
  14104. (mapconcat 'identity current ":")
  14105. nil))))
  14106. (defun org-get-tags-string ()
  14107. "Get the TAGS string in the current headline."
  14108. (unless (org-at-heading-p t)
  14109. (user-error "Not on a heading"))
  14110. (save-excursion
  14111. (beginning-of-line 1)
  14112. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14113. (match-string-no-properties 1)
  14114. "")))
  14115. (defun org-get-tags ()
  14116. "Get the list of tags specified in the current headline."
  14117. (org-split-string (org-get-tags-string) ":"))
  14118. (defun org-get-buffer-tags ()
  14119. "Get a table of all tags used in the buffer, for completion."
  14120. (org-with-wide-buffer
  14121. (goto-char (point-min))
  14122. (let ((tag-re (concat org-outline-regexp-bol
  14123. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14124. tags)
  14125. (while (re-search-forward tag-re nil t)
  14126. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14127. (push tag tags)))
  14128. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14129. ;;;; The mapping API
  14130. (defvar org-agenda-skip-comment-trees)
  14131. (defvar org-agenda-skip-function)
  14132. (defun org-map-entries (func &optional match scope &rest skip)
  14133. "Call FUNC at each headline selected by MATCH in SCOPE.
  14134. FUNC is a function or a lisp form. The function will be called without
  14135. arguments, with the cursor positioned at the beginning of the headline.
  14136. The return values of all calls to the function will be collected and
  14137. returned as a list.
  14138. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14139. does not need to preserve point. After evaluation, the cursor will be
  14140. moved to the end of the line (presumably of the headline of the
  14141. processed entry) and search continues from there. Under some
  14142. circumstances, this may not produce the wanted results. For example,
  14143. if you have removed (e.g. archived) the current (sub)tree it could
  14144. mean that the next entry will be skipped entirely. In such cases, you
  14145. can specify the position from where search should continue by making
  14146. FUNC set the variable `org-map-continue-from' to the desired buffer
  14147. position.
  14148. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14149. Only headlines that are matched by this query will be considered during
  14150. the iteration. When MATCH is nil or t, all headlines will be
  14151. visited by the iteration.
  14152. SCOPE determines the scope of this command. It can be any of:
  14153. nil The current buffer, respecting the restriction if any
  14154. tree The subtree started with the entry at point
  14155. region The entries within the active region, if any
  14156. region-start-level
  14157. The entries within the active region, but only those at
  14158. the same level than the first one.
  14159. file The current buffer, without restriction
  14160. file-with-archives
  14161. The current buffer, and any archives associated with it
  14162. agenda All agenda files
  14163. agenda-with-archives
  14164. All agenda files with any archive files associated with them
  14165. \(file1 file2 ...)
  14166. If this is a list, all files in the list will be scanned
  14167. The remaining args are treated as settings for the skipping facilities of
  14168. the scanner. The following items can be given here:
  14169. archive skip trees with the archive tag
  14170. comment skip trees with the COMMENT keyword
  14171. function or Emacs Lisp form:
  14172. will be used as value for `org-agenda-skip-function', so
  14173. whenever the function returns a position, FUNC will not be
  14174. called for that entry and search will continue from the
  14175. position returned
  14176. If your function needs to retrieve the tags including inherited tags
  14177. at the *current* entry, you can use the value of the variable
  14178. `org-scanner-tags' which will be much faster than getting the value
  14179. with `org-get-tags-at'. If your function gets properties with
  14180. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14181. to t around the call to `org-entry-properties' to get the same speedup.
  14182. Note that if your function moves around to retrieve tags and properties at
  14183. a *different* entry, you cannot use these techniques."
  14184. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14185. (not (org-region-active-p)))
  14186. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14187. (org-agenda-skip-archived-trees (memq 'archive skip))
  14188. (org-agenda-skip-comment-trees (memq 'comment skip))
  14189. (org-agenda-skip-function
  14190. (car (org-delete-all '(comment archive) skip)))
  14191. (org-tags-match-list-sublevels t)
  14192. (start-level (eq scope 'region-start-level))
  14193. matcher res
  14194. org-todo-keywords-for-agenda
  14195. org-done-keywords-for-agenda
  14196. org-todo-keyword-alist-for-agenda
  14197. org-tag-alist-for-agenda
  14198. org--matcher-tags-todo-only)
  14199. (cond
  14200. ((eq match t) (setq matcher t))
  14201. ((eq match nil) (setq matcher t))
  14202. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14203. (save-excursion
  14204. (save-restriction
  14205. (cond ((eq scope 'tree)
  14206. (org-back-to-heading t)
  14207. (org-narrow-to-subtree)
  14208. (setq scope nil))
  14209. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14210. (org-region-active-p))
  14211. ;; If needed, set start-level to a string like "2"
  14212. (when start-level
  14213. (save-excursion
  14214. (goto-char (region-beginning))
  14215. (unless (org-at-heading-p) (outline-next-heading))
  14216. (setq start-level (org-current-level))))
  14217. (narrow-to-region (region-beginning)
  14218. (save-excursion
  14219. (goto-char (region-end))
  14220. (unless (and (bolp) (org-at-heading-p))
  14221. (outline-next-heading))
  14222. (point)))
  14223. (setq scope nil)))
  14224. (if (not scope)
  14225. (progn
  14226. (org-agenda-prepare-buffers
  14227. (and buffer-file-name (list buffer-file-name)))
  14228. (setq res
  14229. (org-scan-tags
  14230. func matcher org--matcher-tags-todo-only start-level)))
  14231. ;; Get the right scope
  14232. (cond
  14233. ((and scope (listp scope) (symbolp (car scope)))
  14234. (setq scope (eval scope)))
  14235. ((eq scope 'agenda)
  14236. (setq scope (org-agenda-files t)))
  14237. ((eq scope 'agenda-with-archives)
  14238. (setq scope (org-agenda-files t))
  14239. (setq scope (org-add-archive-files scope)))
  14240. ((eq scope 'file)
  14241. (setq scope (and buffer-file-name (list buffer-file-name))))
  14242. ((eq scope 'file-with-archives)
  14243. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14244. (org-agenda-prepare-buffers scope)
  14245. (dolist (file scope)
  14246. (with-current-buffer (org-find-base-buffer-visiting file)
  14247. (org-with-wide-buffer
  14248. (goto-char (point-min))
  14249. (setq res
  14250. (append
  14251. res
  14252. (org-scan-tags
  14253. func matcher org--matcher-tags-todo-only)))))))))
  14254. res)))
  14255. ;;; Properties API
  14256. (defconst org-special-properties
  14257. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14258. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14259. "The special properties valid in Org mode.
  14260. These are properties that are not defined in the property drawer,
  14261. but in some other way.")
  14262. (defconst org-default-properties
  14263. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14264. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14265. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14266. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14267. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14268. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14269. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14270. "Some properties that are used by Org mode for various purposes.
  14271. Being in this list makes sure that they are offered for completion.")
  14272. (defun org--valid-property-p (property)
  14273. "Non nil when string PROPERTY is a valid property name."
  14274. (not
  14275. (or (equal property "")
  14276. (string-match-p "\\s-" property))))
  14277. (defun org--update-property-plist (key val props)
  14278. "Associate KEY to VAL in alist PROPS.
  14279. Modifications are made by side-effect. Return new alist."
  14280. (let* ((appending (string= (substring key -1) "+"))
  14281. (key (if appending (substring key 0 -1) key))
  14282. (old (assoc-string key props t)))
  14283. (if (not old) (cons (cons key val) props)
  14284. (setcdr old (if appending (concat (cdr old) " " val) val))
  14285. props)))
  14286. (defun org-get-property-block (&optional beg force)
  14287. "Return the (beg . end) range of the body of the property drawer.
  14288. BEG is the beginning of the current subtree, or of the part
  14289. before the first headline. If it is not given, it will be found.
  14290. If the drawer does not exist, create it if FORCE is non-nil, or
  14291. return nil."
  14292. (org-with-wide-buffer
  14293. (when beg (goto-char beg))
  14294. (unless (org-before-first-heading-p)
  14295. (let ((beg (cond (beg)
  14296. ((or (not (featurep 'org-inlinetask))
  14297. (org-inlinetask-in-task-p))
  14298. (org-back-to-heading t))
  14299. (t (org-with-limited-levels (org-back-to-heading t))))))
  14300. (forward-line)
  14301. (when (looking-at-p org-planning-line-re) (forward-line))
  14302. (cond ((looking-at org-property-drawer-re)
  14303. (forward-line)
  14304. (cons (point) (progn (goto-char (match-end 0))
  14305. (line-beginning-position))))
  14306. (force
  14307. (goto-char beg)
  14308. (org-insert-property-drawer)
  14309. (let ((pos (save-excursion (search-forward ":END:")
  14310. (line-beginning-position))))
  14311. (cons pos pos))))))))
  14312. (defun org-at-property-p ()
  14313. "Non-nil when point is inside a property drawer.
  14314. See `org-property-re' for match data, if applicable."
  14315. (save-excursion
  14316. (beginning-of-line)
  14317. (and (looking-at org-property-re)
  14318. (let ((property-drawer (save-match-data (org-get-property-block))))
  14319. (and property-drawer
  14320. (>= (point) (car property-drawer))
  14321. (< (point) (cdr property-drawer)))))))
  14322. (defun org-property-action ()
  14323. "Do an action on properties."
  14324. (interactive)
  14325. (unless (org-at-property-p) (user-error "Not at a property"))
  14326. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14327. (let ((c (read-char-exclusive)))
  14328. (cl-case c
  14329. (?s (call-interactively #'org-set-property))
  14330. (?d (call-interactively #'org-delete-property))
  14331. (?D (call-interactively #'org-delete-property-globally))
  14332. (?c (call-interactively #'org-compute-property-at-point))
  14333. (otherwise (user-error "No such property action %c" c)))))
  14334. (defun org-inc-effort ()
  14335. "Increment the value of the effort property in the current entry."
  14336. (interactive)
  14337. (org-set-effort nil t))
  14338. (defvar org-clock-effort) ; Defined in org-clock.el.
  14339. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14340. (defun org-set-effort (&optional value increment)
  14341. "Set the effort property of the current entry.
  14342. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14343. 10th allowed value.
  14344. When INCREMENT is non-nil, set the property to the next allowed value."
  14345. (interactive "P")
  14346. (when (equal value 0) (setq value 10))
  14347. (let* ((completion-ignore-case t)
  14348. (prop org-effort-property)
  14349. (cur (org-entry-get nil prop))
  14350. (allowed (org-property-get-allowed-values nil prop 'table))
  14351. (existing (mapcar 'list (org-property-values prop)))
  14352. (heading (nth 4 (org-heading-components)))
  14353. rpl
  14354. (val (cond
  14355. ((stringp value) value)
  14356. ((and allowed (integerp value))
  14357. (or (car (nth (1- value) allowed))
  14358. (car (org-last allowed))))
  14359. ((and allowed increment)
  14360. (or (cl-caadr (member (list cur) allowed))
  14361. (user-error "Allowed effort values are not set")))
  14362. (allowed
  14363. (message "Select 1-9,0, [RET%s]: %s"
  14364. (if cur (concat "=" cur) "")
  14365. (mapconcat 'car allowed " "))
  14366. (setq rpl (read-char-exclusive))
  14367. (if (equal rpl ?\r)
  14368. cur
  14369. (setq rpl (- rpl ?0))
  14370. (when (equal rpl 0) (setq rpl 10))
  14371. (if (and (> rpl 0) (<= rpl (length allowed)))
  14372. (car (nth (1- rpl) allowed))
  14373. (org-completing-read "Effort: " allowed nil))))
  14374. (t
  14375. (org-completing-read
  14376. (concat "Effort" (and cur (string-match "\\S-" cur)
  14377. (concat " [" cur "]"))
  14378. ": ")
  14379. existing nil nil "" nil cur)))))
  14380. (unless (equal (org-entry-get nil prop) val)
  14381. (org-entry-put nil prop val))
  14382. (org-refresh-property
  14383. '((effort . identity)
  14384. (effort-minutes . org-duration-string-to-minutes))
  14385. val)
  14386. (when (equal heading (bound-and-true-p org-clock-current-task))
  14387. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14388. (org-clock-update-mode-line))
  14389. (message "%s is now %s" prop val)))
  14390. (defun org-entry-properties (&optional pom which)
  14391. "Get all properties of the current entry.
  14392. When POM is a buffer position, get all properties from the entry
  14393. there instead.
  14394. This includes the TODO keyword, the tags, time strings for
  14395. deadline, scheduled, and clocking, and any additional properties
  14396. defined in the entry.
  14397. If WHICH is nil or `all', get all properties. If WHICH is
  14398. `special' or `standard', only get that subclass. If WHICH is
  14399. a string, only get that property.
  14400. Return value is an alist. Keys are properties, as upcased
  14401. strings."
  14402. (org-with-point-at pom
  14403. (when (and (derived-mode-p 'org-mode)
  14404. (ignore-errors (org-back-to-heading t)))
  14405. (catch 'exit
  14406. (let* ((beg (point))
  14407. (specific (and (stringp which) (upcase which)))
  14408. (which (cond ((not specific) which)
  14409. ((member specific org-special-properties) 'special)
  14410. (t 'standard)))
  14411. props)
  14412. ;; Get the special properties, like TODO and TAGS.
  14413. (when (memq which '(nil all special))
  14414. (when (or (not specific) (string= specific "CLOCKSUM"))
  14415. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14416. (when clocksum
  14417. (push (cons "CLOCKSUM"
  14418. (org-minutes-to-clocksum-string clocksum))
  14419. props)))
  14420. (when specific (throw 'exit props)))
  14421. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14422. (let ((clocksumt (get-text-property (point)
  14423. :org-clock-minutes-today)))
  14424. (when clocksumt
  14425. (push (cons "CLOCKSUM_T"
  14426. (org-minutes-to-clocksum-string clocksumt))
  14427. props)))
  14428. (when specific (throw 'exit props)))
  14429. (when (or (not specific) (string= specific "ITEM"))
  14430. (let ((case-fold-search nil))
  14431. (when (looking-at org-complex-heading-regexp)
  14432. (push (cons "ITEM"
  14433. (let ((title (match-string-no-properties 4)))
  14434. (if (org-string-nw-p title)
  14435. (org-remove-tabs title)
  14436. "")))
  14437. props)))
  14438. (when specific (throw 'exit props)))
  14439. (when (or (not specific) (string= specific "TODO"))
  14440. (let ((case-fold-search nil))
  14441. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14442. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14443. (when specific (throw 'exit props)))
  14444. (when (or (not specific) (string= specific "PRIORITY"))
  14445. (push (cons "PRIORITY"
  14446. (if (looking-at org-priority-regexp)
  14447. (match-string-no-properties 2)
  14448. (char-to-string org-default-priority)))
  14449. props)
  14450. (when specific (throw 'exit props)))
  14451. (when (or (not specific) (string= specific "FILE"))
  14452. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14453. props)
  14454. (when specific (throw 'exit props)))
  14455. (when (or (not specific) (string= specific "TAGS"))
  14456. (let ((value (org-string-nw-p (org-get-tags-string))))
  14457. (when value (push (cons "TAGS" value) props)))
  14458. (when specific (throw 'exit props)))
  14459. (when (or (not specific) (string= specific "ALLTAGS"))
  14460. (let ((value (org-get-tags-at)))
  14461. (when value
  14462. (push (cons "ALLTAGS"
  14463. (format ":%s:" (mapconcat #'identity value ":")))
  14464. props)))
  14465. (when specific (throw 'exit props)))
  14466. (when (or (not specific) (string= specific "BLOCKED"))
  14467. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14468. (when specific (throw 'exit props)))
  14469. (when (or (not specific)
  14470. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14471. (forward-line)
  14472. (when (looking-at-p org-planning-line-re)
  14473. (end-of-line)
  14474. (let ((bol (line-beginning-position))
  14475. ;; Backward compatibility: time keywords used to
  14476. ;; be configurable (before 8.3). Make sure we
  14477. ;; get the correct keyword.
  14478. (key-assoc `(("CLOSED" . ,org-closed-string)
  14479. ("DEADLINE" . ,org-deadline-string)
  14480. ("SCHEDULED" . ,org-scheduled-string))))
  14481. (dolist (pair (if specific (list (assoc specific key-assoc))
  14482. key-assoc))
  14483. (save-excursion
  14484. (when (search-backward (cdr pair) bol t)
  14485. (goto-char (match-end 0))
  14486. (skip-chars-forward " \t")
  14487. (and (looking-at org-ts-regexp-both)
  14488. (push (cons (car pair)
  14489. (match-string-no-properties 0))
  14490. props)))))))
  14491. (when specific (throw 'exit props)))
  14492. (when (or (not specific)
  14493. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14494. (let ((find-ts
  14495. (lambda (end ts)
  14496. ;; Fix next time-stamp before END. TS is the
  14497. ;; list of time-stamps found so far.
  14498. (let ((ts ts)
  14499. (regexp (cond
  14500. ((string= specific "TIMESTAMP")
  14501. org-ts-regexp)
  14502. ((string= specific "TIMESTAMP_IA")
  14503. org-ts-regexp-inactive)
  14504. ((assoc "TIMESTAMP_IA" ts)
  14505. org-ts-regexp)
  14506. ((assoc "TIMESTAMP" ts)
  14507. org-ts-regexp-inactive)
  14508. (t org-ts-regexp-both))))
  14509. (catch 'next
  14510. (while (re-search-forward regexp end t)
  14511. (backward-char)
  14512. (let ((object (org-element-context)))
  14513. ;; Accept to match timestamps in node
  14514. ;; properties, too.
  14515. (when (memq (org-element-type object)
  14516. '(node-property timestamp))
  14517. (let ((type
  14518. (org-element-property :type object)))
  14519. (cond
  14520. ((and (memq type '(active active-range))
  14521. (not (equal specific "TIMESTAMP_IA")))
  14522. (unless (assoc "TIMESTAMP" ts)
  14523. (push (cons "TIMESTAMP"
  14524. (org-element-property
  14525. :raw-value object))
  14526. ts)
  14527. (when specific (throw 'exit ts))))
  14528. ((and (memq type '(inactive inactive-range))
  14529. (not (string= specific "TIMESTAMP")))
  14530. (unless (assoc "TIMESTAMP_IA" ts)
  14531. (push (cons "TIMESTAMP_IA"
  14532. (org-element-property
  14533. :raw-value object))
  14534. ts)
  14535. (when specific (throw 'exit ts))))))
  14536. ;; Both timestamp types are found,
  14537. ;; move to next part.
  14538. (when (= (length ts) 2) (throw 'next ts)))))
  14539. ts)))))
  14540. (goto-char beg)
  14541. ;; First look for timestamps within headline.
  14542. (let ((ts (funcall find-ts (line-end-position) nil)))
  14543. (if (= (length ts) 2) (setq props (nconc ts props))
  14544. ;; Then find timestamps in the section, skipping
  14545. ;; planning line.
  14546. (let ((end (save-excursion (outline-next-heading))))
  14547. (forward-line)
  14548. (when (looking-at-p org-planning-line-re) (forward-line))
  14549. (setq props (nconc (funcall find-ts end ts) props))))))))
  14550. ;; Get the standard properties, like :PROP:.
  14551. (when (memq which '(nil all standard))
  14552. ;; If we are looking after a specific property, delegate
  14553. ;; to `org-entry-get', which is faster. However, make an
  14554. ;; exception for "CATEGORY", since it can be also set
  14555. ;; through keywords (i.e. #+CATEGORY).
  14556. (if (and specific (not (equal specific "CATEGORY")))
  14557. (let ((value (org-entry-get beg specific nil t)))
  14558. (throw 'exit (and value (list (cons specific value)))))
  14559. (let ((range (org-get-property-block beg)))
  14560. (when range
  14561. (let ((end (cdr range)) seen-base)
  14562. (goto-char (car range))
  14563. ;; Unlike to `org--update-property-plist', we
  14564. ;; handle the case where base values is found
  14565. ;; after its extension. We also forbid standard
  14566. ;; properties to be named as special properties.
  14567. (while (re-search-forward org-property-re end t)
  14568. (let* ((key (upcase (match-string-no-properties 2)))
  14569. (extendp (string-match-p "\\+\\'" key))
  14570. (key-base (if extendp (substring key 0 -1) key))
  14571. (value (match-string-no-properties 3)))
  14572. (cond
  14573. ((member-ignore-case key-base org-special-properties))
  14574. (extendp
  14575. (setq props
  14576. (org--update-property-plist key value props)))
  14577. ((member key seen-base))
  14578. (t (push key seen-base)
  14579. (let ((p (assoc-string key props t)))
  14580. (if p (setcdr p (concat value " " (cdr p)))
  14581. (push (cons key value) props))))))))))))
  14582. (unless (assoc "CATEGORY" props)
  14583. (push (cons "CATEGORY" (org-get-category beg)) props)
  14584. (when (string= specific "CATEGORY") (throw 'exit props)))
  14585. ;; Return value.
  14586. props)))))
  14587. (defun org--property-local-values (property literal-nil)
  14588. "Return value for PROPERTY in current entry.
  14589. Value is a list whose car is the base value for PROPERTY and cdr
  14590. a list of accumulated values. Return nil if neither is found in
  14591. the entry. Also return nil when PROPERTY is set to \"nil\",
  14592. unless LITERAL-NIL is non-nil."
  14593. (let ((range (org-get-property-block)))
  14594. (when range
  14595. (goto-char (car range))
  14596. (let* ((case-fold-search t)
  14597. (end (cdr range))
  14598. (value
  14599. ;; Base value.
  14600. (save-excursion
  14601. (let ((v (and (re-search-forward
  14602. (org-re-property property nil t) end t)
  14603. (match-string-no-properties 3))))
  14604. (list (if literal-nil v (org-not-nil v)))))))
  14605. ;; Find additional values.
  14606. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14607. (while (re-search-forward property+ end t)
  14608. (push (match-string-no-properties 3) value)))
  14609. ;; Return final values.
  14610. (and (not (equal value '(nil))) (nreverse value))))))
  14611. (defun org--property-global-value (property literal-nil)
  14612. "Return value for PROPERTY in current buffer.
  14613. Return value is a string. Return nil if property is not set
  14614. globally. Also return nil when PROPERTY is set to \"nil\",
  14615. unless LITERAL-NIL is non-nil."
  14616. (let ((global
  14617. (cdr (or (assoc-string property org-file-properties t)
  14618. (assoc-string property org-global-properties t)
  14619. (assoc-string property org-global-properties-fixed t)))))
  14620. (if literal-nil global (org-not-nil global))))
  14621. (defun org-entry-get (pom property &optional inherit literal-nil)
  14622. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14623. If INHERIT is non-nil and the entry does not have the property,
  14624. then also check higher levels of the hierarchy. If INHERIT is
  14625. the symbol `selective', use inheritance only if the setting in
  14626. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14627. If the property is present but empty, the return value is the
  14628. empty string. If the property is not present at all, nil is
  14629. returned. In any other case, return the value as a string.
  14630. Search is case-insensitive.
  14631. If LITERAL-NIL is set, return the string value \"nil\" as
  14632. a string, do not interpret it as the list atom nil. This is used
  14633. for inheritance when a \"nil\" value can supersede a non-nil
  14634. value higher up the hierarchy."
  14635. (org-with-point-at pom
  14636. (cond
  14637. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14638. ;; We need a special property. Use `org-entry-properties' to
  14639. ;; retrieve it, but specify the wanted property.
  14640. (cdr (assoc-string property (org-entry-properties nil property))))
  14641. ((and inherit
  14642. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14643. (org-entry-get-with-inheritance property literal-nil))
  14644. (t
  14645. (let* ((local (org--property-local-values property literal-nil))
  14646. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14647. (if literal-nil value (org-not-nil value)))))))
  14648. (defun org-property-or-variable-value (var &optional inherit)
  14649. "Check if there is a property fixing the value of VAR.
  14650. If yes, return this value. If not, return the current value of the variable."
  14651. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14652. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14653. (read prop)
  14654. (symbol-value var))))
  14655. (defun org-entry-delete (pom property)
  14656. "Delete PROPERTY from entry at point-or-marker POM.
  14657. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14658. non-nil when a property was removed."
  14659. (org-with-point-at pom
  14660. (pcase (org-get-property-block)
  14661. (`(,begin . ,origin)
  14662. (let* ((end (copy-marker origin))
  14663. (re (org-re-property
  14664. (concat (regexp-quote property) "\\+?") t t)))
  14665. (goto-char begin)
  14666. (while (re-search-forward re end t)
  14667. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14668. ;; If drawer is empty, remove it altogether.
  14669. (when (= begin end)
  14670. (delete-region (line-beginning-position 0)
  14671. (line-beginning-position 2)))
  14672. ;; Return non-nil if some property was removed.
  14673. (prog1 (/= end origin) (set-marker end nil))))
  14674. (_ nil))))
  14675. ;; Multi-values properties are properties that contain multiple values
  14676. ;; These values are assumed to be single words, separated by whitespace.
  14677. (defun org-entry-add-to-multivalued-property (pom property value)
  14678. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14679. (let* ((old (org-entry-get pom property))
  14680. (values (and old (org-split-string old "[ \t]"))))
  14681. (setq value (org-entry-protect-space value))
  14682. (unless (member value values)
  14683. (setq values (append values (list value)))
  14684. (org-entry-put pom property
  14685. (mapconcat 'identity values " ")))))
  14686. (defun org-entry-remove-from-multivalued-property (pom property value)
  14687. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14688. (let* ((old (org-entry-get pom property))
  14689. (values (and old (org-split-string old "[ \t]"))))
  14690. (setq value (org-entry-protect-space value))
  14691. (when (member value values)
  14692. (setq values (delete value values))
  14693. (org-entry-put pom property
  14694. (mapconcat 'identity values " ")))))
  14695. (defun org-entry-member-in-multivalued-property (pom property value)
  14696. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14697. (let* ((old (org-entry-get pom property))
  14698. (values (and old (org-split-string old "[ \t]"))))
  14699. (setq value (org-entry-protect-space value))
  14700. (member value values)))
  14701. (defun org-entry-get-multivalued-property (pom property)
  14702. "Return a list of values in a multivalued property."
  14703. (let* ((value (org-entry-get pom property))
  14704. (values (and value (org-split-string value "[ \t]"))))
  14705. (mapcar 'org-entry-restore-space values)))
  14706. (defun org-entry-put-multivalued-property (pom property &rest values)
  14707. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14708. VALUES should be a list of strings. Spaces will be protected."
  14709. (org-entry-put pom property
  14710. (mapconcat 'org-entry-protect-space values " "))
  14711. (let* ((value (org-entry-get pom property))
  14712. (values (and value (org-split-string value "[ \t]"))))
  14713. (mapcar 'org-entry-restore-space values)))
  14714. (defun org-entry-protect-space (s)
  14715. "Protect spaces and newline in string S."
  14716. (while (string-match " " s)
  14717. (setq s (replace-match "%20" t t s)))
  14718. (while (string-match "\n" s)
  14719. (setq s (replace-match "%0A" t t s)))
  14720. s)
  14721. (defun org-entry-restore-space (s)
  14722. "Restore spaces and newline in string S."
  14723. (while (string-match "%20" s)
  14724. (setq s (replace-match " " t t s)))
  14725. (while (string-match "%0A" s)
  14726. (setq s (replace-match "\n" t t s)))
  14727. s)
  14728. (defvar org-entry-property-inherited-from (make-marker)
  14729. "Marker pointing to the entry from where a property was inherited.
  14730. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14731. location of the entry where the inheritance search matched. If there was
  14732. no match, the marker will point nowhere.
  14733. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14734. is set.")
  14735. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14736. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14737. The search will stop at the first ancestor which has the property defined.
  14738. If the value found is \"nil\", return nil to show that the property
  14739. should be considered as undefined (this is the meaning of nil here).
  14740. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14741. (move-marker org-entry-property-inherited-from nil)
  14742. (org-with-wide-buffer
  14743. (let (value)
  14744. (catch 'exit
  14745. (while t
  14746. (let ((v (org--property-local-values property literal-nil)))
  14747. (when v
  14748. (setq value
  14749. (concat (mapconcat #'identity (delq nil v) " ")
  14750. (and value " ")
  14751. value)))
  14752. (cond
  14753. ((car v)
  14754. (org-back-to-heading t)
  14755. (move-marker org-entry-property-inherited-from (point))
  14756. (throw 'exit nil))
  14757. ((org-up-heading-safe))
  14758. (t
  14759. (let ((global (org--property-global-value property literal-nil)))
  14760. (cond ((not global))
  14761. (value (setq value (concat global " " value)))
  14762. (t (setq value global))))
  14763. (throw 'exit nil))))))
  14764. (if literal-nil value (org-not-nil value)))))
  14765. (defvar org-property-changed-functions nil
  14766. "Hook called when the value of a property has changed.
  14767. Each hook function should accept two arguments, the name of the property
  14768. and the new value.")
  14769. (defun org-entry-put (pom property value)
  14770. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14771. If the value is nil, it is converted to the empty string. If it
  14772. is not a string, an error is raised. Also raise an error on
  14773. invalid property names.
  14774. PROPERTY can be any regular property (see
  14775. `org-special-properties'). It can also be \"TODO\",
  14776. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14777. For the last two properties, VALUE may have any of the special
  14778. values \"earlier\" and \"later\". The function then increases or
  14779. decreases scheduled or deadline date by one day."
  14780. (cond ((null value) (setq value ""))
  14781. ((not (stringp value)) (error "Properties values should be strings"))
  14782. ((not (org--valid-property-p property))
  14783. (user-error "Invalid property name: \"%s\"" property)))
  14784. (org-with-point-at pom
  14785. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14786. (org-back-to-heading t)
  14787. (org-with-limited-levels (org-back-to-heading t)))
  14788. (let ((beg (point)))
  14789. (cond
  14790. ((equal property "TODO")
  14791. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14792. ((not (member value org-todo-keywords-1))
  14793. (user-error "\"%s\" is not a valid TODO state" value)))
  14794. (org-todo value)
  14795. (org-set-tags nil 'align))
  14796. ((equal property "PRIORITY")
  14797. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14798. (org-set-tags nil 'align))
  14799. ((equal property "SCHEDULED")
  14800. (forward-line)
  14801. (if (and (looking-at-p org-planning-line-re)
  14802. (re-search-forward
  14803. org-scheduled-time-regexp (line-end-position) t))
  14804. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14805. ((string= value "later") (org-timestamp-change 1 'day))
  14806. ((string= value "") (org-schedule '(4)))
  14807. (t (org-schedule nil value)))
  14808. (if (member value '("earlier" "later" ""))
  14809. (call-interactively #'org-schedule)
  14810. (org-schedule nil value))))
  14811. ((equal property "DEADLINE")
  14812. (forward-line)
  14813. (if (and (looking-at-p org-planning-line-re)
  14814. (re-search-forward
  14815. org-deadline-time-regexp (line-end-position) t))
  14816. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14817. ((string= value "later") (org-timestamp-change 1 'day))
  14818. ((string= value "") (org-deadline '(4)))
  14819. (t (org-deadline nil value)))
  14820. (if (member value '("earlier" "later" ""))
  14821. (call-interactively #'org-deadline)
  14822. (org-deadline nil value))))
  14823. ((member property org-special-properties)
  14824. (error "The %s property cannot be set with `org-entry-put'" property))
  14825. (t
  14826. (let* ((range (org-get-property-block beg 'force))
  14827. (end (cdr range))
  14828. (case-fold-search t))
  14829. (goto-char (car range))
  14830. (if (re-search-forward (org-re-property property nil t) end t)
  14831. (progn (delete-region (match-beginning 0) (match-end 0))
  14832. (goto-char (match-beginning 0)))
  14833. (goto-char end)
  14834. (insert "\n")
  14835. (backward-char))
  14836. (insert ":" property ":")
  14837. (when value (insert " " value))
  14838. (org-indent-line)))))
  14839. (run-hook-with-args 'org-property-changed-functions property value)))
  14840. (defun org-buffer-property-keys
  14841. (&optional specials defaults columns ignore-malformed)
  14842. "Get all property keys in the current buffer.
  14843. When SPECIALS is non-nil, also list the special properties that
  14844. reflect things like tags and TODO state.
  14845. When DEFAULTS is non-nil, also include properties that has
  14846. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14847. DESCRIPTION, LOCATION, and LOGGING and others.
  14848. When COLUMNS in non-nil, also include property names given in
  14849. COLUMN formats in the current buffer.
  14850. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14851. automatically performed, such drawers will be silently ignored."
  14852. (let ((case-fold-search t)
  14853. (props (append
  14854. (and specials org-special-properties)
  14855. (and defaults (cons org-effort-property org-default-properties))
  14856. nil)))
  14857. (org-with-wide-buffer
  14858. (goto-char (point-min))
  14859. (while (re-search-forward org-property-start-re nil t)
  14860. (let ((range (org-get-property-block)))
  14861. (catch 'skip
  14862. (unless range
  14863. (when (and (not ignore-malformed)
  14864. (not (org-before-first-heading-p))
  14865. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14866. (line-beginning-position))))
  14867. (org-get-property-block nil t))
  14868. (throw 'skip nil))
  14869. (goto-char (car range))
  14870. (let ((begin (car range))
  14871. (end (cdr range)))
  14872. ;; Make sure that found property block is not located
  14873. ;; before current point, as it would generate an infloop.
  14874. ;; It can happen, for example, in the following
  14875. ;; situation:
  14876. ;;
  14877. ;; * Headline
  14878. ;; :PROPERTIES:
  14879. ;; ...
  14880. ;; :END:
  14881. ;; *************** Inlinetask
  14882. ;; #+BEGIN_EXAMPLE
  14883. ;; :PROPERTIES:
  14884. ;; #+END_EXAMPLE
  14885. ;;
  14886. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14887. (while (< (point) end)
  14888. (let ((p (progn (looking-at org-property-re)
  14889. (match-string-no-properties 2))))
  14890. ;; Only add true property name, not extension symbol.
  14891. (push (if (not (string-match-p "\\+\\'" p)) p
  14892. (substring p 0 -1))
  14893. props))
  14894. (forward-line))))
  14895. (outline-next-heading)))
  14896. (when columns
  14897. (goto-char (point-min))
  14898. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14899. (let ((element (org-element-at-point)))
  14900. (when (memq (org-element-type element) '(keyword node-property))
  14901. (let ((value (org-element-property :value element))
  14902. (start 0))
  14903. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14904. (setq start (match-end 0))
  14905. (let ((p (match-string-no-properties 1 value)))
  14906. (unless (member-ignore-case p org-special-properties)
  14907. (push p props))))))))))
  14908. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14909. (defun org-property-values (key)
  14910. "List all non-nil values of property KEY in current buffer."
  14911. (org-with-wide-buffer
  14912. (goto-char (point-min))
  14913. (let ((case-fold-search t)
  14914. (re (org-re-property key))
  14915. values)
  14916. (while (re-search-forward re nil t)
  14917. (push (org-entry-get (point) key) values))
  14918. (delete-dups values))))
  14919. (defun org-insert-property-drawer ()
  14920. "Insert a property drawer into the current entry."
  14921. (org-with-wide-buffer
  14922. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14923. (org-back-to-heading t)
  14924. (org-with-limited-levels (org-back-to-heading t)))
  14925. (forward-line)
  14926. (when (looking-at-p org-planning-line-re) (forward-line))
  14927. (unless (looking-at-p org-property-drawer-re)
  14928. ;; Make sure we start editing a line from current entry, not from
  14929. ;; next one. It prevents extending text properties or overlays
  14930. ;; belonging to the latter.
  14931. (when (bolp) (backward-char))
  14932. (let ((begin (1+ (point)))
  14933. (inhibit-read-only t))
  14934. (insert "\n:PROPERTIES:\n:END:")
  14935. (when (eobp) (insert "\n"))
  14936. (org-indent-region begin (point))))))
  14937. (defun org-insert-drawer (&optional arg drawer)
  14938. "Insert a drawer at point.
  14939. When optional argument ARG is non-nil, insert a property drawer.
  14940. Optional argument DRAWER, when non-nil, is a string representing
  14941. drawer's name. Otherwise, the user is prompted for a name.
  14942. If a region is active, insert the drawer around that region
  14943. instead.
  14944. Point is left between drawer's boundaries."
  14945. (interactive "P")
  14946. (let* ((drawer (if arg "PROPERTIES"
  14947. (or drawer (read-from-minibuffer "Drawer: ")))))
  14948. (cond
  14949. ;; With C-u, fall back on `org-insert-property-drawer'
  14950. (arg (org-insert-property-drawer))
  14951. ;; Check validity of suggested drawer's name.
  14952. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14953. (user-error "Invalid drawer name"))
  14954. ;; With an active region, insert a drawer at point.
  14955. ((not (org-region-active-p))
  14956. (progn
  14957. (unless (bolp) (insert "\n"))
  14958. (insert (format ":%s:\n\n:END:\n" drawer))
  14959. (forward-line -2)))
  14960. ;; Otherwise, insert the drawer at point
  14961. (t
  14962. (let ((rbeg (region-beginning))
  14963. (rend (copy-marker (region-end))))
  14964. (unwind-protect
  14965. (progn
  14966. (goto-char rbeg)
  14967. (beginning-of-line)
  14968. (when (save-excursion
  14969. (re-search-forward org-outline-regexp-bol rend t))
  14970. (user-error "Drawers cannot contain headlines"))
  14971. ;; Position point at the beginning of the first
  14972. ;; non-blank line in region. Insert drawer's opening
  14973. ;; there, then indent it.
  14974. (org-skip-whitespace)
  14975. (beginning-of-line)
  14976. (insert ":" drawer ":\n")
  14977. (forward-line -1)
  14978. (indent-for-tab-command)
  14979. ;; Move point to the beginning of the first blank line
  14980. ;; after the last non-blank line in region. Insert
  14981. ;; drawer's closing, then indent it.
  14982. (goto-char rend)
  14983. (skip-chars-backward " \r\t\n")
  14984. (insert "\n:END:")
  14985. (deactivate-mark t)
  14986. (indent-for-tab-command)
  14987. (unless (eolp) (insert "\n")))
  14988. ;; Clear marker, whatever the outcome of insertion is.
  14989. (set-marker rend nil)))))))
  14990. (defvar org-property-set-functions-alist nil
  14991. "Property set function alist.
  14992. Each entry should have the following format:
  14993. (PROPERTY . READ-FUNCTION)
  14994. The read function will be called with the same argument as
  14995. `org-completing-read'.")
  14996. (defun org-set-property-function (property)
  14997. "Get the function that should be used to set PROPERTY.
  14998. This is computed according to `org-property-set-functions-alist'."
  14999. (or (cdr (assoc property org-property-set-functions-alist))
  15000. 'org-completing-read))
  15001. (defun org-read-property-value (property)
  15002. "Read PROPERTY value from user."
  15003. (let* ((completion-ignore-case t)
  15004. (allowed (org-property-get-allowed-values nil property 'table))
  15005. (cur (org-entry-get nil property))
  15006. (prompt (concat property " value"
  15007. (if (and cur (string-match "\\S-" cur))
  15008. (concat " [" cur "]") "") ": "))
  15009. (set-function (org-set-property-function property))
  15010. (val (if allowed
  15011. (funcall set-function prompt allowed nil
  15012. (not (get-text-property 0 'org-unrestricted
  15013. (caar allowed))))
  15014. (funcall set-function prompt
  15015. (mapcar 'list (org-property-values property))
  15016. nil nil "" nil cur))))
  15017. (org-trim val)))
  15018. (defvar org-last-set-property nil)
  15019. (defvar org-last-set-property-value nil)
  15020. (defun org-read-property-name ()
  15021. "Read a property name."
  15022. (let ((completion-ignore-case t)
  15023. (default-prop (or (and (org-at-property-p)
  15024. (match-string-no-properties 2))
  15025. org-last-set-property)))
  15026. (org-completing-read
  15027. (concat "Property"
  15028. (if default-prop (concat " [" default-prop "]") "")
  15029. ": ")
  15030. (mapcar #'list (org-buffer-property-keys nil t t))
  15031. nil nil nil nil default-prop)))
  15032. (defun org-set-property-and-value (use-last)
  15033. "Allow to set [PROPERTY]: [value] direction from prompt.
  15034. When use-default, don't even ask, just use the last
  15035. \"[PROPERTY]: [value]\" string from the history."
  15036. (interactive "P")
  15037. (let* ((completion-ignore-case t)
  15038. (pv (or (and use-last org-last-set-property-value)
  15039. (org-completing-read
  15040. "Enter a \"[Property]: [value]\" pair: "
  15041. nil nil nil nil nil
  15042. org-last-set-property-value)))
  15043. prop val)
  15044. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  15045. (setq prop (match-string 1 pv)
  15046. val (match-string 2 pv))
  15047. (org-set-property prop val))))
  15048. (defun org-set-property (property value)
  15049. "In the current entry, set PROPERTY to VALUE.
  15050. When called interactively, this will prompt for a property name, offering
  15051. completion on existing and default properties. And then it will prompt
  15052. for a value, offering completion either on allowed values (via an inherited
  15053. xxx_ALL property) or on existing values in other instances of this property
  15054. in the current file.
  15055. Throw an error when trying to set a property with an invalid name."
  15056. (interactive (list nil nil))
  15057. (let ((property (or property (org-read-property-name))))
  15058. ;; `org-entry-put' also makes the following check, but this one
  15059. ;; avoids polluting `org-last-set-property' and
  15060. ;; `org-last-set-property-value' needlessly.
  15061. (unless (org--valid-property-p property)
  15062. (user-error "Invalid property name: \"%s\"" property))
  15063. (let ((value (or value (org-read-property-value property)))
  15064. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15065. (setq org-last-set-property property)
  15066. (setq org-last-set-property-value (concat property ": " value))
  15067. ;; Possibly postprocess the inserted value:
  15068. (when fn (setq value (funcall fn value)))
  15069. (unless (equal (org-entry-get nil property) value)
  15070. (org-entry-put nil property value)))))
  15071. (defun org-find-property (property &optional value)
  15072. "Find first entry in buffer that sets PROPERTY.
  15073. When optional argument VALUE is non-nil, only consider an entry
  15074. if it contains PROPERTY set to this value. If PROPERTY should be
  15075. explicitly set to nil, use string \"nil\" for VALUE.
  15076. Return position where the entry begins, or nil if there is no
  15077. such entry. If narrowing is in effect, only search the visible
  15078. part of the buffer."
  15079. (save-excursion
  15080. (goto-char (point-min))
  15081. (let ((case-fold-search t)
  15082. (re (org-re-property property nil (not value) value)))
  15083. (catch 'exit
  15084. (while (re-search-forward re nil t)
  15085. (when (if value (org-at-property-p)
  15086. (org-entry-get (point) property nil t))
  15087. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15088. (defun org-delete-property (property)
  15089. "In the current entry, delete PROPERTY."
  15090. (interactive
  15091. (let* ((completion-ignore-case t)
  15092. (cat (org-entry-get (point) "CATEGORY"))
  15093. (props0 (org-entry-properties nil 'standard))
  15094. (props (if cat props0
  15095. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15096. (prop (if (< 1 (length props))
  15097. (completing-read "Property: " props nil t)
  15098. (caar props))))
  15099. (list prop)))
  15100. (if (not property)
  15101. (message "No property to delete in this entry")
  15102. (org-entry-delete nil property)
  15103. (message "Property \"%s\" deleted" property)))
  15104. (defun org-delete-property-globally (property)
  15105. "Remove PROPERTY globally, from all entries.
  15106. This function ignores narrowing, if any."
  15107. (interactive
  15108. (let* ((completion-ignore-case t)
  15109. (prop (completing-read
  15110. "Globally remove property: "
  15111. (mapcar #'list (org-buffer-property-keys)))))
  15112. (list prop)))
  15113. (org-with-wide-buffer
  15114. (goto-char (point-min))
  15115. (let ((count 0)
  15116. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15117. (while (re-search-forward re nil t)
  15118. (when (org-entry-delete (point) property) (cl-incf count)))
  15119. (message "Property \"%s\" removed from %d entries" property count))))
  15120. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15121. (defun org-compute-property-at-point ()
  15122. "Compute the property at point.
  15123. This looks for an enclosing column format, extracts the operator and
  15124. then applies it to the property in the column format's scope."
  15125. (interactive)
  15126. (unless (org-at-property-p)
  15127. (user-error "Not at a property"))
  15128. (let ((prop (match-string-no-properties 2)))
  15129. (org-columns-get-format-and-top-level)
  15130. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15131. (user-error "No operator defined for property %s" prop))
  15132. (org-columns-compute prop)))
  15133. (defvar org-property-allowed-value-functions nil
  15134. "Hook for functions supplying allowed values for a specific property.
  15135. The functions must take a single argument, the name of the property, and
  15136. return a flat list of allowed values. If \":ETC\" is one of
  15137. the values, this means that these values are intended as defaults for
  15138. completion, but that other values should be allowed too.
  15139. The functions must return nil if they are not responsible for this
  15140. property.")
  15141. (defun org-property-get-allowed-values (pom property &optional table)
  15142. "Get allowed values for the property PROPERTY.
  15143. When TABLE is non-nil, return an alist that can directly be used for
  15144. completion."
  15145. (let (vals)
  15146. (cond
  15147. ((equal property "TODO")
  15148. (setq vals (org-with-point-at pom
  15149. (append org-todo-keywords-1 '("")))))
  15150. ((equal property "PRIORITY")
  15151. (let ((n org-lowest-priority))
  15152. (while (>= n org-highest-priority)
  15153. (push (char-to-string n) vals)
  15154. (setq n (1- n)))))
  15155. ((equal property "CATEGORY"))
  15156. ((member property org-special-properties))
  15157. ((setq vals (run-hook-with-args-until-success
  15158. 'org-property-allowed-value-functions property)))
  15159. (t
  15160. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15161. (when (and vals (string-match "\\S-" vals))
  15162. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15163. (setq vals (mapcar (lambda (x)
  15164. (cond ((stringp x) x)
  15165. ((numberp x) (number-to-string x))
  15166. ((symbolp x) (symbol-name x))
  15167. (t "???")))
  15168. vals)))))
  15169. (when (member ":ETC" vals)
  15170. (setq vals (remove ":ETC" vals))
  15171. (org-add-props (car vals) '(org-unrestricted t)))
  15172. (if table (mapcar 'list vals) vals)))
  15173. (defun org-property-previous-allowed-value (&optional _previous)
  15174. "Switch to the next allowed value for this property."
  15175. (interactive)
  15176. (org-property-next-allowed-value t))
  15177. (defun org-property-next-allowed-value (&optional previous)
  15178. "Switch to the next allowed value for this property."
  15179. (interactive)
  15180. (unless (org-at-property-p)
  15181. (user-error "Not at a property"))
  15182. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15183. (key (match-string 2))
  15184. (value (match-string 3))
  15185. (allowed (or (org-property-get-allowed-values (point) key)
  15186. (and (member value '("[ ]" "[-]" "[X]"))
  15187. '("[ ]" "[X]"))))
  15188. (heading (save-match-data (nth 4 (org-heading-components))))
  15189. nval)
  15190. (unless allowed
  15191. (user-error "Allowed values for this property have not been defined"))
  15192. (when previous (setq allowed (reverse allowed)))
  15193. (when (member value allowed)
  15194. (setq nval (car (cdr (member value allowed)))))
  15195. (setq nval (or nval (car allowed)))
  15196. (when (equal nval value)
  15197. (user-error "Only one allowed value for this property"))
  15198. (org-at-property-p)
  15199. (replace-match (concat " :" key ": " nval) t t)
  15200. (org-indent-line)
  15201. (beginning-of-line 1)
  15202. (skip-chars-forward " \t")
  15203. (when (equal prop org-effort-property)
  15204. (org-refresh-property
  15205. '((effort . identity)
  15206. (effort-minutes . org-duration-string-to-minutes))
  15207. nval)
  15208. (when (string= org-clock-current-task heading)
  15209. (setq org-clock-effort nval)
  15210. (org-clock-update-mode-line)))
  15211. (run-hook-with-args 'org-property-changed-functions key nval)))
  15212. (defun org-find-olp (path &optional this-buffer)
  15213. "Return a marker pointing to the entry at outline path OLP.
  15214. If anything goes wrong, throw an error.
  15215. You can wrap this call to catch the error like this:
  15216. (condition-case msg
  15217. (org-mobile-locate-entry (match-string 4))
  15218. (error (nth 1 msg)))
  15219. The return value will then be either a string with the error message,
  15220. or a marker if everything is OK.
  15221. If THIS-BUFFER is set, the outline path does not contain a file,
  15222. only headings."
  15223. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15224. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15225. (level 1)
  15226. (lmin 1)
  15227. (lmax 1)
  15228. end found flevel)
  15229. (unless buffer (error "File not found :%s" file))
  15230. (with-current-buffer buffer
  15231. (org-with-wide-buffer
  15232. (goto-char (point-min))
  15233. (dolist (heading path)
  15234. (let ((re (format org-complex-heading-regexp-format
  15235. (regexp-quote heading)))
  15236. (cnt 0))
  15237. (while (re-search-forward re end t)
  15238. (setq level (- (match-end 1) (match-beginning 1)))
  15239. (when (and (>= level lmin) (<= level lmax))
  15240. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15241. (when (= cnt 0)
  15242. (error "Heading not found on level %d: %s" lmax heading))
  15243. (when (> cnt 1)
  15244. (error "Heading not unique on level %d: %s" lmax heading))
  15245. (goto-char found)
  15246. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15247. (setq end (save-excursion (org-end-of-subtree t t)))))
  15248. (when (org-at-heading-p)
  15249. (point-marker))))))
  15250. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15251. "Find node HEADING in BUFFER.
  15252. Return a marker to the heading if it was found, or nil if not.
  15253. If POS-ONLY is set, return just the position instead of a marker.
  15254. The heading text must match exact, but it may have a TODO keyword,
  15255. a priority cookie and tags in the standard locations."
  15256. (with-current-buffer (or buffer (current-buffer))
  15257. (org-with-wide-buffer
  15258. (goto-char (point-min))
  15259. (let (case-fold-search)
  15260. (when (re-search-forward
  15261. (format org-complex-heading-regexp-format
  15262. (regexp-quote heading)) nil t)
  15263. (if pos-only
  15264. (match-beginning 0)
  15265. (move-marker (make-marker) (match-beginning 0))))))))
  15266. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15267. "Find Org node headline HEADING in all .org files in directory DIR.
  15268. When the target headline is found, return a marker to this location."
  15269. (let ((files (directory-files (or dir default-directory)
  15270. t "\\`[^.#].*\\.org\\'"))
  15271. visiting m buffer)
  15272. (catch 'found
  15273. (dolist (file files)
  15274. (message "trying %s" file)
  15275. (setq visiting (org-find-base-buffer-visiting file))
  15276. (setq buffer (or visiting (find-file-noselect file)))
  15277. (setq m (org-find-exact-headline-in-buffer
  15278. heading buffer))
  15279. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15280. (and m (throw 'found m))))))
  15281. (defun org-find-entry-with-id (ident)
  15282. "Locate the entry that contains the ID property with exact value IDENT.
  15283. IDENT can be a string, a symbol or a number, this function will search for
  15284. the string representation of it.
  15285. Return the position where this entry starts, or nil if there is no such entry."
  15286. (interactive "sID: ")
  15287. (let ((id (cond
  15288. ((stringp ident) ident)
  15289. ((symbolp ident) (symbol-name ident))
  15290. ((numberp ident) (number-to-string ident))
  15291. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15292. (org-with-wide-buffer (org-find-property "ID" id))))
  15293. ;;;; Timestamps
  15294. (defvar org-last-changed-timestamp nil)
  15295. (defvar org-last-inserted-timestamp nil
  15296. "The last time stamp inserted with `org-insert-time-stamp'.")
  15297. (defvar org-ts-what) ; dynamically scoped parameter
  15298. (defun org-time-stamp (arg &optional inactive)
  15299. "Prompt for a date/time and insert a time stamp.
  15300. If the user specifies a time like HH:MM or if this command is
  15301. called with at least one prefix argument, the time stamp contains
  15302. the date and the time. Otherwise, only the date is included.
  15303. All parts of a date not specified by the user are filled in from
  15304. the timestamp at point, if any, or the current date/time
  15305. otherwise.
  15306. If there is already a timestamp at the cursor, it is replaced.
  15307. With two universal prefix arguments, insert an active timestamp
  15308. with the current time without prompting the user.
  15309. When called from lisp, the timestamp is inactive if INACTIVE is
  15310. non-nil."
  15311. (interactive "P")
  15312. (let* ((ts (cond
  15313. ((org-at-date-range-p t)
  15314. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15315. ((org-at-timestamp-p t) (match-string 0))))
  15316. ;; Default time is either the timestamp at point or today.
  15317. ;; When entering a range, only the range start is considered.
  15318. (default-time (if (not ts) (current-time)
  15319. (apply #'encode-time (org-parse-time-string ts))))
  15320. (default-input (and ts (org-get-compact-tod ts)))
  15321. (repeater (and ts
  15322. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15323. (match-string 0 ts)))
  15324. org-time-was-given
  15325. org-end-time-was-given
  15326. (time
  15327. (and (if (equal arg '(16)) (current-time)
  15328. ;; Preserve `this-command' and `last-command'.
  15329. (let ((this-command this-command)
  15330. (last-command last-command))
  15331. (org-read-date
  15332. arg 'totime nil nil default-time default-input
  15333. inactive))))))
  15334. (cond
  15335. ((and ts
  15336. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15337. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15338. (insert "--")
  15339. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15340. (ts
  15341. ;; Make sure we're on a timestamp. When in the middle of a date
  15342. ;; range, move arbitrarily to range end.
  15343. (unless (org-at-timestamp-p t)
  15344. (skip-chars-forward "-")
  15345. (org-at-timestamp-p t))
  15346. (replace-match "")
  15347. (setq org-last-changed-timestamp
  15348. (org-insert-time-stamp
  15349. time (or org-time-was-given arg)
  15350. inactive nil nil (list org-end-time-was-given)))
  15351. (when repeater
  15352. (backward-char)
  15353. (insert " " repeater)
  15354. (setq org-last-changed-timestamp
  15355. (concat (substring org-last-inserted-timestamp 0 -1)
  15356. " " repeater ">")))
  15357. (message "Timestamp updated"))
  15358. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15359. (t (org-insert-time-stamp
  15360. time (or org-time-was-given arg) inactive nil nil
  15361. (list org-end-time-was-given))))))
  15362. ;; FIXME: can we use this for something else, like computing time differences?
  15363. (defun org-get-compact-tod (s)
  15364. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15365. (let* ((t1 (match-string 1 s))
  15366. (h1 (string-to-number (match-string 2 s)))
  15367. (m1 (string-to-number (match-string 3 s)))
  15368. (t2 (and (match-end 4) (match-string 5 s)))
  15369. (h2 (and t2 (string-to-number (match-string 6 s))))
  15370. (m2 (and t2 (string-to-number (match-string 7 s))))
  15371. dh dm)
  15372. (if (not t2)
  15373. t1
  15374. (setq dh (- h2 h1) dm (- m2 m1))
  15375. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15376. (concat t1 "+" (number-to-string dh)
  15377. (and (/= 0 dm) (format ":%02d" dm)))))))
  15378. (defun org-time-stamp-inactive (&optional arg)
  15379. "Insert an inactive time stamp.
  15380. An inactive time stamp is enclosed in square brackets instead of angle
  15381. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15382. does not link to the calendar and cannot be changed with the S-cursor keys.
  15383. So these are more for recording a certain time/date."
  15384. (interactive "P")
  15385. (org-time-stamp arg 'inactive))
  15386. (defvar org-date-ovl (make-overlay 1 1))
  15387. (overlay-put org-date-ovl 'face 'org-date-selected)
  15388. (delete-overlay org-date-ovl)
  15389. (defvar org-ans1) ; dynamically scoped parameter
  15390. (defvar org-ans2) ; dynamically scoped parameter
  15391. (defvar org-plain-time-of-day-regexp) ; defined below
  15392. (defvar org-overriding-default-time nil) ; dynamically scoped
  15393. (defvar org-read-date-overlay nil)
  15394. (defvar org-dcst nil) ; dynamically scoped
  15395. (defvar org-read-date-history nil)
  15396. (defvar org-read-date-final-answer nil)
  15397. (defvar org-read-date-analyze-futurep nil)
  15398. (defvar org-read-date-analyze-forced-year nil)
  15399. (defvar org-read-date-inactive)
  15400. (defvar org-read-date-minibuffer-local-map
  15401. (let* ((map (make-sparse-keymap)))
  15402. (set-keymap-parent map minibuffer-local-map)
  15403. (org-defkey map (kbd ".")
  15404. (lambda () (interactive)
  15405. ;; Are we at the beginning of the prompt?
  15406. (if (looking-back "^[^:]+: "
  15407. (let ((inhibit-field-text-motion t))
  15408. (line-beginning-position)))
  15409. (org-eval-in-calendar '(calendar-goto-today))
  15410. (insert "."))))
  15411. (org-defkey map (kbd "C-.")
  15412. (lambda () (interactive)
  15413. (org-eval-in-calendar '(calendar-goto-today))))
  15414. (org-defkey map [(meta shift left)]
  15415. (lambda () (interactive)
  15416. (org-eval-in-calendar '(calendar-backward-month 1))))
  15417. (org-defkey map [(meta shift right)]
  15418. (lambda () (interactive)
  15419. (org-eval-in-calendar '(calendar-forward-month 1))))
  15420. (org-defkey map [(meta shift up)]
  15421. (lambda () (interactive)
  15422. (org-eval-in-calendar '(calendar-backward-year 1))))
  15423. (org-defkey map [(meta shift down)]
  15424. (lambda () (interactive)
  15425. (org-eval-in-calendar '(calendar-forward-year 1))))
  15426. (org-defkey map [?\e (shift left)]
  15427. (lambda () (interactive)
  15428. (org-eval-in-calendar '(calendar-backward-month 1))))
  15429. (org-defkey map [?\e (shift right)]
  15430. (lambda () (interactive)
  15431. (org-eval-in-calendar '(calendar-forward-month 1))))
  15432. (org-defkey map [?\e (shift up)]
  15433. (lambda () (interactive)
  15434. (org-eval-in-calendar '(calendar-backward-year 1))))
  15435. (org-defkey map [?\e (shift down)]
  15436. (lambda () (interactive)
  15437. (org-eval-in-calendar '(calendar-forward-year 1))))
  15438. (org-defkey map [(shift up)]
  15439. (lambda () (interactive)
  15440. (org-eval-in-calendar '(calendar-backward-week 1))))
  15441. (org-defkey map [(shift down)]
  15442. (lambda () (interactive)
  15443. (org-eval-in-calendar '(calendar-forward-week 1))))
  15444. (org-defkey map [(shift left)]
  15445. (lambda () (interactive)
  15446. (org-eval-in-calendar '(calendar-backward-day 1))))
  15447. (org-defkey map [(shift right)]
  15448. (lambda () (interactive)
  15449. (org-eval-in-calendar '(calendar-forward-day 1))))
  15450. (org-defkey map "!"
  15451. (lambda () (interactive)
  15452. (org-eval-in-calendar '(diary-view-entries))
  15453. (message "")))
  15454. (org-defkey map ">"
  15455. (lambda () (interactive)
  15456. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15457. (org-defkey map "<"
  15458. (lambda () (interactive)
  15459. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15460. (org-defkey map "\C-v"
  15461. (lambda () (interactive)
  15462. (org-eval-in-calendar
  15463. '(calendar-scroll-left-three-months 1))))
  15464. (org-defkey map "\M-v"
  15465. (lambda () (interactive)
  15466. (org-eval-in-calendar
  15467. '(calendar-scroll-right-three-months 1))))
  15468. map)
  15469. "Keymap for minibuffer commands when using `org-read-date'.")
  15470. (defvar org-def)
  15471. (defvar org-defdecode)
  15472. (defvar org-with-time)
  15473. (defvar calendar-setup) ; Dynamically scoped.
  15474. (defun org-read-date (&optional with-time to-time from-string prompt
  15475. default-time default-input inactive)
  15476. "Read a date, possibly a time, and make things smooth for the user.
  15477. The prompt will suggest to enter an ISO date, but you can also enter anything
  15478. which will at least partially be understood by `parse-time-string'.
  15479. Unrecognized parts of the date will default to the current day, month, year,
  15480. hour and minute. If this command is called to replace a timestamp at point,
  15481. or to enter the second timestamp of a range, the default time is taken
  15482. from the existing stamp. Furthermore, the command prefers the future,
  15483. so if you are giving a date where the year is not given, and the day-month
  15484. combination is already past in the current year, it will assume you
  15485. mean next year. For details, see the manual. A few examples:
  15486. 3-2-5 --> 2003-02-05
  15487. feb 15 --> currentyear-02-15
  15488. 2/15 --> currentyear-02-15
  15489. sep 12 9 --> 2009-09-12
  15490. 12:45 --> today 12:45
  15491. 22 sept 0:34 --> currentyear-09-22 0:34
  15492. 12 --> currentyear-currentmonth-12
  15493. Fri --> nearest Friday after today
  15494. -Tue --> last Tuesday
  15495. etc.
  15496. Furthermore you can specify a relative date by giving, as the *first* thing
  15497. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15498. change in days weeks, months, years.
  15499. With a single plus or minus, the date is relative to today. With a double
  15500. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15501. +4d --> four days from today
  15502. +4 --> same as above
  15503. +2w --> two weeks from today
  15504. ++5 --> five days from default date
  15505. The function understands only English month and weekday abbreviations.
  15506. While prompting, a calendar is popped up - you can also select the
  15507. date with the mouse (button 1). The calendar shows a period of three
  15508. months. To scroll it to other months, use the keys `>' and `<'.
  15509. If you don't like the calendar, turn it off with
  15510. (setq org-read-date-popup-calendar nil)
  15511. With optional argument TO-TIME, the date will immediately be converted
  15512. to an internal time.
  15513. With an optional argument WITH-TIME, the prompt will suggest to
  15514. also insert a time. Note that when WITH-TIME is not set, you can
  15515. still enter a time, and this function will inform the calling routine
  15516. about this change. The calling routine may then choose to change the
  15517. format used to insert the time stamp into the buffer to include the time.
  15518. With optional argument FROM-STRING, read from this string instead from
  15519. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15520. the time/date that is used for everything that is not specified by the
  15521. user."
  15522. (require 'parse-time)
  15523. (let* ((org-with-time with-time)
  15524. (org-time-stamp-rounding-minutes
  15525. (if (equal org-with-time '(16))
  15526. '(0 0)
  15527. org-time-stamp-rounding-minutes))
  15528. (org-dcst org-display-custom-times)
  15529. (ct (org-current-time))
  15530. (org-def (or org-overriding-default-time default-time ct))
  15531. (org-defdecode (decode-time org-def))
  15532. (cur-frame (selected-frame))
  15533. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15534. (calendar-setup
  15535. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15536. (calendar-move-hook nil)
  15537. (calendar-view-diary-initially-flag nil)
  15538. (calendar-view-holidays-initially-flag nil)
  15539. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15540. ;; Rationalize `org-def' and `org-defdecode', if required.
  15541. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15542. (setf (nth 2 org-defdecode) -1)
  15543. (setf (nth 1 org-defdecode) 59)
  15544. (setq org-def (apply #'encode-time org-defdecode))
  15545. (setq org-defdecode (decode-time org-def)))
  15546. (let* ((timestr (format-time-string
  15547. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15548. org-def))
  15549. (prompt (concat (if prompt (concat prompt " ") "")
  15550. (format "Date+time [%s]: " timestr))))
  15551. (cond
  15552. (from-string (setq ans from-string))
  15553. (org-read-date-popup-calendar
  15554. (save-excursion
  15555. (save-window-excursion
  15556. (calendar)
  15557. (when (eq calendar-setup 'calendar-only)
  15558. (setq cal-frame
  15559. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15560. (select-frame cal-frame))
  15561. (org-eval-in-calendar '(setq cursor-type nil) t)
  15562. (unwind-protect
  15563. (progn
  15564. (calendar-forward-day (- (time-to-days org-def)
  15565. (calendar-absolute-from-gregorian
  15566. (calendar-current-date))))
  15567. (org-eval-in-calendar nil t)
  15568. (let* ((old-map (current-local-map))
  15569. (map (copy-keymap calendar-mode-map))
  15570. (minibuffer-local-map
  15571. (copy-keymap org-read-date-minibuffer-local-map)))
  15572. (org-defkey map (kbd "RET") 'org-calendar-select)
  15573. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15574. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15575. (unwind-protect
  15576. (progn
  15577. (use-local-map map)
  15578. (setq org-read-date-inactive inactive)
  15579. (add-hook 'post-command-hook 'org-read-date-display)
  15580. (setq org-ans0
  15581. (read-string prompt
  15582. default-input
  15583. 'org-read-date-history
  15584. nil))
  15585. ;; org-ans0: from prompt
  15586. ;; org-ans1: from mouse click
  15587. ;; org-ans2: from calendar motion
  15588. (setq ans
  15589. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15590. (remove-hook 'post-command-hook 'org-read-date-display)
  15591. (use-local-map old-map)
  15592. (when org-read-date-overlay
  15593. (delete-overlay org-read-date-overlay)
  15594. (setq org-read-date-overlay nil)))))
  15595. (bury-buffer "*Calendar*")
  15596. (when cal-frame
  15597. (delete-frame cal-frame)
  15598. (select-frame-set-input-focus cur-frame))))))
  15599. (t ; Naked prompt only
  15600. (unwind-protect
  15601. (setq ans (read-string prompt default-input
  15602. 'org-read-date-history timestr))
  15603. (when org-read-date-overlay
  15604. (delete-overlay org-read-date-overlay)
  15605. (setq org-read-date-overlay nil))))))
  15606. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15607. (when org-read-date-analyze-forced-year
  15608. (message "Year was forced into %s"
  15609. (if org-read-date-force-compatible-dates
  15610. "compatible range (1970-2037)"
  15611. "range representable on this machine"))
  15612. (ding))
  15613. ;; One round trip to get rid of 34th of August and stuff like that....
  15614. (setq final (decode-time (apply 'encode-time final)))
  15615. (setq org-read-date-final-answer ans)
  15616. (if to-time
  15617. (apply 'encode-time final)
  15618. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15619. (format "%04d-%02d-%02d %02d:%02d"
  15620. (nth 5 final) (nth 4 final) (nth 3 final)
  15621. (nth 2 final) (nth 1 final))
  15622. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15623. (defun org-read-date-display ()
  15624. "Display the current date prompt interpretation in the minibuffer."
  15625. (when org-read-date-display-live
  15626. (when org-read-date-overlay
  15627. (delete-overlay org-read-date-overlay))
  15628. (when (minibufferp (current-buffer))
  15629. (save-excursion
  15630. (end-of-line 1)
  15631. (while (not (equal (buffer-substring
  15632. (max (point-min) (- (point) 4)) (point))
  15633. " "))
  15634. (insert " ")))
  15635. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15636. " " (or org-ans1 org-ans2)))
  15637. (org-end-time-was-given nil)
  15638. (f (org-read-date-analyze ans org-def org-defdecode))
  15639. (fmts (if org-dcst
  15640. org-time-stamp-custom-formats
  15641. org-time-stamp-formats))
  15642. (fmt (if (or org-with-time
  15643. (and (boundp 'org-time-was-given) org-time-was-given))
  15644. (cdr fmts)
  15645. (car fmts)))
  15646. (txt (format-time-string fmt (apply 'encode-time f)))
  15647. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15648. (txt (concat "=> " txt)))
  15649. (when (and org-end-time-was-given
  15650. (string-match org-plain-time-of-day-regexp txt))
  15651. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15652. org-end-time-was-given
  15653. (substring txt (match-end 0)))))
  15654. (when org-read-date-analyze-futurep
  15655. (setq txt (concat txt " (=>F)")))
  15656. (setq org-read-date-overlay
  15657. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15658. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15659. (defun org-read-date-analyze (ans def defdecode)
  15660. "Analyze the combined answer of the date prompt."
  15661. ;; FIXME: cleanup and comment
  15662. ;; Pass `current-time' result to `decode-time' (instead of calling
  15663. ;; without arguments) so that only `current-time' has to be
  15664. ;; overriden in tests.
  15665. (let ((org-def def)
  15666. (org-defdecode defdecode)
  15667. (nowdecode (decode-time (current-time)))
  15668. delta deltan deltaw deltadef year month day
  15669. hour minute second wday pm h2 m2 tl wday1
  15670. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15671. (setq org-read-date-analyze-futurep nil
  15672. org-read-date-analyze-forced-year nil)
  15673. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15674. (setq ans "+0"))
  15675. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15676. (setq ans (replace-match "" t t ans)
  15677. deltan (car delta)
  15678. deltaw (nth 1 delta)
  15679. deltadef (nth 2 delta)))
  15680. ;; Check if there is an iso week date in there. If yes, store the
  15681. ;; info and postpone interpreting it until the rest of the parsing
  15682. ;; is done.
  15683. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15684. (setq iso-year (when (match-end 1)
  15685. (org-small-year-to-year
  15686. (string-to-number (match-string 1 ans))))
  15687. iso-weekday (when (match-end 3)
  15688. (string-to-number (match-string 3 ans)))
  15689. iso-week (string-to-number (match-string 2 ans)))
  15690. (setq ans (replace-match "" t t ans)))
  15691. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15692. (when (string-match
  15693. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15694. (setq year (if (match-end 2)
  15695. (string-to-number (match-string 2 ans))
  15696. (progn (setq kill-year t)
  15697. (string-to-number (format-time-string "%Y"))))
  15698. month (string-to-number (match-string 3 ans))
  15699. day (string-to-number (match-string 4 ans)))
  15700. (setq year (org-small-year-to-year year))
  15701. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15702. t nil ans)))
  15703. ;; Help matching dotted european dates
  15704. (when (string-match
  15705. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15706. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15707. (setq kill-year t)
  15708. (string-to-number (format-time-string "%Y")))
  15709. day (string-to-number (match-string 1 ans))
  15710. month (string-to-number (match-string 2 ans))
  15711. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15712. t nil ans)))
  15713. ;; Help matching american dates, like 5/30 or 5/30/7
  15714. (when (string-match
  15715. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15716. (setq year (if (match-end 4)
  15717. (string-to-number (match-string 4 ans))
  15718. (progn (setq kill-year t)
  15719. (string-to-number (format-time-string "%Y"))))
  15720. month (string-to-number (match-string 1 ans))
  15721. day (string-to-number (match-string 2 ans)))
  15722. (setq year (org-small-year-to-year year))
  15723. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15724. t nil ans)))
  15725. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15726. ;; If there is a time with am/pm, and *no* time without it, we convert
  15727. ;; so that matching will be successful.
  15728. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15729. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15730. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15731. (setq hour (string-to-number (match-string 1 ans))
  15732. minute (if (match-end 3)
  15733. (string-to-number (match-string 3 ans))
  15734. 0)
  15735. pm (equal ?p
  15736. (string-to-char (downcase (match-string 4 ans)))))
  15737. (if (and (= hour 12) (not pm))
  15738. (setq hour 0)
  15739. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15740. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15741. t t ans))))
  15742. ;; Check if a time range is given as a duration
  15743. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15744. (setq hour (string-to-number (match-string 1 ans))
  15745. h2 (+ hour (string-to-number (match-string 3 ans)))
  15746. minute (string-to-number (match-string 2 ans))
  15747. m2 (+ minute (if (match-end 5) (string-to-number
  15748. (match-string 5 ans))0)))
  15749. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15750. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15751. t t ans)))
  15752. ;; Check if there is a time range
  15753. (when (boundp 'org-end-time-was-given)
  15754. (setq org-time-was-given nil)
  15755. (when (and (string-match org-plain-time-of-day-regexp ans)
  15756. (match-end 8))
  15757. (setq org-end-time-was-given (match-string 8 ans))
  15758. (setq ans (concat (substring ans 0 (match-beginning 7))
  15759. (substring ans (match-end 7))))))
  15760. (setq tl (parse-time-string ans)
  15761. day (or (nth 3 tl) (nth 3 org-defdecode))
  15762. month
  15763. (cond ((nth 4 tl))
  15764. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15765. ;; Day was specified. Make sure DAY+MONTH
  15766. ;; combination happens in the future.
  15767. ((nth 3 tl)
  15768. (setq futurep t)
  15769. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15770. (nth 4 nowdecode)))
  15771. (t (nth 4 org-defdecode)))
  15772. year
  15773. (cond ((and (not kill-year) (nth 5 tl)))
  15774. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15775. ;; Month was guessed in the future and is at least
  15776. ;; equal to NOWDECODE's. Fix year accordingly.
  15777. (futurep
  15778. (if (or (> month (nth 4 nowdecode))
  15779. (>= day (nth 3 nowdecode)))
  15780. (nth 5 nowdecode)
  15781. (1+ (nth 5 nowdecode))))
  15782. ;; Month was specified. Make sure MONTH+YEAR
  15783. ;; combination happens in the future.
  15784. ((nth 4 tl)
  15785. (setq futurep t)
  15786. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15787. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15788. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15789. (t (nth 5 nowdecode))))
  15790. (t (nth 5 org-defdecode)))
  15791. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15792. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15793. second (or (nth 0 tl) 0)
  15794. wday (nth 6 tl))
  15795. (when (and (eq org-read-date-prefer-future 'time)
  15796. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15797. (equal day (nth 3 nowdecode))
  15798. (equal month (nth 4 nowdecode))
  15799. (equal year (nth 5 nowdecode))
  15800. (nth 2 tl)
  15801. (or (< (nth 2 tl) (nth 2 nowdecode))
  15802. (and (= (nth 2 tl) (nth 2 nowdecode))
  15803. (nth 1 tl)
  15804. (< (nth 1 tl) (nth 1 nowdecode)))))
  15805. (setq day (1+ day)
  15806. futurep t))
  15807. ;; Special date definitions below
  15808. (cond
  15809. (iso-week
  15810. ;; There was an iso week
  15811. (require 'cal-iso)
  15812. (setq futurep nil)
  15813. (setq year (or iso-year year)
  15814. day (or iso-weekday wday 1)
  15815. wday nil ; to make sure that the trigger below does not match
  15816. iso-date (calendar-gregorian-from-absolute
  15817. (calendar-iso-to-absolute
  15818. (list iso-week day year))))
  15819. ; FIXME: Should we also push ISO weeks into the future?
  15820. ; (when (and org-read-date-prefer-future
  15821. ; (not iso-year)
  15822. ; (< (calendar-absolute-from-gregorian iso-date)
  15823. ; (time-to-days (current-time))))
  15824. ; (setq year (1+ year)
  15825. ; iso-date (calendar-gregorian-from-absolute
  15826. ; (calendar-iso-to-absolute
  15827. ; (list iso-week day year)))))
  15828. (setq month (car iso-date)
  15829. year (nth 2 iso-date)
  15830. day (nth 1 iso-date)))
  15831. (deltan
  15832. (setq futurep nil)
  15833. (unless deltadef
  15834. ;; Pass `current-time' result to `decode-time' (instead of
  15835. ;; calling without arguments) so that only `current-time' has
  15836. ;; to be overriden in tests.
  15837. (let ((now (decode-time (current-time))))
  15838. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15839. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15840. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15841. ((equal deltaw "m") (setq month (+ month deltan)))
  15842. ((equal deltaw "y") (setq year (+ year deltan)))))
  15843. ((and wday (not (nth 3 tl)))
  15844. ;; Weekday was given, but no day, so pick that day in the week
  15845. ;; on or after the derived date.
  15846. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15847. (unless (equal wday wday1)
  15848. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15849. (when (and (boundp 'org-time-was-given)
  15850. (nth 2 tl))
  15851. (setq org-time-was-given t))
  15852. (when (< year 100) (setq year (+ 2000 year)))
  15853. ;; Check of the date is representable
  15854. (if org-read-date-force-compatible-dates
  15855. (progn
  15856. (when (< year 1970)
  15857. (setq year 1970 org-read-date-analyze-forced-year t))
  15858. (when (> year 2037)
  15859. (setq year 2037 org-read-date-analyze-forced-year t)))
  15860. (condition-case nil
  15861. (ignore (encode-time second minute hour day month year))
  15862. (error
  15863. (setq year (nth 5 org-defdecode))
  15864. (setq org-read-date-analyze-forced-year t))))
  15865. (setq org-read-date-analyze-futurep futurep)
  15866. (list second minute hour day month year)))
  15867. (defvar parse-time-weekdays)
  15868. (defun org-read-date-get-relative (s today default)
  15869. "Check string S for special relative date string.
  15870. TODAY and DEFAULT are internal times, for today and for a default.
  15871. Return shift list (N what def-flag)
  15872. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15873. N is the number of WHATs to shift.
  15874. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15875. the DEFAULT date rather than TODAY."
  15876. (require 'parse-time)
  15877. (when (and
  15878. (string-match
  15879. (concat
  15880. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15881. "\\([0-9]+\\)?"
  15882. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15883. "\\([ \t]\\|$\\)") s)
  15884. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15885. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15886. (string-to-char (substring (match-string 1 s) -1))
  15887. ?+))
  15888. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15889. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15890. (what (if (match-end 3) (match-string 3 s) "d"))
  15891. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15892. (date (if rel default today))
  15893. (wday (nth 6 (decode-time date)))
  15894. delta)
  15895. (if wday1
  15896. (progn
  15897. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15898. (when (= delta 0) (setq delta 7))
  15899. (when (= dir ?-)
  15900. (setq delta (- delta 7))
  15901. (when (= delta 0) (setq delta -7)))
  15902. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15903. (list delta "d" rel))
  15904. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15905. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15906. "Turn a user-specified date into the internal representation.
  15907. The internal representation needed by the calendar is (month day year).
  15908. This is a wrapper to handle the brain-dead convention in calendar that
  15909. user function argument order change dependent on argument order."
  15910. (pcase calendar-date-style
  15911. (`american (list arg1 arg2 arg3))
  15912. (`european (list arg2 arg1 arg3))
  15913. (`iso (list arg2 arg3 arg1))))
  15914. (defun org-eval-in-calendar (form &optional keepdate)
  15915. "Eval FORM in the calendar window and return to current window.
  15916. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15917. (let ((sf (selected-frame))
  15918. (sw (selected-window)))
  15919. (select-window (get-buffer-window "*Calendar*" t))
  15920. (eval form)
  15921. (when (and (not keepdate) (calendar-cursor-to-date))
  15922. (let* ((date (calendar-cursor-to-date))
  15923. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15924. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15925. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15926. (select-window sw)
  15927. (select-frame-set-input-focus sf)))
  15928. (defun org-calendar-select ()
  15929. "Return to `org-read-date' with the date currently selected.
  15930. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15931. (interactive)
  15932. (when (calendar-cursor-to-date)
  15933. (let* ((date (calendar-cursor-to-date))
  15934. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15935. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15936. (when (active-minibuffer-window) (exit-minibuffer))))
  15937. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15938. "Insert a date stamp for the date given by the internal TIME.
  15939. See `format-time-string' for the format of TIME.
  15940. WITH-HM means use the stamp format that includes the time of the day.
  15941. INACTIVE means use square brackets instead of angular ones, so that the
  15942. stamp will not contribute to the agenda.
  15943. PRE and POST are optional strings to be inserted before and after the
  15944. stamp.
  15945. The command returns the inserted time stamp."
  15946. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15947. stamp)
  15948. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15949. (insert-before-markers (or pre ""))
  15950. (when (listp extra)
  15951. (setq extra (car extra))
  15952. (if (and (stringp extra)
  15953. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15954. (setq extra (format "-%02d:%02d"
  15955. (string-to-number (match-string 1 extra))
  15956. (string-to-number (match-string 2 extra))))
  15957. (setq extra nil)))
  15958. (when extra
  15959. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15960. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15961. (insert-before-markers (or post ""))
  15962. (setq org-last-inserted-timestamp stamp)))
  15963. (defun org-toggle-time-stamp-overlays ()
  15964. "Toggle the use of custom time stamp formats."
  15965. (interactive)
  15966. (setq org-display-custom-times (not org-display-custom-times))
  15967. (unless org-display-custom-times
  15968. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15969. (while (setq p (next-single-property-change p 'display))
  15970. (when (and (get-text-property p 'display)
  15971. (eq (get-text-property p 'face) 'org-date))
  15972. (remove-text-properties
  15973. p (setq p (next-single-property-change p 'display))
  15974. '(display t))))
  15975. (set-buffer-modified-p bmp)))
  15976. (org-restart-font-lock)
  15977. (setq org-table-may-need-update t)
  15978. (if org-display-custom-times
  15979. (message "Time stamps are overlaid with custom format")
  15980. (message "Time stamp overlays removed")))
  15981. (defun org-display-custom-time (beg end)
  15982. "Overlay modified time stamp format over timestamp between BEG and END."
  15983. (let* ((ts (buffer-substring beg end))
  15984. t1 w1 with-hm tf time str w2 (off 0))
  15985. (save-match-data
  15986. (setq t1 (org-parse-time-string ts t))
  15987. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15988. (setq off (- (match-end 0) (match-beginning 0)))))
  15989. (setq end (- end off))
  15990. (setq w1 (- end beg)
  15991. with-hm (and (nth 1 t1) (nth 2 t1))
  15992. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15993. time (org-fix-decoded-time t1)
  15994. str (org-add-props
  15995. (format-time-string
  15996. (substring tf 1 -1) (apply 'encode-time time))
  15997. nil 'mouse-face 'highlight)
  15998. w2 (length str))
  15999. (unless (= w2 w1)
  16000. (add-text-properties (1+ beg) (+ 2 beg)
  16001. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  16002. (put-text-property beg end 'display str)))
  16003. (defun org-fix-decoded-time (time)
  16004. "Set 0 instead of nil for the first 6 elements of time.
  16005. Don't touch the rest."
  16006. (let ((n 0))
  16007. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  16008. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  16009. "Difference between TIMESTAMP-STRING and now in days.
  16010. If SECONDS is non-nil, return the difference in seconds."
  16011. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  16012. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  16013. (funcall fdiff (current-time)))))
  16014. (defun org-deadline-close-p (timestamp-string &optional ndays)
  16015. "Is the time in TIMESTAMP-STRING close to the current date?"
  16016. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  16017. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  16018. (not (org-entry-is-done-p))))
  16019. (defun org-get-wdays (ts &optional delay zero-delay)
  16020. "Get the deadline lead time appropriate for timestring TS.
  16021. When DELAY is non-nil, get the delay time for scheduled items
  16022. instead of the deadline lead time. When ZERO-DELAY is non-nil
  16023. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  16024. don't try to find the delay cookie in the scheduled timestamp."
  16025. (let ((tv (if delay org-scheduled-delay-days
  16026. org-deadline-warning-days)))
  16027. (cond
  16028. ((or (and delay (< tv 0))
  16029. (and delay zero-delay (<= tv 0))
  16030. (and (not delay) (<= tv 0)))
  16031. ;; Enforce this value no matter what
  16032. (- tv))
  16033. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  16034. ;; lead time is specified.
  16035. (floor (* (string-to-number (match-string 1 ts))
  16036. (cdr (assoc (match-string 2 ts)
  16037. '(("d" . 1) ("w" . 7)
  16038. ("m" . 30.4) ("y" . 365.25)
  16039. ("h" . 0.041667)))))))
  16040. ;; go for the default.
  16041. (t tv))))
  16042. (defun org-calendar-select-mouse (ev)
  16043. "Return to `org-read-date' with the date currently selected.
  16044. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  16045. (interactive "e")
  16046. (mouse-set-point ev)
  16047. (when (calendar-cursor-to-date)
  16048. (let* ((date (calendar-cursor-to-date))
  16049. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  16050. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  16051. (when (active-minibuffer-window) (exit-minibuffer))))
  16052. (defun org-check-deadlines (ndays)
  16053. "Check if there are any deadlines due or past due.
  16054. A deadline is considered due if it happens within `org-deadline-warning-days'
  16055. days from today's date. If the deadline appears in an entry marked DONE,
  16056. it is not shown. A numeric prefix argument NDAYS can be used to test that
  16057. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  16058. are shown."
  16059. (interactive "P")
  16060. (let* ((org-warn-days
  16061. (cond
  16062. ((equal ndays '(4)) 100000)
  16063. (ndays (prefix-numeric-value ndays))
  16064. (t (abs org-deadline-warning-days))))
  16065. (case-fold-search nil)
  16066. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16067. (callback
  16068. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16069. (message "%d deadlines past-due or due within %d days"
  16070. (org-occur regexp nil callback)
  16071. org-warn-days)))
  16072. (defsubst org-re-timestamp (type)
  16073. "Return a regexp for timestamp TYPE.
  16074. Allowed values for TYPE are:
  16075. all: all timestamps
  16076. active: only active timestamps (<...>)
  16077. inactive: only inactive timestamps ([...])
  16078. scheduled: only scheduled timestamps
  16079. deadline: only deadline timestamps
  16080. closed: only closed time-stamps
  16081. When TYPE is nil, fall back on returning a regexp that matches
  16082. both scheduled and deadline timestamps."
  16083. (cl-case type
  16084. (all org-ts-regexp-both)
  16085. (active org-ts-regexp)
  16086. (inactive org-ts-regexp-inactive)
  16087. (scheduled org-scheduled-time-regexp)
  16088. (deadline org-deadline-time-regexp)
  16089. (closed org-closed-time-regexp)
  16090. (otherwise
  16091. (concat "\\<"
  16092. (regexp-opt (list org-deadline-string org-scheduled-string))
  16093. " *<\\([^>]+\\)>"))))
  16094. (defun org-check-before-date (d)
  16095. "Check if there are deadlines or scheduled entries before date D."
  16096. (interactive (list (org-read-date)))
  16097. (let* ((case-fold-search nil)
  16098. (regexp (org-re-timestamp org-ts-type))
  16099. (ts-type org-ts-type)
  16100. (callback
  16101. (lambda ()
  16102. (let ((match (match-string 1)))
  16103. (and (if (memq ts-type '(active inactive all))
  16104. (eq (org-element-type (save-excursion
  16105. (backward-char)
  16106. (org-element-context)))
  16107. 'timestamp)
  16108. (org-at-planning-p))
  16109. (time-less-p
  16110. (org-time-string-to-time match)
  16111. (org-time-string-to-time d)))))))
  16112. (message "%d entries before %s"
  16113. (org-occur regexp nil callback)
  16114. d)))
  16115. (defun org-check-after-date (d)
  16116. "Check if there are deadlines or scheduled entries after date D."
  16117. (interactive (list (org-read-date)))
  16118. (let* ((case-fold-search nil)
  16119. (regexp (org-re-timestamp org-ts-type))
  16120. (ts-type org-ts-type)
  16121. (callback
  16122. (lambda ()
  16123. (let ((match (match-string 1)))
  16124. (and (if (memq ts-type '(active inactive all))
  16125. (eq (org-element-type (save-excursion
  16126. (backward-char)
  16127. (org-element-context)))
  16128. 'timestamp)
  16129. (org-at-planning-p))
  16130. (not (time-less-p
  16131. (org-time-string-to-time match)
  16132. (org-time-string-to-time d))))))))
  16133. (message "%d entries after %s"
  16134. (org-occur regexp nil callback)
  16135. d)))
  16136. (defun org-check-dates-range (start-date end-date)
  16137. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16138. (interactive (list (org-read-date nil nil nil "Range starts")
  16139. (org-read-date nil nil nil "Range end")))
  16140. (let ((case-fold-search nil)
  16141. (regexp (org-re-timestamp org-ts-type))
  16142. (callback
  16143. (let ((type org-ts-type))
  16144. (lambda ()
  16145. (let ((match (match-string 1)))
  16146. (and
  16147. (if (memq type '(active inactive all))
  16148. (eq (org-element-type (save-excursion
  16149. (backward-char)
  16150. (org-element-context)))
  16151. 'timestamp)
  16152. (org-at-planning-p))
  16153. (not (time-less-p
  16154. (org-time-string-to-time match)
  16155. (org-time-string-to-time start-date)))
  16156. (time-less-p
  16157. (org-time-string-to-time match)
  16158. (org-time-string-to-time end-date))))))))
  16159. (message "%d entries between %s and %s"
  16160. (org-occur regexp nil callback) start-date end-date)))
  16161. (defun org-evaluate-time-range (&optional to-buffer)
  16162. "Evaluate a time range by computing the difference between start and end.
  16163. Normally the result is just printed in the echo area, but with prefix arg
  16164. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16165. If the time range is actually in a table, the result is inserted into the
  16166. next column.
  16167. For time difference computation, a year is assumed to be exactly 365
  16168. days in order to avoid rounding problems."
  16169. (interactive "P")
  16170. (or
  16171. (org-clock-update-time-maybe)
  16172. (save-excursion
  16173. (unless (org-at-date-range-p t)
  16174. (goto-char (point-at-bol))
  16175. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16176. (unless (org-at-date-range-p t)
  16177. (user-error "Not at a time-stamp range, and none found in current line")))
  16178. (let* ((ts1 (match-string 1))
  16179. (ts2 (match-string 2))
  16180. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16181. (match-end (match-end 0))
  16182. (time1 (org-time-string-to-time ts1))
  16183. (time2 (org-time-string-to-time ts2))
  16184. (t1 (float-time time1))
  16185. (t2 (float-time time2))
  16186. (diff (abs (- t2 t1)))
  16187. (negative (< (- t2 t1) 0))
  16188. ;; (ys (floor (* 365 24 60 60)))
  16189. (ds (* 24 60 60))
  16190. (hs (* 60 60))
  16191. (fy "%dy %dd %02d:%02d")
  16192. (fy1 "%dy %dd")
  16193. (fd "%dd %02d:%02d")
  16194. (fd1 "%dd")
  16195. (fh "%02d:%02d")
  16196. y d h m align)
  16197. (if havetime
  16198. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16199. y 0
  16200. d (floor (/ diff ds)) diff (mod diff ds)
  16201. h (floor (/ diff hs)) diff (mod diff hs)
  16202. m (floor (/ diff 60)))
  16203. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16204. y 0
  16205. d (floor (+ (/ diff ds) 0.5))
  16206. h 0 m 0))
  16207. (if (not to-buffer)
  16208. (message "%s" (org-make-tdiff-string y d h m))
  16209. (if (org-at-table-p)
  16210. (progn
  16211. (goto-char match-end)
  16212. (setq align t)
  16213. (and (looking-at " *|") (goto-char (match-end 0))))
  16214. (goto-char match-end))
  16215. (when (looking-at
  16216. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16217. (replace-match ""))
  16218. (when negative (insert " -"))
  16219. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16220. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16221. (insert " " (format fh h m))))
  16222. (when align (org-table-align))
  16223. (message "Time difference inserted")))))
  16224. (defun org-make-tdiff-string (y d h m)
  16225. (let ((fmt "")
  16226. (l nil))
  16227. (when (> y 0)
  16228. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16229. (push y l))
  16230. (when (> d 0)
  16231. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16232. (push d l))
  16233. (when (> h 0)
  16234. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16235. (push h l))
  16236. (when (> m 0)
  16237. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16238. (push m l))
  16239. (apply 'format fmt (nreverse l))))
  16240. (defun org-time-string-to-time (s &optional buffer pos)
  16241. "Convert a timestamp string into internal time."
  16242. (condition-case errdata
  16243. (apply 'encode-time (org-parse-time-string s))
  16244. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16245. s (if (not (and buffer pos))
  16246. ""
  16247. (format-message " at %d in buffer `%s'" pos buffer))
  16248. (cdr errdata)))))
  16249. (defun org-time-string-to-seconds (s)
  16250. "Convert a timestamp string to a number of seconds."
  16251. (float-time (org-time-string-to-time s)))
  16252. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16253. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16254. "Convert time stamp S to an absolute day number.
  16255. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16256. stamp, get the closest date to DAYNR. If PREFER is
  16257. `past' (respectively `future') return a date past (respectively
  16258. after) or equal to DAYNR.
  16259. POS is the location of time stamp S, as a buffer position in
  16260. BUFFER.
  16261. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16262. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16263. signalled."
  16264. (cond
  16265. ((string-match "\\`%%\\((.*)\\)" s)
  16266. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16267. ;; only able to match individual dates. If it fails, raise an
  16268. ;; error.
  16269. (if (and daynr
  16270. (org-diary-sexp-entry
  16271. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16272. daynr
  16273. (signal 'org-diary-sexp-no-match (list s))))
  16274. (daynr (org-closest-date s daynr prefer))
  16275. (t (time-to-days
  16276. (condition-case errdata
  16277. (apply #'encode-time (org-parse-time-string s))
  16278. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16279. s
  16280. (if (not (and buffer pos)) ""
  16281. (format-message " at %d in buffer `%s'" pos buffer))
  16282. (cdr errdata))))))))
  16283. (defun org-days-to-iso-week (days)
  16284. "Return the iso week number."
  16285. (require 'cal-iso)
  16286. (car (calendar-iso-from-absolute days)))
  16287. (defun org-small-year-to-year (year)
  16288. "Convert 2-digit years into 4-digit years.
  16289. YEAR is expanded into one of the 30 next years, if possible, or
  16290. into a past one. Any year larger than 99 is returned unchanged."
  16291. (if (>= year 100) year
  16292. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16293. (century (/ current 100))
  16294. (offset (- year (% current 100))))
  16295. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16296. ((> offset -70) (+ (* century 100) year))
  16297. (t (+ (* (1+ century) 100) year))))))
  16298. (defun org-time-from-absolute (d)
  16299. "Return the time corresponding to date D.
  16300. D may be an absolute day number, or a calendar-type list (month day year)."
  16301. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16302. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16303. (defvar org-agenda-current-date)
  16304. (defun org-calendar-holiday ()
  16305. "List of holidays, for Diary display in Org mode."
  16306. (require 'holidays)
  16307. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16308. (and hl (mapconcat #'identity hl "; "))))
  16309. (defun org-diary-sexp-entry (sexp entry d)
  16310. "Process a SEXP diary ENTRY for date D."
  16311. (require 'diary-lib)
  16312. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16313. ;; dynamically.
  16314. (let* ((sexp `(let ((entry ,entry)
  16315. (date ',d))
  16316. ,(car (read-from-string sexp))))
  16317. (result (if calendar-debug-sexp (eval sexp)
  16318. (condition-case nil
  16319. (eval sexp)
  16320. (error
  16321. (beep)
  16322. (message "Bad sexp at line %d in %s: %s"
  16323. (org-current-line)
  16324. (buffer-file-name) sexp)
  16325. (sleep-for 2))))))
  16326. (cond ((stringp result) (split-string result "; "))
  16327. ((and (consp result)
  16328. (not (consp (cdr result)))
  16329. (stringp (cdr result))) (cdr result))
  16330. ((and (consp result)
  16331. (stringp (car result))) result)
  16332. (result entry))))
  16333. (defun org-diary-to-ical-string (frombuf)
  16334. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16335. This uses the icalendar.el library."
  16336. (let* ((tmpdir temporary-file-directory)
  16337. (tmpfile (make-temp-name
  16338. (expand-file-name "orgics" tmpdir)))
  16339. buf rtn b e)
  16340. (with-current-buffer frombuf
  16341. (icalendar-export-region (point-min) (point-max) tmpfile)
  16342. (setq buf (find-buffer-visiting tmpfile))
  16343. (set-buffer buf)
  16344. (goto-char (point-min))
  16345. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16346. (setq b (match-beginning 0)))
  16347. (goto-char (point-max))
  16348. (when (re-search-backward "^END:VEVENT" nil t)
  16349. (setq e (match-end 0)))
  16350. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16351. (kill-buffer buf)
  16352. (delete-file tmpfile)
  16353. rtn))
  16354. (defun org-closest-date (start current prefer)
  16355. "Return closest date to CURRENT starting from START.
  16356. CURRENT and START are both time stamps.
  16357. When PREFER is `past', return a date that is either CURRENT or
  16358. past. When PREFER is `future', return a date that is either
  16359. CURRENT or future.
  16360. Only time stamps with a repeater are modified. Any other time
  16361. stamp stay unchanged. In any case, return value is an absolute
  16362. day number."
  16363. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16364. ;; No repeater. Do not shift time stamp.
  16365. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16366. (let ((value (string-to-number (match-string 1 start)))
  16367. (type (match-string 2 start)))
  16368. (if (= 0 value)
  16369. ;; Repeater with a 0-value is considered as void.
  16370. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16371. (let* ((base (org-date-to-gregorian start))
  16372. (target (org-date-to-gregorian current))
  16373. (sday (calendar-absolute-from-gregorian base))
  16374. (cday (calendar-absolute-from-gregorian target))
  16375. n1 n2)
  16376. ;; If START is already past CURRENT, just return START.
  16377. (if (<= cday sday) sday
  16378. ;; Compute closest date before (N1) and closest date past
  16379. ;; (N2) CURRENT.
  16380. (pcase type
  16381. ("h"
  16382. (let ((missing-hours
  16383. (mod (+ (- (* 24 (- cday sday))
  16384. (nth 2 (org-parse-time-string start)))
  16385. org-extend-today-until)
  16386. value)))
  16387. (setf n1 (if (= missing-hours 0) cday
  16388. (- cday (1+ (/ missing-hours 24)))))
  16389. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16390. ((or "d" "w")
  16391. (let ((value (if (equal type "w") (* 7 value) value)))
  16392. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16393. (setf n2 (+ n1 value))))
  16394. ("m"
  16395. (let* ((add-months
  16396. (lambda (d n)
  16397. ;; Add N months to gregorian date D, i.e.,
  16398. ;; a list (MONTH DAY YEAR). Return a valid
  16399. ;; gregorian date.
  16400. (let ((m (+ (nth 0 d) n)))
  16401. (list (mod m 12)
  16402. (nth 1 d)
  16403. (+ (/ m 12) (nth 2 d))))))
  16404. (months ; Complete months to TARGET.
  16405. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16406. (- (nth 0 target) (nth 0 base))
  16407. ;; If START's day is greater than
  16408. ;; TARGET's, remove incomplete month.
  16409. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16410. value)
  16411. value))
  16412. (before (funcall add-months base months)))
  16413. (setf n1 (calendar-absolute-from-gregorian before))
  16414. (setf n2
  16415. (calendar-absolute-from-gregorian
  16416. (funcall add-months before value)))))
  16417. (_
  16418. (let* ((d (nth 1 base))
  16419. (m (nth 0 base))
  16420. (y (nth 2 base))
  16421. (years ; Complete years to TARGET.
  16422. (* (/ (- (nth 2 target)
  16423. y
  16424. ;; If START's month and day are
  16425. ;; greater than TARGET's, remove
  16426. ;; incomplete year.
  16427. (if (or (> (nth 0 target) m)
  16428. (and (= (nth 0 target) m)
  16429. (> (nth 1 target) d)))
  16430. 0
  16431. 1))
  16432. value)
  16433. value))
  16434. (before (list m d (+ y years))))
  16435. (setf n1 (calendar-absolute-from-gregorian before))
  16436. (setf n2 (calendar-absolute-from-gregorian
  16437. (list m d (+ (nth 2 before) value)))))))
  16438. ;; Handle PREFER parameter, if any.
  16439. (cond
  16440. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16441. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16442. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16443. (defun org-date-to-gregorian (d)
  16444. "Turn any specification of date D into a Gregorian date for the calendar."
  16445. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16446. ((and (listp d) (= (length d) 3)) d)
  16447. ((stringp d)
  16448. (let ((d (org-parse-time-string d)))
  16449. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16450. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16451. (defun org-parse-time-string (s &optional nodefault)
  16452. "Parse the standard Org time string.
  16453. This should be a lot faster than the normal `parse-time-string'.
  16454. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16455. hour and minute fields will be nil if not given."
  16456. (cond ((string-match org-ts-regexp0 s)
  16457. (list 0
  16458. (when (or (match-beginning 8) (not nodefault))
  16459. (string-to-number (or (match-string 8 s) "0")))
  16460. (when (or (match-beginning 7) (not nodefault))
  16461. (string-to-number (or (match-string 7 s) "0")))
  16462. (string-to-number (match-string 4 s))
  16463. (string-to-number (match-string 3 s))
  16464. (string-to-number (match-string 2 s))
  16465. nil nil nil))
  16466. ((string-match "^<[^>]+>$" s)
  16467. (decode-time (seconds-to-time (org-matcher-time s))))
  16468. (t (error "Not a standard Org time string: %s" s))))
  16469. (defun org-timestamp-up (&optional arg)
  16470. "Increase the date item at the cursor by one.
  16471. If the cursor is on the year, change the year. If it is on the month,
  16472. the day or the time, change that.
  16473. With prefix ARG, change by that many units."
  16474. (interactive "p")
  16475. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16476. (defun org-timestamp-down (&optional arg)
  16477. "Decrease the date item at the cursor by one.
  16478. If the cursor is on the year, change the year. If it is on the month,
  16479. the day or the time, change that.
  16480. With prefix ARG, change by that many units."
  16481. (interactive "p")
  16482. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16483. (defun org-timestamp-up-day (&optional arg)
  16484. "Increase the date in the time stamp by one day.
  16485. With prefix ARG, change that many days."
  16486. (interactive "p")
  16487. (if (and (not (org-at-timestamp-p t))
  16488. (org-at-heading-p))
  16489. (org-todo 'up)
  16490. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16491. (defun org-timestamp-down-day (&optional arg)
  16492. "Decrease the date in the time stamp by one day.
  16493. With prefix ARG, change that many days."
  16494. (interactive "p")
  16495. (if (and (not (org-at-timestamp-p t))
  16496. (org-at-heading-p))
  16497. (org-todo 'down)
  16498. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16499. (defun org-at-timestamp-p (&optional inactive-ok)
  16500. "Non-nil if point is inside a timestamp.
  16501. When optional argument INACTIVE-OK is non-nil, also consider
  16502. inactive timestamps.
  16503. When this function returns a non-nil value, match data is set
  16504. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16505. INACTIVE-OK."
  16506. (interactive)
  16507. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16508. (pos (point))
  16509. (ans (or (looking-at tsr)
  16510. (save-excursion
  16511. (skip-chars-backward "^[<\n\r\t")
  16512. (when (> (point) (point-min)) (backward-char 1))
  16513. (and (looking-at tsr)
  16514. (> (- (match-end 0) pos) -1))))))
  16515. (and ans
  16516. (boundp 'org-ts-what)
  16517. (setq org-ts-what
  16518. (cond
  16519. ((= pos (match-beginning 0)) 'bracket)
  16520. ;; Point is considered to be "on the bracket" whether
  16521. ;; it's really on it or right after it.
  16522. ((= pos (1- (match-end 0))) 'bracket)
  16523. ((= pos (match-end 0)) 'after)
  16524. ((org-pos-in-match-range pos 2) 'year)
  16525. ((org-pos-in-match-range pos 3) 'month)
  16526. ((org-pos-in-match-range pos 7) 'hour)
  16527. ((org-pos-in-match-range pos 8) 'minute)
  16528. ((or (org-pos-in-match-range pos 4)
  16529. (org-pos-in-match-range pos 5)) 'day)
  16530. ((and (> pos (or (match-end 8) (match-end 5)))
  16531. (< pos (match-end 0)))
  16532. (- pos (or (match-end 8) (match-end 5))))
  16533. (t 'day))))
  16534. ans))
  16535. (defun org-toggle-timestamp-type ()
  16536. "Toggle the type (<active> or [inactive]) of a time stamp."
  16537. (interactive)
  16538. (when (org-at-timestamp-p t)
  16539. (let ((beg (match-beginning 0)) (end (match-end 0))
  16540. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16541. (save-excursion
  16542. (goto-char beg)
  16543. (while (re-search-forward "[][<>]" end t)
  16544. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16545. t t)))
  16546. (message "Timestamp is now %sactive"
  16547. (if (equal (char-after beg) ?<) "" "in")))))
  16548. (defun org-at-clock-log-p nil
  16549. "Is the cursor on the clock log line?"
  16550. (save-excursion
  16551. (beginning-of-line)
  16552. (looking-at org-clock-line-re)))
  16553. (defvar org-clock-history) ; defined in org-clock.el
  16554. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16555. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16556. "Change the date in the time stamp at point.
  16557. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16558. `year', `minute', `second'. If WHAT is not given, the cursor position
  16559. in the timestamp determines what will be changed.
  16560. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16561. (let ((origin (point)) origin-cat
  16562. with-hm inactive
  16563. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16564. org-ts-what
  16565. extra rem
  16566. ts time time0 fixnext clrgx)
  16567. (unless (org-at-timestamp-p t)
  16568. (user-error "Not at a timestamp"))
  16569. (if (and (not what) (eq org-ts-what 'bracket))
  16570. (org-toggle-timestamp-type)
  16571. ;; Point isn't on brackets. Remember the part of the time-stamp
  16572. ;; the point was in. Indeed, size of time-stamps may change,
  16573. ;; but point must be kept in the same category nonetheless.
  16574. (setq origin-cat org-ts-what)
  16575. (when (and (not what) (not (eq org-ts-what 'day))
  16576. org-display-custom-times
  16577. (get-text-property (point) 'display)
  16578. (not (get-text-property (1- (point)) 'display)))
  16579. (setq org-ts-what 'day))
  16580. (setq org-ts-what (or what org-ts-what)
  16581. inactive (= (char-after (match-beginning 0)) ?\[)
  16582. ts (match-string 0))
  16583. (replace-match "")
  16584. (when (string-match
  16585. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16586. ts)
  16587. (setq extra (match-string 1 ts))
  16588. (when suppress-tmp-delay
  16589. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16590. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16591. (setq with-hm t))
  16592. (setq time0 (org-parse-time-string ts))
  16593. (when (and updown
  16594. (eq org-ts-what 'minute)
  16595. (not current-prefix-arg))
  16596. ;; This looks like s-up and s-down. Change by one rounding step.
  16597. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16598. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16599. (setcar (cdr time0) (+ (nth 1 time0)
  16600. (if (> n 0) (- rem) (- dm rem))))))
  16601. (setq time
  16602. (apply #'encode-time
  16603. (or (car time0) 0)
  16604. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16605. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16606. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16607. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16608. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16609. (nthcdr 6 time0)))
  16610. (when (and (member org-ts-what '(hour minute))
  16611. extra
  16612. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16613. (setq extra (org-modify-ts-extra
  16614. extra
  16615. (if (eq org-ts-what 'hour) 2 5)
  16616. n dm)))
  16617. (when (integerp org-ts-what)
  16618. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16619. (when (eq what 'calendar)
  16620. (let ((cal-date (org-get-date-from-calendar)))
  16621. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16622. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16623. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16624. (setcar time0 (or (car time0) 0))
  16625. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16626. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16627. (setq time (apply 'encode-time time0))))
  16628. ;; Insert the new time-stamp, and ensure point stays in the same
  16629. ;; category as before (i.e. not after the last position in that
  16630. ;; category).
  16631. (let ((pos (point)))
  16632. ;; Stay before inserted string. `save-excursion' is of no use.
  16633. (setq org-last-changed-timestamp
  16634. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16635. (goto-char pos))
  16636. (save-match-data
  16637. (looking-at org-ts-regexp3)
  16638. (goto-char
  16639. (pcase origin-cat
  16640. ;; `day' category ends before `hour' if any, or at the end
  16641. ;; of the day name.
  16642. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16643. (`hour (min (match-end 7) origin))
  16644. (`minute (min (1- (match-end 8)) origin))
  16645. ((pred integerp) (min (1- (match-end 0)) origin))
  16646. ;; Point was right after the time-stamp. However, the
  16647. ;; time-stamp length might have changed, so refer to
  16648. ;; (match-end 0) instead.
  16649. (`after (match-end 0))
  16650. ;; `year' and `month' have both fixed size: point couldn't
  16651. ;; have moved into another part.
  16652. (_ origin))))
  16653. ;; Update clock if on a CLOCK line.
  16654. (org-clock-update-time-maybe)
  16655. ;; Maybe adjust the closest clock in `org-clock-history'
  16656. (when org-clock-adjust-closest
  16657. (if (not (and (org-at-clock-log-p)
  16658. (< 1 (length (delq nil (mapcar 'marker-position
  16659. org-clock-history))))))
  16660. (message "No clock to adjust")
  16661. (cond ((save-excursion ; fix previous clock?
  16662. (re-search-backward org-ts-regexp0 nil t)
  16663. (looking-back (concat org-clock-string " \\[")
  16664. (line-beginning-position)))
  16665. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16666. ((save-excursion ; fix next clock?
  16667. (re-search-backward org-ts-regexp0 nil t)
  16668. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16669. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16670. (save-window-excursion
  16671. ;; Find closest clock to point, adjust the previous/next one in history
  16672. (let* ((p (save-excursion (org-back-to-heading t)))
  16673. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16674. (clfixnth
  16675. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16676. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16677. (if (not clfixpos)
  16678. (message "No clock to adjust")
  16679. (save-excursion
  16680. (org-goto-marker-or-bmk clfixpos)
  16681. (org-show-subtree)
  16682. (when (re-search-forward clrgx nil t)
  16683. (goto-char (match-beginning 1))
  16684. (let (org-clock-adjust-closest)
  16685. (org-timestamp-change n org-ts-what updown))
  16686. (message "Clock adjusted in %s for heading: %s"
  16687. (file-name-nondirectory (buffer-file-name))
  16688. (org-get-heading t t)))))))))
  16689. ;; Try to recenter the calendar window, if any.
  16690. (when (and org-calendar-follow-timestamp-change
  16691. (get-buffer-window "*Calendar*" t)
  16692. (memq org-ts-what '(day month year)))
  16693. (org-recenter-calendar (time-to-days time))))))
  16694. (defun org-modify-ts-extra (s pos n dm)
  16695. "Change the different parts of the lead-time and repeat fields in timestamp."
  16696. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16697. ng h m new rem)
  16698. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16699. (cond
  16700. ((or (org-pos-in-match-range pos 2)
  16701. (org-pos-in-match-range pos 3))
  16702. (setq m (string-to-number (match-string 3 s))
  16703. h (string-to-number (match-string 2 s)))
  16704. (if (org-pos-in-match-range pos 2)
  16705. (setq h (+ h n))
  16706. (setq n (* dm (with-no-warnings (signum n))))
  16707. (unless (= 0 (setq rem (% m dm)))
  16708. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16709. (setq m (+ m n)))
  16710. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16711. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16712. (setq h (mod h 24))
  16713. (setq ng 1 new (format "-%02d:%02d" h m)))
  16714. ((org-pos-in-match-range pos 6)
  16715. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16716. ((org-pos-in-match-range pos 5)
  16717. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16718. ((org-pos-in-match-range pos 9)
  16719. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16720. ((org-pos-in-match-range pos 8)
  16721. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16722. (when ng
  16723. (setq s (concat
  16724. (substring s 0 (match-beginning ng))
  16725. new
  16726. (substring s (match-end ng))))))
  16727. s))
  16728. (defun org-recenter-calendar (d)
  16729. "If the calendar is visible, recenter it to date D."
  16730. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16731. (when cwin
  16732. (let ((calendar-move-hook nil))
  16733. (with-selected-window cwin
  16734. (calendar-goto-date
  16735. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16736. (defun org-goto-calendar (&optional arg)
  16737. "Go to the Emacs calendar at the current date.
  16738. If there is a time stamp in the current line, go to that date.
  16739. A prefix ARG can be used to force the current date."
  16740. (interactive "P")
  16741. (let ((tsr org-ts-regexp) diff
  16742. (calendar-move-hook nil)
  16743. (calendar-view-holidays-initially-flag nil)
  16744. (calendar-view-diary-initially-flag nil))
  16745. (when (or (org-at-timestamp-p)
  16746. (save-excursion
  16747. (beginning-of-line 1)
  16748. (looking-at (concat ".*" tsr))))
  16749. (let ((d1 (time-to-days (current-time)))
  16750. (d2 (time-to-days
  16751. (org-time-string-to-time (match-string 1)))))
  16752. (setq diff (- d2 d1))))
  16753. (calendar)
  16754. (calendar-goto-today)
  16755. (when (and diff (not arg)) (calendar-forward-day diff))))
  16756. (defun org-get-date-from-calendar ()
  16757. "Return a list (month day year) of date at point in calendar."
  16758. (with-current-buffer "*Calendar*"
  16759. (save-match-data
  16760. (calendar-cursor-to-date))))
  16761. (defun org-date-from-calendar ()
  16762. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16763. If there is already a time stamp at the cursor position, update it."
  16764. (interactive)
  16765. (if (org-at-timestamp-p t)
  16766. (org-timestamp-change 0 'calendar)
  16767. (let ((cal-date (org-get-date-from-calendar)))
  16768. (org-insert-time-stamp
  16769. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16770. (defcustom org-effort-durations
  16771. `(("min" . 1)
  16772. ("h" . 60)
  16773. ("d" . ,(* 60 8))
  16774. ("w" . ,(* 60 8 5))
  16775. ("m" . ,(* 60 8 5 4))
  16776. ("y" . ,(* 60 8 5 40)))
  16777. "Conversion factor to minutes for an effort modifier.
  16778. Each entry has the form (MODIFIER . MINUTES).
  16779. In an effort string, a number followed by MODIFIER is multiplied
  16780. by the specified number of MINUTES to obtain an effort in
  16781. minutes.
  16782. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16783. effort string \"2hours\" is equivalent to 120 minutes."
  16784. :group 'org-agenda
  16785. :version "26.1"
  16786. :package-version '(Org . "8.3")
  16787. :type '(alist :key-type (string :tag "Modifier")
  16788. :value-type (number :tag "Minutes")))
  16789. (defun org-minutes-to-clocksum-string (m)
  16790. "Format number of minutes as a clocksum string.
  16791. The format is determined by `org-time-clocksum-format',
  16792. `org-time-clocksum-use-fractional' and
  16793. `org-time-clocksum-fractional-format' and
  16794. `org-time-clocksum-use-effort-durations'."
  16795. (let ((clocksum "")
  16796. (m (round m)) ; Don't allow fractions of minutes
  16797. h d w mo y fmt n)
  16798. (setq h (if org-time-clocksum-use-effort-durations
  16799. (cdr (assoc "h" org-effort-durations)) 60)
  16800. d (if org-time-clocksum-use-effort-durations
  16801. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16802. w (if org-time-clocksum-use-effort-durations
  16803. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16804. mo (if org-time-clocksum-use-effort-durations
  16805. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16806. y (if org-time-clocksum-use-effort-durations
  16807. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16808. ;; fractional format
  16809. (if org-time-clocksum-use-fractional
  16810. (cond
  16811. ;; single format string
  16812. ((stringp org-time-clocksum-fractional-format)
  16813. (format org-time-clocksum-fractional-format (/ m (float h))))
  16814. ;; choice of fractional formats for different time units
  16815. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16816. (> (/ (truncate m) (* y d h)) 0))
  16817. (format fmt (/ m (* y d (float h)))))
  16818. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16819. (> (/ (truncate m) (* mo d h)) 0))
  16820. (format fmt (/ m (* mo d (float h)))))
  16821. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16822. (> (/ (truncate m) (* w d h)) 0))
  16823. (format fmt (/ m (* w d (float h)))))
  16824. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16825. (> (/ (truncate m) (* d h)) 0))
  16826. (format fmt (/ m (* d (float h)))))
  16827. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16828. (> (/ (truncate m) h) 0))
  16829. (format fmt (/ m (float h))))
  16830. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16831. (format fmt m))
  16832. ;; fall back to smallest time unit with a format
  16833. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16834. (format fmt (/ m (float h))))
  16835. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16836. (format fmt (/ m (* d (float h)))))
  16837. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16838. (format fmt (/ m (* w d (float h)))))
  16839. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16840. (format fmt (/ m (* mo d (float h)))))
  16841. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16842. (format fmt (/ m (* y d (float h))))))
  16843. ;; standard (non-fractional) format, with single format string
  16844. (if (stringp org-time-clocksum-format)
  16845. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16846. ;; separate formats components
  16847. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16848. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16849. (plist-get org-time-clocksum-format :require-years))
  16850. (setq clocksum (concat clocksum (format fmt n))
  16851. m (- m (* n y d h))))
  16852. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16853. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16854. (plist-get org-time-clocksum-format :require-months))
  16855. (setq clocksum (concat clocksum (format fmt n))
  16856. m (- m (* n mo d h))))
  16857. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16858. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16859. (plist-get org-time-clocksum-format :require-weeks))
  16860. (setq clocksum (concat clocksum (format fmt n))
  16861. m (- m (* n w d h))))
  16862. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16863. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16864. (plist-get org-time-clocksum-format :require-days))
  16865. (setq clocksum (concat clocksum (format fmt n))
  16866. m (- m (* n d h))))
  16867. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16868. (or (> (setq n (/ (truncate m) h)) 0)
  16869. (plist-get org-time-clocksum-format :require-hours))
  16870. (setq clocksum (concat clocksum (format fmt n))
  16871. m (- m (* n h))))
  16872. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16873. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16874. (setq clocksum (concat clocksum (format fmt m))))
  16875. ;; return formatted time duration
  16876. clocksum))))
  16877. (defun org-hours-to-clocksum-string (n)
  16878. (org-minutes-to-clocksum-string (* n 60)))
  16879. (defun org-hh:mm-string-to-minutes (s)
  16880. "Convert a string H:MM to a number of minutes.
  16881. If the string is just a number, interpret it as minutes.
  16882. In fact, the first hh:mm or number in the string will be taken,
  16883. there can be extra stuff in the string.
  16884. If no number is found, the return value is 0."
  16885. (cond
  16886. ((integerp s) s)
  16887. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16888. (+ (* (string-to-number (match-string 1 s)) 60)
  16889. (string-to-number (match-string 2 s))))
  16890. ((string-match "\\([0-9]+\\)" s)
  16891. (string-to-number (match-string 1 s)))
  16892. (t 0)))
  16893. (defcustom org-image-actual-width t
  16894. "Should we use the actual width of images when inlining them?
  16895. When set to t, always use the image width.
  16896. When set to a number, use imagemagick (when available) to set
  16897. the image's width to this value.
  16898. When set to a number in a list, try to get the width from any
  16899. #+ATTR.* keyword if it matches a width specification like
  16900. #+ATTR_HTML: :width 300px
  16901. and fall back on that number if none is found.
  16902. When set to nil, try to get the width from an #+ATTR.* keyword
  16903. and fall back on the original width if none is found.
  16904. This requires Emacs >= 24.1, build with imagemagick support."
  16905. :group 'org-appearance
  16906. :version "24.4"
  16907. :package-version '(Org . "8.0")
  16908. :type '(choice
  16909. (const :tag "Use the image width" t)
  16910. (integer :tag "Use a number of pixels")
  16911. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16912. (const :tag "Use #+ATTR* or don't resize" nil)))
  16913. (defcustom org-agenda-inhibit-startup nil
  16914. "Inhibit startup when preparing agenda buffers.
  16915. When this variable is t, the initialization of the Org agenda
  16916. buffers is inhibited: e.g. the visibility state is not set, the
  16917. tables are not re-aligned, etc."
  16918. :type 'boolean
  16919. :version "24.3"
  16920. :group 'org-agenda)
  16921. (defcustom org-agenda-ignore-properties nil
  16922. "Avoid updating text properties when building the agenda.
  16923. Properties are used to prepare buffers for effort estimates,
  16924. appointments, statistics and subtree-local categories.
  16925. If you don't use these in the agenda, you can add them to this
  16926. list and agenda building will be a bit faster.
  16927. The value is a list, with zero or more of the symbols `effort', `appt',
  16928. `stats' or `category'."
  16929. :type '(set :greedy t
  16930. (const effort)
  16931. (const appt)
  16932. (const stats)
  16933. (const category))
  16934. :version "26.1"
  16935. :package-version '(Org . "8.3")
  16936. :group 'org-agenda)
  16937. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16938. "Convert a duration string S to minutes.
  16939. A bare number is interpreted as minutes, modifiers can be set by
  16940. customizing `org-effort-durations' (which see).
  16941. Entries containing a colon are interpreted as H:MM by
  16942. `org-hh:mm-string-to-minutes'."
  16943. (let ((result 0)
  16944. (re (concat "\\([0-9.]+\\) *\\("
  16945. (regexp-opt (mapcar 'car org-effort-durations))
  16946. "\\)")))
  16947. (while (string-match re s)
  16948. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16949. (string-to-number (match-string 1 s))))
  16950. (setq s (replace-match "" nil t s)))
  16951. (setq result (floor result))
  16952. (cl-incf result (org-hh:mm-string-to-minutes s))
  16953. (if output-to-string (number-to-string result) result)))
  16954. ;;;; Files
  16955. (defun org-save-all-org-buffers ()
  16956. "Save all Org buffers without user confirmation."
  16957. (interactive)
  16958. (message "Saving all Org buffers...")
  16959. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16960. (when (featurep 'org-id) (org-id-locations-save))
  16961. (message "Saving all Org buffers... done"))
  16962. (defun org-revert-all-org-buffers ()
  16963. "Revert all Org buffers.
  16964. Prompt for confirmation when there are unsaved changes.
  16965. Be sure you know what you are doing before letting this function
  16966. overwrite your changes.
  16967. This function is useful in a setup where one tracks org files
  16968. with a version control system, to revert on one machine after pulling
  16969. changes from another. I believe the procedure must be like this:
  16970. 1. M-x org-save-all-org-buffers
  16971. 2. Pull changes from the other machine, resolve conflicts
  16972. 3. M-x org-revert-all-org-buffers"
  16973. (interactive)
  16974. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16975. (user-error "Abort"))
  16976. (save-excursion
  16977. (save-window-excursion
  16978. (dolist (b (buffer-list))
  16979. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16980. (with-current-buffer b buffer-file-name))
  16981. (pop-to-buffer-same-window b)
  16982. (revert-buffer t 'no-confirm)))
  16983. (when (and (featurep 'org-id) org-id-track-globally)
  16984. (org-id-locations-load)))))
  16985. ;;;; Agenda files
  16986. ;;;###autoload
  16987. (defun org-switchb (&optional arg)
  16988. "Switch between Org buffers.
  16989. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16990. With `\\[universal-argument] \\[universal-argument]' \
  16991. prefix, restrict available buffers to agenda files."
  16992. (interactive "P")
  16993. (let ((blist (org-buffer-list
  16994. (cond ((equal arg '(4)) 'files)
  16995. ((equal arg '(16)) 'agenda)))))
  16996. (pop-to-buffer-same-window
  16997. (completing-read "Org buffer: "
  16998. (mapcar #'list (mapcar #'buffer-name blist))
  16999. nil t))))
  17000. (defun org-buffer-list (&optional predicate exclude-tmp)
  17001. "Return a list of Org buffers.
  17002. PREDICATE can be `export', `files' or `agenda'.
  17003. export restrict the list to Export buffers.
  17004. files restrict the list to buffers visiting Org files.
  17005. agenda restrict the list to buffers visiting agenda files.
  17006. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  17007. (let* ((bfn nil)
  17008. (agenda-files (and (eq predicate 'agenda)
  17009. (mapcar 'file-truename (org-agenda-files t))))
  17010. (filter
  17011. (cond
  17012. ((eq predicate 'files)
  17013. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  17014. ((eq predicate 'export)
  17015. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  17016. ((eq predicate 'agenda)
  17017. (lambda (b)
  17018. (with-current-buffer b
  17019. (and (derived-mode-p 'org-mode)
  17020. (setq bfn (buffer-file-name b))
  17021. (member (file-truename bfn) agenda-files)))))
  17022. (t (lambda (b) (with-current-buffer b
  17023. (or (derived-mode-p 'org-mode)
  17024. (string-match "\\*Org .*Export"
  17025. (buffer-name b)))))))))
  17026. (delq nil
  17027. (mapcar
  17028. (lambda(b)
  17029. (if (and (funcall filter b)
  17030. (or (not exclude-tmp)
  17031. (not (string-match "tmp" (buffer-name b)))))
  17032. b
  17033. nil))
  17034. (buffer-list)))))
  17035. (defun org-agenda-files (&optional unrestricted archives)
  17036. "Get the list of agenda files.
  17037. Optional UNRESTRICTED means return the full list even if a restriction
  17038. is currently in place.
  17039. When ARCHIVES is t, include all archive files that are really being
  17040. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  17041. `org-agenda-archives-mode' is t."
  17042. (let ((files
  17043. (cond
  17044. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  17045. ((stringp org-agenda-files) (org-read-agenda-file-list))
  17046. ((listp org-agenda-files) org-agenda-files)
  17047. (t (error "Invalid value of `org-agenda-files'")))))
  17048. (setq files (apply 'append
  17049. (mapcar (lambda (f)
  17050. (if (file-directory-p f)
  17051. (directory-files
  17052. f t org-agenda-file-regexp)
  17053. (list f)))
  17054. files)))
  17055. (when org-agenda-skip-unavailable-files
  17056. (setq files (delq nil
  17057. (mapcar (function
  17058. (lambda (file)
  17059. (and (file-readable-p file) file)))
  17060. files))))
  17061. (when (or (eq archives t)
  17062. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17063. (setq files (org-add-archive-files files)))
  17064. files))
  17065. (defun org-agenda-file-p (&optional file)
  17066. "Return non-nil, if FILE is an agenda file.
  17067. If FILE is omitted, use the file associated with the current
  17068. buffer."
  17069. (let ((fname (or file (buffer-file-name))))
  17070. (and fname
  17071. (member (file-truename fname)
  17072. (mapcar #'file-truename (org-agenda-files t))))))
  17073. (defun org-edit-agenda-file-list ()
  17074. "Edit the list of agenda files.
  17075. Depending on setup, this either uses customize to edit the variable
  17076. `org-agenda-files', or it visits the file that is holding the list. In the
  17077. latter case, the buffer is set up in a way that saving it automatically kills
  17078. the buffer and restores the previous window configuration."
  17079. (interactive)
  17080. (if (stringp org-agenda-files)
  17081. (let ((cw (current-window-configuration)))
  17082. (find-file org-agenda-files)
  17083. (setq-local org-window-configuration cw)
  17084. (add-hook 'after-save-hook
  17085. (lambda ()
  17086. (set-window-configuration
  17087. (prog1 org-window-configuration
  17088. (kill-buffer (current-buffer))))
  17089. (org-install-agenda-files-menu)
  17090. (message "New agenda file list installed"))
  17091. nil 'local)
  17092. (message "%s" (substitute-command-keys
  17093. "Edit list and finish with \\[save-buffer]")))
  17094. (customize-variable 'org-agenda-files)))
  17095. (defun org-store-new-agenda-file-list (list)
  17096. "Set new value for the agenda file list and save it correctly."
  17097. (if (stringp org-agenda-files)
  17098. (let ((fe (org-read-agenda-file-list t)) b u)
  17099. (while (setq b (find-buffer-visiting org-agenda-files))
  17100. (kill-buffer b))
  17101. (with-temp-file org-agenda-files
  17102. (insert
  17103. (mapconcat
  17104. (lambda (f) ;; Keep un-expanded entries.
  17105. (if (setq u (assoc f fe))
  17106. (cdr u)
  17107. f))
  17108. list "\n")
  17109. "\n")))
  17110. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17111. (org-insert-mode-line-in-empty-file nil))
  17112. (setq org-agenda-files list)
  17113. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17114. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17115. "Read the list of agenda files from a file.
  17116. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17117. filenames, used by `org-store-new-agenda-file-list' to write back
  17118. un-expanded file names."
  17119. (when (file-directory-p org-agenda-files)
  17120. (error "`org-agenda-files' cannot be a single directory"))
  17121. (when (stringp org-agenda-files)
  17122. (with-temp-buffer
  17123. (insert-file-contents org-agenda-files)
  17124. (mapcar
  17125. (lambda (f)
  17126. (let ((e (expand-file-name (substitute-in-file-name f)
  17127. org-directory)))
  17128. (if pair-with-expansion
  17129. (cons e f)
  17130. e)))
  17131. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17132. ;;;###autoload
  17133. (defun org-cycle-agenda-files ()
  17134. "Cycle through the files in `org-agenda-files'.
  17135. If the current buffer visits an agenda file, find the next one in the list.
  17136. If the current buffer does not, find the first agenda file."
  17137. (interactive)
  17138. (let* ((fs (or (org-agenda-files t)
  17139. (user-error "No agenda files")))
  17140. (files (copy-sequence fs))
  17141. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17142. file)
  17143. (when tcf
  17144. (while (and (setq file (pop files))
  17145. (not (equal (file-truename file) tcf)))))
  17146. (find-file (car (or files fs)))
  17147. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17148. (defun org-agenda-file-to-front (&optional to-end)
  17149. "Move/add the current file to the top of the agenda file list.
  17150. If the file is not present in the list, it is added to the front. If it is
  17151. present, it is moved there. With optional argument TO-END, add/move to the
  17152. end of the list."
  17153. (interactive "P")
  17154. (let ((org-agenda-skip-unavailable-files nil)
  17155. (file-alist (mapcar (lambda (x)
  17156. (cons (file-truename x) x))
  17157. (org-agenda-files t)))
  17158. (ctf (file-truename
  17159. (or buffer-file-name
  17160. (user-error "Please save the current buffer to a file"))))
  17161. x had)
  17162. (setq x (assoc ctf file-alist) had x)
  17163. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17164. (if to-end
  17165. (setq file-alist (append (delq x file-alist) (list x)))
  17166. (setq file-alist (cons x (delq x file-alist))))
  17167. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17168. (org-install-agenda-files-menu)
  17169. (message "File %s to %s of agenda file list"
  17170. (if had "moved" "added") (if to-end "end" "front"))))
  17171. (defun org-remove-file (&optional file)
  17172. "Remove current file from the list of files in variable `org-agenda-files'.
  17173. These are the files which are being checked for agenda entries.
  17174. Optional argument FILE means use this file instead of the current."
  17175. (interactive)
  17176. (let* ((org-agenda-skip-unavailable-files nil)
  17177. (file (or file buffer-file-name
  17178. (user-error "Current buffer does not visit a file")))
  17179. (true-file (file-truename file))
  17180. (afile (abbreviate-file-name file))
  17181. (files (delq nil (mapcar
  17182. (lambda (x)
  17183. (unless (equal true-file
  17184. (file-truename x))
  17185. x))
  17186. (org-agenda-files t)))))
  17187. (if (not (= (length files) (length (org-agenda-files t))))
  17188. (progn
  17189. (org-store-new-agenda-file-list files)
  17190. (org-install-agenda-files-menu)
  17191. (message "Removed from Org Agenda list: %s" afile))
  17192. (message "File was not in list: %s (not removed)" afile))))
  17193. (defun org-file-menu-entry (file)
  17194. (vector file (list 'find-file file) t))
  17195. (defun org-check-agenda-file (file)
  17196. "Make sure FILE exists. If not, ask user what to do."
  17197. (unless (file-exists-p file)
  17198. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17199. (abbreviate-file-name file))
  17200. (let ((r (downcase (read-char-exclusive))))
  17201. (cond
  17202. ((equal r ?r)
  17203. (org-remove-file file)
  17204. (throw 'nextfile t))
  17205. (t (user-error "Abort"))))))
  17206. (defun org-get-agenda-file-buffer (file)
  17207. "Get an agenda buffer visiting FILE.
  17208. If the buffer needs to be created, add it to the list of buffers
  17209. which might be released later."
  17210. (let ((buf (org-find-base-buffer-visiting file)))
  17211. (if buf
  17212. buf ; just return it
  17213. ;; Make a new buffer and remember it
  17214. (setq buf (find-file-noselect file))
  17215. (when buf (push buf org-agenda-new-buffers))
  17216. buf)))
  17217. (defun org-release-buffers (blist)
  17218. "Release all buffers in list, asking the user for confirmation when needed.
  17219. When a buffer is unmodified, it is just killed. When modified, it is saved
  17220. \(if the user agrees) and then killed."
  17221. (let (file)
  17222. (dolist (buf blist)
  17223. (setq file (buffer-file-name buf))
  17224. (when (and (buffer-modified-p buf)
  17225. file
  17226. (y-or-n-p (format "Save file %s? " file)))
  17227. (with-current-buffer buf (save-buffer)))
  17228. (kill-buffer buf))))
  17229. (defun org-agenda-prepare-buffers (files)
  17230. "Create buffers for all agenda files, protect archived trees and comments."
  17231. (interactive)
  17232. (let ((pa '(:org-archived t))
  17233. (pc '(:org-comment t))
  17234. (pall '(:org-archived t :org-comment t))
  17235. (inhibit-read-only t)
  17236. (org-inhibit-startup org-agenda-inhibit-startup)
  17237. (rea (concat ":" org-archive-tag ":"))
  17238. re pos)
  17239. (setq org-tag-alist-for-agenda nil
  17240. org-tag-groups-alist-for-agenda nil)
  17241. (save-excursion
  17242. (save-restriction
  17243. (dolist (file files)
  17244. (catch 'nextfile
  17245. (if (bufferp file)
  17246. (set-buffer file)
  17247. (org-check-agenda-file file)
  17248. (set-buffer (org-get-agenda-file-buffer file)))
  17249. (widen)
  17250. (org-set-regexps-and-options 'tags-only)
  17251. (setq pos (point))
  17252. (or (memq 'category org-agenda-ignore-properties)
  17253. (org-refresh-category-properties))
  17254. (or (memq 'stats org-agenda-ignore-properties)
  17255. (org-refresh-stats-properties))
  17256. (or (memq 'effort org-agenda-ignore-properties)
  17257. (org-refresh-effort-properties))
  17258. (or (memq 'appt org-agenda-ignore-properties)
  17259. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17260. (setq org-todo-keywords-for-agenda
  17261. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17262. (setq org-done-keywords-for-agenda
  17263. (append org-done-keywords-for-agenda org-done-keywords))
  17264. (setq org-todo-keyword-alist-for-agenda
  17265. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17266. (setq org-tag-alist-for-agenda
  17267. (org-uniquify
  17268. (append org-tag-alist-for-agenda
  17269. org-current-tag-alist)))
  17270. ;; Merge current file's tag groups into global
  17271. ;; `org-tag-groups-alist-for-agenda'.
  17272. (when org-group-tags
  17273. (dolist (alist org-tag-groups-alist)
  17274. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17275. (if old
  17276. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17277. (push alist org-tag-groups-alist-for-agenda)))))
  17278. (org-with-silent-modifications
  17279. (save-excursion
  17280. (remove-text-properties (point-min) (point-max) pall)
  17281. (when org-agenda-skip-archived-trees
  17282. (goto-char (point-min))
  17283. (while (re-search-forward rea nil t)
  17284. (when (org-at-heading-p t)
  17285. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17286. (goto-char (point-min))
  17287. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17288. (while (re-search-forward re nil t)
  17289. (when (save-match-data (org-in-commented-heading-p t))
  17290. (add-text-properties
  17291. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17292. (goto-char pos)))))
  17293. (setq org-todo-keywords-for-agenda
  17294. (org-uniquify org-todo-keywords-for-agenda))
  17295. (setq org-todo-keyword-alist-for-agenda
  17296. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17297. ;;;; CDLaTeX minor mode
  17298. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17299. "Keymap for the minor `org-cdlatex-mode'.")
  17300. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17301. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17302. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17303. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17304. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17305. (defvar org-cdlatex-texmathp-advice-is-done nil
  17306. "Flag remembering if we have applied the advice to texmathp already.")
  17307. (define-minor-mode org-cdlatex-mode
  17308. "Toggle the minor `org-cdlatex-mode'.
  17309. This mode supports entering LaTeX environment and math in LaTeX fragments
  17310. in Org mode.
  17311. \\{org-cdlatex-mode-map}"
  17312. nil " OCDL" nil
  17313. (when org-cdlatex-mode
  17314. (require 'cdlatex)
  17315. (run-hooks 'cdlatex-mode-hook)
  17316. (cdlatex-compute-tables))
  17317. (unless org-cdlatex-texmathp-advice-is-done
  17318. (setq org-cdlatex-texmathp-advice-is-done t)
  17319. (defadvice texmathp (around org-math-always-on activate)
  17320. "Always return t in Org buffers.
  17321. This is because we want to insert math symbols without dollars even outside
  17322. the LaTeX math segments. If Org mode thinks that point is actually inside
  17323. an embedded LaTeX fragment, let `texmathp' do its job.
  17324. `\\[org-cdlatex-mode-map]'"
  17325. (interactive)
  17326. (let (p)
  17327. (cond
  17328. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17329. ((eq this-command 'cdlatex-math-symbol)
  17330. (setq ad-return-value t
  17331. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17332. (t
  17333. (let ((p (org-inside-LaTeX-fragment-p)))
  17334. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17335. (setq ad-return-value t
  17336. texmathp-why '("Org mode embedded math" . 0))
  17337. (when p ad-do-it)))))))))
  17338. (defun turn-on-org-cdlatex ()
  17339. "Unconditionally turn on `org-cdlatex-mode'."
  17340. (org-cdlatex-mode 1))
  17341. (defun org-try-cdlatex-tab ()
  17342. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17343. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17344. - inside a LaTeX fragment, or
  17345. - after the first word in a line, where an abbreviation expansion could
  17346. insert a LaTeX environment."
  17347. (when org-cdlatex-mode
  17348. (cond
  17349. ;; Before any word on the line: No expansion possible.
  17350. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17351. ;; Just after first word on the line: Expand it. Make sure it
  17352. ;; cannot happen on headlines, though.
  17353. ((save-excursion
  17354. (skip-chars-backward "a-zA-Z0-9*")
  17355. (skip-chars-backward " \t")
  17356. (and (bolp) (not (org-at-heading-p))))
  17357. (cdlatex-tab) t)
  17358. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17359. (defun org-cdlatex-underscore-caret (&optional _arg)
  17360. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17361. Revert to the normal definition outside of these fragments."
  17362. (interactive "P")
  17363. (if (org-inside-LaTeX-fragment-p)
  17364. (call-interactively 'cdlatex-sub-superscript)
  17365. (let (org-cdlatex-mode)
  17366. (call-interactively (key-binding (vector last-input-event))))))
  17367. (defun org-cdlatex-math-modify (&optional _arg)
  17368. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17369. Revert to the normal definition outside of these fragments."
  17370. (interactive "P")
  17371. (if (org-inside-LaTeX-fragment-p)
  17372. (call-interactively 'cdlatex-math-modify)
  17373. (let (org-cdlatex-mode)
  17374. (call-interactively (key-binding (vector last-input-event))))))
  17375. (defun org-cdlatex-environment-indent (&optional environment item)
  17376. "Execute `cdlatex-environment' and indent the inserted environment.
  17377. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17378. The inserted environment is indented to current indentation
  17379. unless point is at the beginning of the line, in which the
  17380. environment remains unintended."
  17381. (interactive)
  17382. ;; cdlatex-environment always return nil. Therefore, capture output
  17383. ;; first and determine if an environment was selected.
  17384. (let* ((beg (point-marker))
  17385. (end (copy-marker (point) t))
  17386. (inserted (progn
  17387. (ignore-errors (cdlatex-environment environment item))
  17388. (< beg end)))
  17389. ;; Figure out how many lines to move forward after the
  17390. ;; environment has been inserted.
  17391. (lines (when inserted
  17392. (save-excursion
  17393. (- (cl-loop while (< beg (point))
  17394. with x = 0
  17395. do (forward-line -1)
  17396. (cl-incf x)
  17397. finally return x)
  17398. (if (progn (goto-char beg)
  17399. (and (progn (skip-chars-forward " \t") (eolp))
  17400. (progn (skip-chars-backward " \t") (bolp))))
  17401. 1 0)))))
  17402. (env (org-trim (delete-and-extract-region beg end))))
  17403. (when inserted
  17404. ;; Get indentation of next line unless at column 0.
  17405. (let ((ind (if (bolp) 0
  17406. (save-excursion
  17407. (org-return-indent)
  17408. (prog1 (org-get-indentation)
  17409. (when (progn (skip-chars-forward " \t") (eolp))
  17410. (delete-region beg (point)))))))
  17411. (bol (progn (skip-chars-backward " \t") (bolp))))
  17412. ;; Insert a newline before environment unless at column zero
  17413. ;; to "escape" the current line. Insert a newline if
  17414. ;; something is one the same line as \end{ENVIRONMENT}.
  17415. (insert
  17416. (concat (unless bol "\n") env
  17417. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17418. (unless (zerop ind)
  17419. (save-excursion
  17420. (goto-char beg)
  17421. (while (< (point) end)
  17422. (unless (eolp) (indent-line-to ind))
  17423. (forward-line))))
  17424. (goto-char beg)
  17425. (forward-line lines)
  17426. (indent-line-to ind)))
  17427. (set-marker beg nil)
  17428. (set-marker end nil)))
  17429. ;;;; LaTeX fragments
  17430. (defun org-inside-LaTeX-fragment-p ()
  17431. "Test if point is inside a LaTeX fragment.
  17432. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17433. sequence appearing also before point.
  17434. Even though the matchers for math are configurable, this function assumes
  17435. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17436. delimiters are skipped when they have been removed by customization.
  17437. The return value is nil, or a cons cell with the delimiter and the
  17438. position of this delimiter.
  17439. This function does a reasonably good job, but can locally be fooled by
  17440. for example currency specifications. For example it will assume being in
  17441. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17442. fragments that are properly closed, but during editing, we have to live
  17443. with the uncertainty caused by missing closing delimiters. This function
  17444. looks only before point, not after."
  17445. (catch 'exit
  17446. (let ((pos (point))
  17447. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17448. (lim (progn
  17449. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17450. (point)))
  17451. dd-on str (start 0) m re)
  17452. (goto-char pos)
  17453. (when dodollar
  17454. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17455. re (nth 1 (assoc "$" org-latex-regexps)))
  17456. (while (string-match re str start)
  17457. (cond
  17458. ((= (match-end 0) (length str))
  17459. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17460. ((= (match-end 0) (- (length str) 5))
  17461. (throw 'exit nil))
  17462. (t (setq start (match-end 0))))))
  17463. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17464. (goto-char pos)
  17465. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17466. (and (match-beginning 2) (throw 'exit nil))
  17467. ;; count $$
  17468. (while (re-search-backward "\\$\\$" lim t)
  17469. (setq dd-on (not dd-on)))
  17470. (goto-char pos)
  17471. (when dd-on (cons "$$" m))))))
  17472. (defun org-inside-latex-macro-p ()
  17473. "Is point inside a LaTeX macro or its arguments?"
  17474. (save-match-data
  17475. (org-in-regexp
  17476. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17477. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17478. "Build an overlay between BEG and END using IMAGE file.
  17479. Argument IMAGETYPE is the extension of the displayed image,
  17480. as a string. It defaults to \"png\"."
  17481. (let ((ov (make-overlay beg end))
  17482. (imagetype (or (intern imagetype) 'png)))
  17483. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17484. (overlay-put ov 'evaporate t)
  17485. (overlay-put ov
  17486. 'modification-hooks
  17487. (list (lambda (o _flag _beg _end &optional _l)
  17488. (delete-overlay o))))
  17489. (overlay-put ov
  17490. 'display
  17491. (list 'image :type imagetype :file image :ascent 'center))))
  17492. (defun org--list-latex-overlays (&optional beg end)
  17493. "List all Org LaTeX overlays in current buffer.
  17494. Limit to overlays between BEG and END when those are provided."
  17495. (cl-remove-if-not
  17496. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17497. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17498. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17499. "Remove all overlays with LaTeX fragment images in current buffer.
  17500. When optional arguments BEG and END are non-nil, remove all
  17501. overlays between them instead. Return a non-nil value when some
  17502. overlays were removed, nil otherwise."
  17503. (let ((overlays (org--list-latex-overlays beg end)))
  17504. (mapc #'delete-overlay overlays)
  17505. overlays))
  17506. (defun org-toggle-latex-fragment (&optional arg)
  17507. "Preview the LaTeX fragment at point, or all locally or globally.
  17508. If the cursor is on a LaTeX fragment, create the image and overlay
  17509. it over the source code, if there is none. Remove it otherwise.
  17510. If there is no fragment at point, display all fragments in the
  17511. current section.
  17512. With prefix ARG, preview or clear image for all fragments in the
  17513. current subtree or in the whole buffer when used before the first
  17514. headline. With a prefix ARG `\\[universal-argument] \
  17515. \\[universal-argument]' preview or clear images
  17516. for all fragments in the buffer."
  17517. (interactive "P")
  17518. (when (display-graphic-p)
  17519. (catch 'exit
  17520. (save-excursion
  17521. (let (beg end msg)
  17522. (cond
  17523. ((or (equal arg '(16))
  17524. (and (equal arg '(4))
  17525. (org-with-limited-levels (org-before-first-heading-p))))
  17526. (if (org-remove-latex-fragment-image-overlays)
  17527. (progn (message "LaTeX fragments images removed from buffer")
  17528. (throw 'exit nil))
  17529. (setq msg "Creating images for buffer...")))
  17530. ((equal arg '(4))
  17531. (org-with-limited-levels (org-back-to-heading t))
  17532. (setq beg (point))
  17533. (setq end (progn (org-end-of-subtree t) (point)))
  17534. (if (org-remove-latex-fragment-image-overlays beg end)
  17535. (progn
  17536. (message "LaTeX fragment images removed from subtree")
  17537. (throw 'exit nil))
  17538. (setq msg "Creating images for subtree...")))
  17539. ((let ((datum (org-element-context)))
  17540. (when (memq (org-element-type datum)
  17541. '(latex-environment latex-fragment))
  17542. (setq beg (org-element-property :begin datum))
  17543. (setq end (org-element-property :end datum))
  17544. (if (org-remove-latex-fragment-image-overlays beg end)
  17545. (progn (message "LaTeX fragment image removed")
  17546. (throw 'exit nil))
  17547. (setq msg "Creating image...")))))
  17548. (t
  17549. (org-with-limited-levels
  17550. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17551. (outline-previous-heading)
  17552. (point)))
  17553. (setq end (progn (outline-next-heading) (point)))
  17554. (if (org-remove-latex-fragment-image-overlays beg end)
  17555. (progn
  17556. (message "LaTeX fragment images removed from section")
  17557. (throw 'exit nil))
  17558. (setq msg "Creating images for section...")))))
  17559. (let ((file (buffer-file-name (buffer-base-buffer))))
  17560. (org-format-latex
  17561. (concat org-preview-latex-image-directory "org-ltximg")
  17562. beg end
  17563. ;; Emacs cannot overlay images from remote hosts. Create
  17564. ;; it in `temporary-file-directory' instead.
  17565. (if (or (not file) (file-remote-p file))
  17566. temporary-file-directory
  17567. default-directory)
  17568. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17569. (message (concat msg "done")))))))
  17570. (defun org-format-latex
  17571. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17572. "Replace LaTeX fragments with links to an image.
  17573. The function takes care of creating the replacement image.
  17574. Only consider fragments between BEG and END when those are
  17575. provided.
  17576. When optional argument OVERLAYS is non-nil, display the image on
  17577. top of the fragment instead of replacing it.
  17578. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17579. Some of the options can be changed using the variable
  17580. `org-format-latex-options', which see."
  17581. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17582. (unless (eq processing-type 'verbatim)
  17583. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17584. (cnt 0)
  17585. checkdir-flag)
  17586. (goto-char (or beg (point-min)))
  17587. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17588. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17589. (overlay-recenter (or end (point-max))))
  17590. (while (re-search-forward math-regexp end t)
  17591. (unless (and overlays
  17592. (eq (get-char-property (point) 'org-overlay-type)
  17593. 'org-latex-overlay))
  17594. (let* ((context (org-element-context))
  17595. (type (org-element-type context)))
  17596. (when (memq type '(latex-environment latex-fragment))
  17597. (let ((block-type (eq type 'latex-environment))
  17598. (value (org-element-property :value context))
  17599. (beg (org-element-property :begin context))
  17600. (end (save-excursion
  17601. (goto-char (org-element-property :end context))
  17602. (skip-chars-backward " \r\t\n")
  17603. (point))))
  17604. (cond
  17605. ((eq processing-type 'mathjax)
  17606. ;; Prepare for MathJax processing.
  17607. (if (not (string-match "\\`\\$\\$?" value))
  17608. (goto-char end)
  17609. (delete-region beg end)
  17610. (if (string= (match-string 0 value) "$$")
  17611. (insert "\\[" (substring value 2 -2) "\\]")
  17612. (insert "\\(" (substring value 1 -1) "\\)"))))
  17613. ((assq processing-type org-preview-latex-process-alist)
  17614. ;; Process to an image.
  17615. (cl-incf cnt)
  17616. (goto-char beg)
  17617. (let* ((processing-info
  17618. (cdr (assq processing-type org-preview-latex-process-alist)))
  17619. (face (face-at-point))
  17620. ;; Get the colors from the face at point.
  17621. (fg
  17622. (let ((color (plist-get org-format-latex-options
  17623. :foreground)))
  17624. (if (and forbuffer (eq color 'auto))
  17625. (face-attribute face :foreground nil 'default)
  17626. color)))
  17627. (bg
  17628. (let ((color (plist-get org-format-latex-options
  17629. :background)))
  17630. (if (and forbuffer (eq color 'auto))
  17631. (face-attribute face :background nil 'default)
  17632. color)))
  17633. (hash (sha1 (prin1-to-string
  17634. (list org-format-latex-header
  17635. org-latex-default-packages-alist
  17636. org-latex-packages-alist
  17637. org-format-latex-options
  17638. forbuffer value fg bg))))
  17639. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17640. (absprefix (expand-file-name prefix dir))
  17641. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17642. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17643. (sep (and block-type "\n\n"))
  17644. (link (concat sep "[[file:" linkfile "]]" sep))
  17645. (options
  17646. (org-combine-plists
  17647. org-format-latex-options
  17648. `(:foreground ,fg :background ,bg))))
  17649. (when msg (message msg cnt))
  17650. (unless checkdir-flag ; Ensure the directory exists.
  17651. (setq checkdir-flag t)
  17652. (let ((todir (file-name-directory absprefix)))
  17653. (unless (file-directory-p todir)
  17654. (make-directory todir t))))
  17655. (unless (file-exists-p movefile)
  17656. (org-create-formula-image
  17657. value movefile options forbuffer processing-type))
  17658. (if overlays
  17659. (progn
  17660. (dolist (o (overlays-in beg end))
  17661. (when (eq (overlay-get o 'org-overlay-type)
  17662. 'org-latex-overlay)
  17663. (delete-overlay o)))
  17664. (org--format-latex-make-overlay beg end movefile imagetype)
  17665. (goto-char end))
  17666. (delete-region beg end)
  17667. (insert
  17668. (org-add-props link
  17669. (list 'org-latex-src
  17670. (replace-regexp-in-string "\"" "" value)
  17671. 'org-latex-src-embed-type
  17672. (if block-type 'paragraph 'character)))))))
  17673. ((eq processing-type 'mathml)
  17674. ;; Process to MathML.
  17675. (unless (org-format-latex-mathml-available-p)
  17676. (user-error "LaTeX to MathML converter not configured"))
  17677. (cl-incf cnt)
  17678. (when msg (message msg cnt))
  17679. (goto-char beg)
  17680. (delete-region beg end)
  17681. (insert (org-format-latex-as-mathml
  17682. value block-type prefix dir)))
  17683. (t
  17684. (error "Unknown conversion process %s for LaTeX fragments"
  17685. processing-type)))))))))))
  17686. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17687. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17688. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17689. sucessful, return the portion between \"<math...> </math>\"
  17690. elements otherwise return nil. When MATHML-FILE is specified,
  17691. write the results in to that file. When invoked as an
  17692. interactive command, prompt for LATEX-FRAG, with initial value
  17693. set to the current active region and echo the results for user
  17694. inspection."
  17695. (interactive (list (let ((frag (when (org-region-active-p)
  17696. (buffer-substring-no-properties
  17697. (region-beginning) (region-end)))))
  17698. (read-string "LaTeX Fragment: " frag nil frag))))
  17699. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17700. (let* ((tmp-in-file
  17701. (let ((file (file-relative-name
  17702. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17703. (write-region latex-frag nil file)
  17704. file))
  17705. (tmp-out-file (file-relative-name
  17706. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17707. (cmd (format-spec
  17708. org-latex-to-mathml-convert-command
  17709. `((?j . ,(and org-latex-to-mathml-jar-file
  17710. (shell-quote-argument
  17711. (expand-file-name
  17712. org-latex-to-mathml-jar-file))))
  17713. (?I . ,(shell-quote-argument tmp-in-file))
  17714. (?i . ,latex-frag)
  17715. (?o . ,(shell-quote-argument tmp-out-file)))))
  17716. mathml shell-command-output)
  17717. (when (called-interactively-p 'any)
  17718. (unless (org-format-latex-mathml-available-p)
  17719. (user-error "LaTeX to MathML converter not configured")))
  17720. (message "Running %s" cmd)
  17721. (setq shell-command-output (shell-command-to-string cmd))
  17722. (setq mathml
  17723. (when (file-readable-p tmp-out-file)
  17724. (with-current-buffer (find-file-noselect tmp-out-file t)
  17725. (goto-char (point-min))
  17726. (when (re-search-forward
  17727. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17728. (regexp-quote
  17729. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17730. nil t)
  17731. (prog1 (match-string 0) (kill-buffer))))))
  17732. (cond
  17733. (mathml
  17734. (setq mathml
  17735. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17736. (when mathml-file
  17737. (write-region mathml nil mathml-file))
  17738. (when (called-interactively-p 'any)
  17739. (message mathml)))
  17740. ((message "LaTeX to MathML conversion failed")
  17741. (message shell-command-output)))
  17742. (delete-file tmp-in-file)
  17743. (when (file-exists-p tmp-out-file)
  17744. (delete-file tmp-out-file))
  17745. mathml))
  17746. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17747. prefix &optional dir)
  17748. "Use `org-create-math-formula' but check local cache first."
  17749. (let* ((absprefix (expand-file-name prefix dir))
  17750. (print-length nil) (print-level nil)
  17751. (formula-id (concat
  17752. "formula-"
  17753. (sha1
  17754. (prin1-to-string
  17755. (list latex-frag
  17756. org-latex-to-mathml-convert-command)))))
  17757. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17758. (formula-cache-dir (file-name-directory formula-cache)))
  17759. (unless (file-directory-p formula-cache-dir)
  17760. (make-directory formula-cache-dir t))
  17761. (unless (file-exists-p formula-cache)
  17762. (org-create-math-formula latex-frag formula-cache))
  17763. (if (file-exists-p formula-cache)
  17764. ;; Successful conversion. Return the link to MathML file.
  17765. (org-add-props
  17766. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17767. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17768. 'org-latex-src-embed-type (if latex-frag-type
  17769. 'paragraph 'character)))
  17770. ;; Failed conversion. Return the LaTeX fragment verbatim
  17771. latex-frag)))
  17772. (defun org--get-display-dpi ()
  17773. "Get the DPI of the display.
  17774. The function assumes that the display has the same pixel width in
  17775. the horizontal and vertical directions."
  17776. (if (display-graphic-p)
  17777. (round (/ (display-pixel-height)
  17778. (/ (display-mm-height) 25.4)))
  17779. (error "Attempt to calculate the dpi of a non-graphic display")))
  17780. (defun org-create-formula-image
  17781. (string tofile options buffer &optional processing-type)
  17782. "Create an image from LaTeX source using external processes.
  17783. The LaTeX STRING is saved to a temporary LaTeX file, then
  17784. converted to an image file by process PROCESSING-TYPE defined in
  17785. `org-preview-latex-process-alist'. A nil value defaults to
  17786. `org-preview-latex-default-process'.
  17787. The generated image file is eventually moved to TOFILE.
  17788. The OPTIONS argument controls the size, foreground color and
  17789. background color of the generated image.
  17790. When BUFFER non-nil, this function is used for LaTeX previewing.
  17791. Otherwise, it is used to deal with LaTeX snippets showed in
  17792. a HTML file."
  17793. (let* ((processing-type (or processing-type
  17794. org-preview-latex-default-process))
  17795. (processing-info
  17796. (cdr (assq processing-type org-preview-latex-process-alist)))
  17797. (programs (plist-get processing-info :programs))
  17798. (error-message (or (plist-get processing-info :message) ""))
  17799. (use-xcolor (plist-get processing-info :use-xcolor))
  17800. (image-input-type (plist-get processing-info :image-input-type))
  17801. (image-output-type (plist-get processing-info :image-output-type))
  17802. (post-clean (or (plist-get processing-info :post-clean)
  17803. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17804. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17805. (latex-header
  17806. (or (plist-get processing-info :latex-header)
  17807. (org-latex-make-preamble
  17808. (org-export-get-environment (org-export-get-backend 'latex))
  17809. org-format-latex-header
  17810. 'snippet)))
  17811. (latex-compiler (plist-get processing-info :latex-compiler))
  17812. (image-converter (plist-get processing-info :image-converter))
  17813. (tmpdir temporary-file-directory)
  17814. (texfilebase (make-temp-name
  17815. (expand-file-name "orgtex" tmpdir)))
  17816. (texfile (concat texfilebase ".tex"))
  17817. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17818. '(1.0 . 1.0)))
  17819. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17820. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17821. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17822. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17823. "Black"))
  17824. (bg (or (plist-get options (if buffer :background :html-background))
  17825. "Transparent"))
  17826. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17827. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17828. (dolist (program programs)
  17829. (org-check-external-command program error-message))
  17830. (if use-xcolor
  17831. (progn (if (eq fg 'default)
  17832. (setq fg (org-latex-color :foreground))
  17833. (setq fg (org-latex-color-format fg)))
  17834. (if (eq bg 'default)
  17835. (setq bg (org-latex-color :background))
  17836. (setq bg (org-latex-color-format
  17837. (if (string= bg "Transparent") "white" bg))))
  17838. (with-temp-file texfile
  17839. (insert latex-header)
  17840. (insert "\n\\begin{document}\n"
  17841. "\\definecolor{fg}{rgb}{" fg "}\n"
  17842. "\\definecolor{bg}{rgb}{" bg "}\n"
  17843. "\n\\pagecolor{bg}\n"
  17844. "\n{\\color{fg}\n"
  17845. string
  17846. "\n}\n"
  17847. "\n\\end{document}\n")))
  17848. (if (eq fg 'default)
  17849. (setq fg (org-dvipng-color :foreground))
  17850. (unless (string= fg "Transparent")
  17851. (setq fg (org-dvipng-color-format fg))))
  17852. (if (eq bg 'default)
  17853. (setq bg (org-dvipng-color :background))
  17854. (unless (string= bg "Transparent")
  17855. (setq bg (org-dvipng-color-format bg))))
  17856. (with-temp-file texfile
  17857. (insert latex-header)
  17858. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17859. (let* ((err-msg (format "Please adjust '%s' part of \
  17860. `org-preview-latex-process-alist'."
  17861. processing-type))
  17862. (image-input-file
  17863. (org-compile-file
  17864. texfile latex-compiler image-input-type err-msg log-buf))
  17865. (image-output-file
  17866. (org-compile-file
  17867. image-input-file image-converter image-output-type err-msg log-buf
  17868. `((?F . ,(shell-quote-argument fg))
  17869. (?B . ,(shell-quote-argument bg))
  17870. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17871. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17872. (copy-file image-output-file tofile 'replace)
  17873. (dolist (e post-clean)
  17874. (when (file-exists-p (concat texfilebase e))
  17875. (delete-file (concat texfilebase e))))
  17876. image-output-file)))
  17877. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17878. "Fill a LaTeX header template TPL.
  17879. In the template, the following place holders will be recognized:
  17880. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17881. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17882. [PACKAGES] \\usepackage statements for PKG
  17883. [NO-PACKAGES] do not include PKG
  17884. [EXTRA] the string EXTRA
  17885. [NO-EXTRA] do not include EXTRA
  17886. For backward compatibility, if both the positive and the negative place
  17887. holder is missing, the positive one (without the \"NO-\") will be
  17888. assumed to be present at the end of the template.
  17889. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17890. EXTRA is a string.
  17891. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17892. (let (rpl (end ""))
  17893. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17894. (setq rpl (if (or (match-end 1) (not def-pkg))
  17895. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17896. tpl (replace-match rpl t t tpl))
  17897. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17898. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17899. (setq rpl (if (or (match-end 1) (not pkg))
  17900. "" (org-latex-packages-to-string pkg snippets-p t))
  17901. tpl (replace-match rpl t t tpl))
  17902. (when pkg (setq end
  17903. (concat end "\n"
  17904. (org-latex-packages-to-string pkg snippets-p)))))
  17905. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17906. (setq rpl (if (or (match-end 1) (not extra))
  17907. "" (concat extra "\n"))
  17908. tpl (replace-match rpl t t tpl))
  17909. (when (and extra (string-match "\\S-" extra))
  17910. (setq end (concat end "\n" extra))))
  17911. (if (string-match "\\S-" end)
  17912. (concat tpl "\n" end)
  17913. tpl)))
  17914. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17915. "Turn an alist of packages into a string with the \\usepackage macros."
  17916. (setq pkg (mapconcat (lambda(p)
  17917. (cond
  17918. ((stringp p) p)
  17919. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17920. (format "%% Package %s omitted" (cadr p)))
  17921. ((equal "" (car p))
  17922. (format "\\usepackage{%s}" (cadr p)))
  17923. (t
  17924. (format "\\usepackage[%s]{%s}"
  17925. (car p) (cadr p)))))
  17926. pkg
  17927. "\n"))
  17928. (if newline (concat pkg "\n") pkg))
  17929. (defun org-dvipng-color (attr)
  17930. "Return a RGB color specification for dvipng."
  17931. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17932. (defun org-dvipng-color-format (color-name)
  17933. "Convert COLOR-NAME to a RGB color value for dvipng."
  17934. (apply #'format "rgb %s %s %s"
  17935. (mapcar 'org-normalize-color
  17936. (color-values color-name))))
  17937. (defun org-latex-color (attr)
  17938. "Return a RGB color for the LaTeX color package."
  17939. (org-latex-color-format (face-attribute 'default attr nil)))
  17940. (defun org-latex-color-format (color-name)
  17941. "Convert COLOR-NAME to a RGB color value."
  17942. (apply #'format "%s,%s,%s"
  17943. (mapcar 'org-normalize-color
  17944. (color-values color-name))))
  17945. (defun org-normalize-color (value)
  17946. "Return string to be used as color value for an RGB component."
  17947. (format "%g" (/ value 65535.0)))
  17948. ;; Image display
  17949. (defvar-local org-inline-image-overlays nil)
  17950. (defun org-toggle-inline-images (&optional include-linked)
  17951. "Toggle the display of inline images.
  17952. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17953. (interactive "P")
  17954. (if org-inline-image-overlays
  17955. (progn
  17956. (org-remove-inline-images)
  17957. (when (called-interactively-p 'interactive)
  17958. (message "Inline image display turned off")))
  17959. (org-display-inline-images include-linked)
  17960. (when (called-interactively-p 'interactive)
  17961. (message (if org-inline-image-overlays
  17962. (format "%d images displayed inline"
  17963. (length org-inline-image-overlays))
  17964. "No images to display inline")))))
  17965. (defun org-redisplay-inline-images ()
  17966. "Refresh the display of inline images."
  17967. (interactive)
  17968. (if (not org-inline-image-overlays)
  17969. (org-toggle-inline-images)
  17970. (org-toggle-inline-images)
  17971. (org-toggle-inline-images)))
  17972. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17973. "Display inline images.
  17974. An inline image is a link which follows either of these
  17975. conventions:
  17976. 1. Its path is a file with an extension matching return value
  17977. from `image-file-name-regexp' and it has no contents.
  17978. 2. Its description consists in a single link of the previous
  17979. type.
  17980. When optional argument INCLUDE-LINKED is non-nil, also links with
  17981. a text description part will be inlined. This can be nice for
  17982. a quick look at those images, but it does not reflect what
  17983. exported files will look like.
  17984. When optional argument REFRESH is non-nil, refresh existing
  17985. images between BEG and END. This will create new image displays
  17986. only if necessary. BEG and END default to the buffer
  17987. boundaries."
  17988. (interactive "P")
  17989. (when (display-graphic-p)
  17990. (unless refresh
  17991. (org-remove-inline-images)
  17992. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17993. (org-with-wide-buffer
  17994. (goto-char (or beg (point-min)))
  17995. (let ((case-fold-search t)
  17996. (file-extension-re (image-file-name-regexp)))
  17997. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17998. (let ((link (save-match-data (org-element-context))))
  17999. ;; Check if we're at an inline image.
  18000. (when (and (equal (org-element-property :type link) "file")
  18001. (or include-linked
  18002. (not (org-element-property :contents-begin link)))
  18003. (let ((parent (org-element-property :parent link)))
  18004. (or (not (eq (org-element-type parent) 'link))
  18005. (not (cdr (org-element-contents parent)))))
  18006. (string-match-p file-extension-re
  18007. (org-element-property :path link)))
  18008. (let ((file (expand-file-name
  18009. (org-link-unescape
  18010. (org-element-property :path link)))))
  18011. (when (file-exists-p file)
  18012. (let ((width
  18013. ;; Apply `org-image-actual-width' specifications.
  18014. (cond
  18015. ((not (image-type-available-p 'imagemagick)) nil)
  18016. ((eq org-image-actual-width t) nil)
  18017. ((listp org-image-actual-width)
  18018. (or
  18019. ;; First try to find a width among
  18020. ;; attributes associated to the paragraph
  18021. ;; containing link.
  18022. (let ((paragraph
  18023. (let ((e link))
  18024. (while (and (setq e (org-element-property
  18025. :parent e))
  18026. (not (eq (org-element-type e)
  18027. 'paragraph))))
  18028. e)))
  18029. (when paragraph
  18030. (save-excursion
  18031. (goto-char (org-element-property :begin paragraph))
  18032. (when
  18033. (re-search-forward
  18034. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18035. (org-element-property
  18036. :post-affiliated paragraph)
  18037. t)
  18038. (string-to-number (match-string 1))))))
  18039. ;; Otherwise, fall-back to provided number.
  18040. (car org-image-actual-width)))
  18041. ((numberp org-image-actual-width)
  18042. org-image-actual-width)))
  18043. (old (get-char-property-and-overlay
  18044. (org-element-property :begin link)
  18045. 'org-image-overlay)))
  18046. (if (and (car-safe old) refresh)
  18047. (image-refresh (overlay-get (cdr old) 'display))
  18048. (let ((image (create-image file
  18049. (and width 'imagemagick)
  18050. nil
  18051. :width width)))
  18052. (when image
  18053. (let* ((link
  18054. ;; If inline image is the description
  18055. ;; of another link, be sure to
  18056. ;; consider the latter as the one to
  18057. ;; apply the overlay on.
  18058. (let ((parent
  18059. (org-element-property :parent link)))
  18060. (if (eq (org-element-type parent) 'link)
  18061. parent
  18062. link)))
  18063. (ov (make-overlay
  18064. (org-element-property :begin link)
  18065. (progn
  18066. (goto-char
  18067. (org-element-property :end link))
  18068. (skip-chars-backward " \t")
  18069. (point)))))
  18070. (overlay-put ov 'display image)
  18071. (overlay-put ov 'face 'default)
  18072. (overlay-put ov 'org-image-overlay t)
  18073. (overlay-put
  18074. ov 'modification-hooks
  18075. (list 'org-display-inline-remove-overlay))
  18076. (push ov org-inline-image-overlays)))))))))))))))
  18077. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18078. "Remove inline-display overlay if a corresponding region is modified."
  18079. (let ((inhibit-modification-hooks t))
  18080. (when (and ov after)
  18081. (delete ov org-inline-image-overlays)
  18082. (delete-overlay ov))))
  18083. (defun org-remove-inline-images ()
  18084. "Remove inline display of images."
  18085. (interactive)
  18086. (mapc #'delete-overlay org-inline-image-overlays)
  18087. (setq org-inline-image-overlays nil))
  18088. ;;;; Key bindings
  18089. ;; Outline functions from `outline-mode-prefix-map'
  18090. ;; that can be remapped in Org:
  18091. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18092. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18093. (define-key org-mode-map [remap outline-forward-same-level]
  18094. 'org-forward-heading-same-level)
  18095. (define-key org-mode-map [remap outline-backward-same-level]
  18096. 'org-backward-heading-same-level)
  18097. (define-key org-mode-map [remap outline-show-branches]
  18098. 'org-kill-note-or-show-branches)
  18099. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18100. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18101. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18102. (define-key org-mode-map [remap outline-next-visible-heading]
  18103. 'org-next-visible-heading)
  18104. (define-key org-mode-map [remap outline-previous-visible-heading]
  18105. 'org-previous-visible-heading)
  18106. (define-key org-mode-map [remap show-children] 'org-show-children)
  18107. ;; Outline functions from `outline-mode-prefix-map' that can not
  18108. ;; be remapped in Org:
  18109. ;; - the column "key binding" shows whether the Outline function is still
  18110. ;; available in Org mode on the same key that it has been bound to in
  18111. ;; Outline mode:
  18112. ;; - "overridden": key used for a different functionality in Org mode
  18113. ;; - else: key still bound to the same Outline function in Org mode
  18114. ;; | Outline function | key binding | Org replacement |
  18115. ;; |------------------------------------+-------------+--------------------------|
  18116. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18117. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18118. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18119. ;; | `show-entry' | overridden | no replacement |
  18120. ;; | `show-branches' | `C-c C-k' | still same function |
  18121. ;; | `show-subtree' | overridden | visibility cycling |
  18122. ;; | `show-all' | overridden | no replacement |
  18123. ;; | `hide-subtree' | overridden | visibility cycling |
  18124. ;; | `hide-body' | overridden | no replacement |
  18125. ;; | `hide-entry' | overridden | visibility cycling |
  18126. ;; | `hide-leaves' | overridden | no replacement |
  18127. ;; | `hide-sublevels' | overridden | no replacement |
  18128. ;; | `hide-other' | overridden | no replacement |
  18129. ;; Make `C-c C-x' a prefix key
  18130. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18131. ;; TAB key with modifiers
  18132. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18133. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18134. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18135. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18136. ;; The following line is necessary under Suse GNU/Linux
  18137. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18138. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18139. (define-key org-mode-map [backtab] 'org-shifttab)
  18140. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18141. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18142. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18143. ;; Cursor keys with modifiers
  18144. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18145. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18146. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18147. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18148. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18149. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18150. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18151. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18152. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18153. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18154. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18155. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18156. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18157. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18158. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18159. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18160. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18161. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18162. ;; Babel keys
  18163. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18164. (dolist (pair org-babel-key-bindings)
  18165. (define-key org-babel-map (car pair) (cdr pair)))
  18166. ;;; Extra keys for tty access.
  18167. ;; We only set them when really needed because otherwise the
  18168. ;; menus don't show the simple keys
  18169. (when (or org-use-extra-keys (not window-system))
  18170. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18171. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18172. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18173. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18174. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18175. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18176. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18177. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18178. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18179. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18180. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18181. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18182. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18183. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18184. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18185. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18186. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18187. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18188. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18189. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18190. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18191. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18192. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18193. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18194. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18195. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18196. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18197. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18198. ;; All the other keys
  18199. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18200. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18201. (if (boundp 'narrow-map)
  18202. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18203. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18204. (if (boundp 'narrow-map)
  18205. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18206. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18207. (if (boundp 'narrow-map)
  18208. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18209. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18210. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18211. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18212. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18213. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18214. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18215. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18216. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18217. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18218. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18219. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18220. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18221. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18222. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18223. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18224. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18225. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18226. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18227. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18228. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18229. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18230. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18231. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18232. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18233. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18234. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18235. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18236. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18237. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18238. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18239. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18240. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18241. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18242. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18243. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18244. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18245. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18246. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18247. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18248. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18249. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18250. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18251. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18252. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18253. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18254. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18255. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18256. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18257. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18258. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18259. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18260. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18261. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18262. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18263. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18264. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18265. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18266. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18267. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18268. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18269. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18270. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18271. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18272. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18273. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18274. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18275. (org-defkey org-mode-map "\C-m" 'org-return)
  18276. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18277. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18278. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18279. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18280. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18281. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18282. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18283. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18284. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18285. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18286. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18287. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18288. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18289. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18290. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18291. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18292. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18293. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18294. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18295. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18296. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18297. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18298. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18299. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18300. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18301. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18302. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18303. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18304. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18305. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18306. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18307. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18308. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18309. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18310. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18311. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18312. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18313. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18314. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18315. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18316. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18317. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18318. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18319. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18320. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18321. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18322. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18323. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18324. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18325. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18326. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18327. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18328. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18329. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18330. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18331. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18332. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18333. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18334. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18335. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18336. (defconst org-speed-commands-default
  18337. '(
  18338. ("Outline Navigation")
  18339. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18340. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18341. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18342. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18343. ("F" . org-next-block)
  18344. ("B" . org-previous-block)
  18345. ("u" . (org-speed-move-safe 'outline-up-heading))
  18346. ("j" . org-goto)
  18347. ("g" . (org-refile t))
  18348. ("Outline Visibility")
  18349. ("c" . org-cycle)
  18350. ("C" . org-shifttab)
  18351. (" " . org-display-outline-path)
  18352. ("s" . org-narrow-to-subtree)
  18353. ("=" . org-columns)
  18354. ("Outline Structure Editing")
  18355. ("U" . org-metaup)
  18356. ("D" . org-metadown)
  18357. ("r" . org-metaright)
  18358. ("l" . org-metaleft)
  18359. ("R" . org-shiftmetaright)
  18360. ("L" . org-shiftmetaleft)
  18361. ("i" . (progn (forward-char 1) (call-interactively
  18362. 'org-insert-heading-respect-content)))
  18363. ("^" . org-sort)
  18364. ("w" . org-refile)
  18365. ("a" . org-archive-subtree-default-with-confirmation)
  18366. ("@" . org-mark-subtree)
  18367. ("#" . org-toggle-comment)
  18368. ("Clock Commands")
  18369. ("I" . org-clock-in)
  18370. ("O" . org-clock-out)
  18371. ("Meta Data Editing")
  18372. ("t" . org-todo)
  18373. ("," . (org-priority))
  18374. ("0" . (org-priority ?\ ))
  18375. ("1" . (org-priority ?A))
  18376. ("2" . (org-priority ?B))
  18377. ("3" . (org-priority ?C))
  18378. (":" . org-set-tags-command)
  18379. ("e" . org-set-effort)
  18380. ("E" . org-inc-effort)
  18381. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18382. (org-entry-put (point) "APPT_WARNTIME" m)))
  18383. ("Agenda Views etc")
  18384. ("v" . org-agenda)
  18385. ("/" . org-sparse-tree)
  18386. ("Misc")
  18387. ("o" . org-open-at-point)
  18388. ("?" . org-speed-command-help)
  18389. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18390. (">" . (org-agenda-remove-restriction-lock))
  18391. )
  18392. "The default speed commands.")
  18393. (defun org-print-speed-command (e)
  18394. (if (> (length (car e)) 1)
  18395. (progn
  18396. (princ "\n")
  18397. (princ (car e))
  18398. (princ "\n")
  18399. (princ (make-string (length (car e)) ?-))
  18400. (princ "\n"))
  18401. (princ (car e))
  18402. (princ " ")
  18403. (if (symbolp (cdr e))
  18404. (princ (symbol-name (cdr e)))
  18405. (prin1 (cdr e)))
  18406. (princ "\n")))
  18407. (defun org-speed-command-help ()
  18408. "Show the available speed commands."
  18409. (interactive)
  18410. (if (not org-use-speed-commands)
  18411. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18412. (with-output-to-temp-buffer "*Help*"
  18413. (princ "User-defined Speed commands\n===========================\n")
  18414. (mapc #'org-print-speed-command org-speed-commands-user)
  18415. (princ "\n")
  18416. (princ "Built-in Speed commands\n=======================\n")
  18417. (mapc #'org-print-speed-command org-speed-commands-default))
  18418. (with-current-buffer "*Help*"
  18419. (setq truncate-lines t))))
  18420. (defun org-speed-move-safe (cmd)
  18421. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18422. If not, return to the original position and throw an error."
  18423. (interactive)
  18424. (let ((pos (point)))
  18425. (call-interactively cmd)
  18426. (unless (and (bolp) (org-at-heading-p))
  18427. (goto-char pos)
  18428. (error "Boundary reached while executing %s" cmd))))
  18429. (defvar org-self-insert-command-undo-counter 0)
  18430. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18431. (defvar org-speed-command nil)
  18432. (defun org-speed-command-activate (keys)
  18433. "Hook for activating single-letter speed commands.
  18434. `org-speed-commands-default' specifies a minimal command set.
  18435. Use `org-speed-commands-user' for further customization."
  18436. (when (or (and (bolp) (looking-at org-outline-regexp))
  18437. (and (functionp org-use-speed-commands)
  18438. (funcall org-use-speed-commands)))
  18439. (cdr (assoc keys (append org-speed-commands-user
  18440. org-speed-commands-default)))))
  18441. (defun org-babel-speed-command-activate (keys)
  18442. "Hook for activating single-letter code block commands."
  18443. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18444. (cdr (assoc keys org-babel-key-bindings))))
  18445. (defcustom org-speed-command-hook
  18446. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18447. "Hook for activating speed commands at strategic locations.
  18448. Hook functions are called in sequence until a valid handler is
  18449. found.
  18450. Each hook takes a single argument, a user-pressed command key
  18451. which is also a `self-insert-command' from the global map.
  18452. Within the hook, examine the cursor position and the command key
  18453. and return nil or a valid handler as appropriate. Handler could
  18454. be one of an interactive command, a function, or a form.
  18455. Set `org-use-speed-commands' to non-nil value to enable this
  18456. hook. The default setting is `org-speed-command-activate'."
  18457. :group 'org-structure
  18458. :version "24.1"
  18459. :type 'hook)
  18460. (defun org-self-insert-command (N)
  18461. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18462. If the cursor is in a table looking at whitespace, the whitespace is
  18463. overwritten, and the table is not marked as requiring realignment."
  18464. (interactive "p")
  18465. (org-check-before-invisible-edit 'insert)
  18466. (cond
  18467. ((and org-use-speed-commands
  18468. (let ((kv (this-command-keys-vector)))
  18469. (setq org-speed-command
  18470. (run-hook-with-args-until-success
  18471. 'org-speed-command-hook
  18472. (make-string 1 (aref kv (1- (length kv))))))))
  18473. (cond
  18474. ((commandp org-speed-command)
  18475. (setq this-command org-speed-command)
  18476. (call-interactively org-speed-command))
  18477. ((functionp org-speed-command)
  18478. (funcall org-speed-command))
  18479. ((and org-speed-command (listp org-speed-command))
  18480. (eval org-speed-command))
  18481. (t (let (org-use-speed-commands)
  18482. (call-interactively 'org-self-insert-command)))))
  18483. ((and
  18484. (org-at-table-p)
  18485. (progn
  18486. ;; Check if we blank the field, and if that triggers align.
  18487. (and (featurep 'org-table) org-table-auto-blank-field
  18488. (memq last-command
  18489. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18490. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18491. ;; Got extra space, this field does not determine
  18492. ;; column width.
  18493. (let (org-table-may-need-update) (org-table-blank-field))
  18494. ;; No extra space, this field may determine column
  18495. ;; width.
  18496. (org-table-blank-field)))
  18497. t)
  18498. (eq N 1)
  18499. (looking-at "[^|\n]* \\( \\)|"))
  18500. ;; There is room for insertion without re-aligning the table.
  18501. (delete-region (match-beginning 1) (match-end 1))
  18502. (self-insert-command N))
  18503. (t
  18504. (setq org-table-may-need-update t)
  18505. (self-insert-command N)
  18506. (org-fix-tags-on-the-fly)
  18507. (when org-self-insert-cluster-for-undo
  18508. (if (not (eq last-command 'org-self-insert-command))
  18509. (setq org-self-insert-command-undo-counter 1)
  18510. (if (>= org-self-insert-command-undo-counter 20)
  18511. (setq org-self-insert-command-undo-counter 1)
  18512. (and (> org-self-insert-command-undo-counter 0)
  18513. buffer-undo-list (listp buffer-undo-list)
  18514. (not (cadr buffer-undo-list)) ; remove nil entry
  18515. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18516. (setq org-self-insert-command-undo-counter
  18517. (1+ org-self-insert-command-undo-counter))))))))
  18518. (defun org-check-before-invisible-edit (kind)
  18519. "Check is editing if kind KIND would be dangerous with invisible text around.
  18520. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18521. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18522. (when (and org-catch-invisible-edits
  18523. (or (not (boundp 'visible-mode)) (not visible-mode))
  18524. (or (get-char-property (point) 'invisible)
  18525. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18526. ;; OK, we need to take a closer look
  18527. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18528. (invisible-before-point (unless (bobp) (get-char-property
  18529. (1- (point)) 'invisible)))
  18530. (border-and-ok-direction
  18531. (or
  18532. ;; Check if we are acting predictably before invisible text
  18533. (and invisible-at-point (not invisible-before-point)
  18534. (memq kind '(insert delete-backward)))
  18535. ;; Check if we are acting predictably after invisible text
  18536. ;; This works not well, and I have turned it off. It seems
  18537. ;; better to always show and stop after invisible text.
  18538. ;; (and (not invisible-at-point) invisible-before-point
  18539. ;; (memq kind '(insert delete)))
  18540. )))
  18541. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18542. (memq invisible-before-point '(outline org-hide-block t)))
  18543. (when (eq org-catch-invisible-edits 'error)
  18544. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18545. (if (and org-custom-properties-overlays
  18546. (y-or-n-p "Display invisible properties in this buffer? "))
  18547. (org-toggle-custom-properties-visibility)
  18548. ;; Make the area visible
  18549. (save-excursion
  18550. (when invisible-before-point
  18551. (goto-char (previous-single-char-property-change
  18552. (point) 'invisible)))
  18553. (outline-show-subtree))
  18554. (cond
  18555. ((eq org-catch-invisible-edits 'show)
  18556. ;; That's it, we do the edit after showing
  18557. (message
  18558. "Unfolding invisible region around point before editing")
  18559. (sit-for 1))
  18560. ((and (eq org-catch-invisible-edits 'smart)
  18561. border-and-ok-direction)
  18562. (message "Unfolding invisible region around point before editing"))
  18563. (t
  18564. ;; Don't do the edit, make the user repeat it in full visibility
  18565. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18566. (defun org-fix-tags-on-the-fly ()
  18567. "Align tags in headline at point.
  18568. Unlike to `org-set-tags', it ignores region and sorting."
  18569. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18570. (org-at-heading-p))
  18571. (let ((org-ignore-region t)
  18572. (org-tags-sort-function nil))
  18573. (org-set-tags nil t))))
  18574. (defun org-delete-backward-char (N)
  18575. "Like `delete-backward-char', insert whitespace at field end in tables.
  18576. When deleting backwards, in tables this function will insert whitespace in
  18577. front of the next \"|\" separator, to keep the table aligned. The table will
  18578. still be marked for re-alignment if the field did fill the entire column,
  18579. because, in this case the deletion might narrow the column."
  18580. (interactive "p")
  18581. (save-match-data
  18582. (org-check-before-invisible-edit 'delete-backward)
  18583. (if (and (org-at-table-p)
  18584. (eq N 1)
  18585. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18586. (looking-at ".*?|"))
  18587. (let ((pos (point))
  18588. (noalign (looking-at "[^|\n\r]* |"))
  18589. (c org-table-may-need-update))
  18590. (backward-delete-char N)
  18591. (unless overwrite-mode
  18592. (skip-chars-forward "^|")
  18593. (insert " ")
  18594. (goto-char (1- pos)))
  18595. ;; noalign: if there were two spaces at the end, this field
  18596. ;; does not determine the width of the column.
  18597. (when noalign (setq org-table-may-need-update c)))
  18598. (backward-delete-char N)
  18599. (org-fix-tags-on-the-fly))))
  18600. (defun org-delete-char (N)
  18601. "Like `delete-char', but insert whitespace at field end in tables.
  18602. When deleting characters, in tables this function will insert whitespace in
  18603. front of the next \"|\" separator, to keep the table aligned. The table will
  18604. still be marked for re-alignment if the field did fill the entire column,
  18605. because, in this case the deletion might narrow the column."
  18606. (interactive "p")
  18607. (save-match-data
  18608. (org-check-before-invisible-edit 'delete)
  18609. (if (and (org-at-table-p)
  18610. (not (bolp))
  18611. (not (= (char-after) ?|))
  18612. (eq N 1))
  18613. (if (looking-at ".*?|")
  18614. (let ((pos (point))
  18615. (noalign (looking-at "[^|\n\r]* |"))
  18616. (c org-table-may-need-update))
  18617. (replace-match
  18618. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18619. (goto-char pos)
  18620. ;; noalign: if there were two spaces at the end, this field
  18621. ;; does not determine the width of the column.
  18622. (when noalign (setq org-table-may-need-update c)))
  18623. (delete-char N))
  18624. (delete-char N)
  18625. (org-fix-tags-on-the-fly))))
  18626. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18627. (put 'org-self-insert-command 'delete-selection
  18628. (lambda ()
  18629. (not (run-hook-with-args-until-success
  18630. 'self-insert-uses-region-functions))))
  18631. (put 'orgtbl-self-insert-command 'delete-selection
  18632. (lambda ()
  18633. (not (run-hook-with-args-until-success
  18634. 'self-insert-uses-region-functions))))
  18635. (put 'org-delete-char 'delete-selection 'supersede)
  18636. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18637. (put 'org-yank 'delete-selection 'yank)
  18638. ;; Make `flyspell-mode' delay after some commands
  18639. (put 'org-self-insert-command 'flyspell-delayed t)
  18640. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18641. (put 'org-delete-char 'flyspell-delayed t)
  18642. (put 'org-delete-backward-char 'flyspell-delayed t)
  18643. ;; Make pabbrev-mode expand after Org mode commands
  18644. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18645. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18646. (defun org-remap (map &rest commands)
  18647. "In MAP, remap the functions given in COMMANDS.
  18648. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18649. (let (new old)
  18650. (while commands
  18651. (setq old (pop commands) new (pop commands))
  18652. (org-defkey map (vector 'remap old) new))))
  18653. (defun org-transpose-words ()
  18654. "Transpose words for Org.
  18655. This uses the `org-mode-transpose-word-syntax-table' syntax
  18656. table, which interprets characters in `org-emphasis-alist' as
  18657. word constituents."
  18658. (interactive)
  18659. (with-syntax-table org-mode-transpose-word-syntax-table
  18660. (call-interactively 'transpose-words)))
  18661. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18662. (when (eq org-enable-table-editor 'optimized)
  18663. ;; If the user wants maximum table support, we need to hijack
  18664. ;; some standard editing functions
  18665. (org-remap org-mode-map
  18666. 'self-insert-command 'org-self-insert-command
  18667. 'delete-char 'org-delete-char
  18668. 'delete-backward-char 'org-delete-backward-char)
  18669. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18670. (defvar org-ctrl-c-ctrl-c-hook nil
  18671. "Hook for functions attaching themselves to `C-c C-c'.
  18672. This can be used to add additional functionality to the C-c C-c
  18673. key which executes context-dependent commands. This hook is run
  18674. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18675. run after the last test.
  18676. Each function will be called with no arguments. The function
  18677. must check if the context is appropriate for it to act. If yes,
  18678. it should do its thing and then return a non-nil value. If the
  18679. context is wrong, just do nothing and return nil.")
  18680. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18681. "Hook for functions attaching themselves to `C-c C-c'.
  18682. This can be used to add additional functionality to the C-c C-c
  18683. key which executes context-dependent commands. This hook is run
  18684. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18685. before the first test.
  18686. Each function will be called with no arguments. The function
  18687. must check if the context is appropriate for it to act. If yes,
  18688. it should do its thing and then return a non-nil value. If the
  18689. context is wrong, just do nothing and return nil.")
  18690. (defvar org-tab-first-hook nil
  18691. "Hook for functions to attach themselves to TAB.
  18692. See `org-ctrl-c-ctrl-c-hook' for more information.
  18693. This hook runs as the first action when TAB is pressed, even before
  18694. `org-cycle' messes around with the `outline-regexp' to cater for
  18695. inline tasks and plain list item folding.
  18696. If any function in this hook returns t, any other actions that
  18697. would have been caused by TAB (such as table field motion or visibility
  18698. cycling) will not occur.")
  18699. (defvar org-tab-after-check-for-table-hook nil
  18700. "Hook for functions to attach themselves to TAB.
  18701. See `org-ctrl-c-ctrl-c-hook' for more information.
  18702. This hook runs after it has been established that the cursor is not in a
  18703. table, but before checking if the cursor is in a headline or if global cycling
  18704. should be done.
  18705. If any function in this hook returns t, not other actions like visibility
  18706. cycling will be done.")
  18707. (defvar org-tab-after-check-for-cycling-hook nil
  18708. "Hook for functions to attach themselves to TAB.
  18709. See `org-ctrl-c-ctrl-c-hook' for more information.
  18710. This hook runs after it has been established that not table field motion and
  18711. not visibility should be done because of current context. This is probably
  18712. the place where a package like yasnippets can hook in.")
  18713. (defvar org-tab-before-tab-emulation-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 every other options for TAB have been exhausted, but
  18717. before indentation and \t insertion takes place.")
  18718. (defvar org-metaleft-hook nil
  18719. "Hook for functions attaching themselves to `M-left'.
  18720. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18721. (defvar org-metaright-hook nil
  18722. "Hook for functions attaching themselves to `M-right'.
  18723. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18724. (defvar org-metaup-hook nil
  18725. "Hook for functions attaching themselves to `M-up'.
  18726. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18727. (defvar org-metadown-hook nil
  18728. "Hook for functions attaching themselves to `M-down'.
  18729. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18730. (defvar org-shiftmetaleft-hook nil
  18731. "Hook for functions attaching themselves to `M-S-left'.
  18732. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18733. (defvar org-shiftmetaright-hook nil
  18734. "Hook for functions attaching themselves to `M-S-right'.
  18735. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18736. (defvar org-shiftmetaup-hook nil
  18737. "Hook for functions attaching themselves to `M-S-up'.
  18738. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18739. (defvar org-shiftmetadown-hook nil
  18740. "Hook for functions attaching themselves to `M-S-down'.
  18741. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18742. (defvar org-metareturn-hook nil
  18743. "Hook for functions attaching themselves to `M-RET'.
  18744. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18745. (defvar org-shiftup-hook nil
  18746. "Hook for functions attaching themselves to `S-up'.
  18747. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18748. (defvar org-shiftup-final-hook nil
  18749. "Hook for functions attaching themselves to `S-up'.
  18750. This one runs after all other options except shift-select have been excluded.
  18751. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18752. (defvar org-shiftdown-hook nil
  18753. "Hook for functions attaching themselves to `S-down'.
  18754. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18755. (defvar org-shiftdown-final-hook nil
  18756. "Hook for functions attaching themselves to `S-down'.
  18757. This one runs after all other options except shift-select have been excluded.
  18758. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18759. (defvar org-shiftleft-hook nil
  18760. "Hook for functions attaching themselves to `S-left'.
  18761. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18762. (defvar org-shiftleft-final-hook nil
  18763. "Hook for functions attaching themselves to `S-left'.
  18764. This one runs after all other options except shift-select have been excluded.
  18765. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18766. (defvar org-shiftright-hook nil
  18767. "Hook for functions attaching themselves to `S-right'.
  18768. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18769. (defvar org-shiftright-final-hook nil
  18770. "Hook for functions attaching themselves to `S-right'.
  18771. This one runs after all other options except shift-select have been excluded.
  18772. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18773. (defun org-modifier-cursor-error ()
  18774. "Throw an error, a modified cursor command was applied in wrong context."
  18775. (user-error "This command is active in special context like tables, headlines or items"))
  18776. (defun org-shiftselect-error ()
  18777. "Throw an error because Shift-Cursor command was applied in wrong context."
  18778. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18779. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18780. (user-error "This command works only in special context like headlines or timestamps")))
  18781. (defun org-call-for-shift-select (cmd)
  18782. (let ((this-command-keys-shift-translated t))
  18783. (call-interactively cmd)))
  18784. (defun org-shifttab (&optional arg)
  18785. "Global visibility cycling or move to previous table field.
  18786. Call `org-table-previous-field' within a table.
  18787. When ARG is nil, cycle globally through visibility states.
  18788. When ARG is a numeric prefix, show contents of this level."
  18789. (interactive "P")
  18790. (cond
  18791. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18792. ((integerp arg)
  18793. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18794. (message "Content view to level: %d" arg)
  18795. (org-content (prefix-numeric-value arg2))
  18796. (org-cycle-show-empty-lines t)
  18797. (setq org-cycle-global-status 'overview)))
  18798. (t (call-interactively 'org-global-cycle))))
  18799. (defun org-shiftmetaleft ()
  18800. "Promote subtree or delete table column.
  18801. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18802. `org-table-delete-column', depending on context. See the
  18803. individual commands for more information."
  18804. (interactive)
  18805. (cond
  18806. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18807. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18808. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18809. ((if (not (org-region-active-p)) (org-at-item-p)
  18810. (save-excursion (goto-char (region-beginning))
  18811. (org-at-item-p)))
  18812. (call-interactively 'org-outdent-item-tree))
  18813. (t (org-modifier-cursor-error))))
  18814. (defun org-shiftmetaright ()
  18815. "Demote subtree or insert table column.
  18816. Calls `org-demote-subtree', `org-indent-item-tree', or
  18817. `org-table-insert-column', depending on context. See the
  18818. individual commands for more information."
  18819. (interactive)
  18820. (cond
  18821. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18822. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18823. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18824. ((if (not (org-region-active-p)) (org-at-item-p)
  18825. (save-excursion (goto-char (region-beginning))
  18826. (org-at-item-p)))
  18827. (call-interactively 'org-indent-item-tree))
  18828. (t (org-modifier-cursor-error))))
  18829. (defun org-shiftmetaup (&optional _arg)
  18830. "Drag the line at point up.
  18831. In a table, kill the current row.
  18832. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18833. but also adjust the previous clocked item in the clock history.
  18834. Everywhere else, drag the line at point up."
  18835. (interactive "P")
  18836. (cond
  18837. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18838. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18839. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18840. (call-interactively 'org-timestamp-up)))
  18841. (t (call-interactively 'org-drag-line-backward))))
  18842. (defun org-shiftmetadown (&optional _arg)
  18843. "Drag the line at point down.
  18844. In a table, insert an empty row at the current line.
  18845. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18846. but also adjust the previous clocked item in the clock history.
  18847. Everywhere else, drag the line at point down."
  18848. (interactive "P")
  18849. (cond
  18850. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18851. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18852. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18853. (call-interactively 'org-timestamp-down)))
  18854. (t (call-interactively 'org-drag-line-forward))))
  18855. (defsubst org-hidden-tree-error ()
  18856. (user-error
  18857. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18858. (defun org-metaleft (&optional _arg)
  18859. "Promote heading, list item at point or move table column left.
  18860. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18861. depending on context. With no specific context, calls the Emacs
  18862. default `backward-word'. See the individual commands for more
  18863. information.
  18864. This function runs the hook `org-metaleft-hook' as a first step,
  18865. and returns at first non-nil value."
  18866. (interactive "P")
  18867. (cond
  18868. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18869. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18870. ((org-with-limited-levels
  18871. (or (org-at-heading-p)
  18872. (and (org-region-active-p)
  18873. (save-excursion
  18874. (goto-char (region-beginning))
  18875. (org-at-heading-p)))))
  18876. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18877. (call-interactively 'org-do-promote))
  18878. ;; At an inline task.
  18879. ((org-at-heading-p)
  18880. (call-interactively 'org-inlinetask-promote))
  18881. ((or (org-at-item-p)
  18882. (and (org-region-active-p)
  18883. (save-excursion
  18884. (goto-char (region-beginning))
  18885. (org-at-item-p))))
  18886. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18887. (call-interactively 'org-outdent-item))
  18888. (t (call-interactively 'backward-word))))
  18889. (defun org-metaright (&optional _arg)
  18890. "Demote heading, list item at point or move table column right.
  18891. In front of a drawer or a block keyword, indent it correctly.
  18892. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18893. `org-indent-drawer' or `org-indent-block' depending on context.
  18894. With no specific context, calls the Emacs default `forward-word'.
  18895. See the individual commands for more information.
  18896. This function runs the hook `org-metaright-hook' as a first step,
  18897. and returns at first non-nil value."
  18898. (interactive "P")
  18899. (cond
  18900. ((run-hook-with-args-until-success 'org-metaright-hook))
  18901. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18902. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18903. ((org-at-block-p) (call-interactively 'org-indent-block))
  18904. ((org-with-limited-levels
  18905. (or (org-at-heading-p)
  18906. (and (org-region-active-p)
  18907. (save-excursion
  18908. (goto-char (region-beginning))
  18909. (org-at-heading-p)))))
  18910. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18911. (call-interactively 'org-do-demote))
  18912. ;; At an inline task.
  18913. ((org-at-heading-p)
  18914. (call-interactively 'org-inlinetask-demote))
  18915. ((or (org-at-item-p)
  18916. (and (org-region-active-p)
  18917. (save-excursion
  18918. (goto-char (region-beginning))
  18919. (org-at-item-p))))
  18920. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18921. (call-interactively 'org-indent-item))
  18922. (t (call-interactively 'forward-word))))
  18923. (defun org-check-for-hidden (what)
  18924. "Check if there are hidden headlines/items in the current visual line.
  18925. WHAT can be either `headlines' or `items'. If the current line is
  18926. an outline or item heading and it has a folded subtree below it,
  18927. this function returns t, nil otherwise."
  18928. (let ((re (cond
  18929. ((eq what 'headlines) org-outline-regexp-bol)
  18930. ((eq what 'items) (org-item-beginning-re))
  18931. (t (error "This should not happen"))))
  18932. beg end)
  18933. (save-excursion
  18934. (catch 'exit
  18935. (unless (org-region-active-p)
  18936. (setq beg (point-at-bol))
  18937. (beginning-of-line 2)
  18938. (while (and (not (eobp)) ;; this is like `next-line'
  18939. (get-char-property (1- (point)) 'invisible))
  18940. (beginning-of-line 2))
  18941. (setq end (point))
  18942. (goto-char beg)
  18943. (goto-char (point-at-eol))
  18944. (setq end (max end (point)))
  18945. (while (re-search-forward re end t)
  18946. (when (get-char-property (match-beginning 0) 'invisible)
  18947. (throw 'exit t))))
  18948. nil))))
  18949. (defun org-metaup (&optional _arg)
  18950. "Move subtree up or move table row up.
  18951. Calls `org-move-subtree-up' or `org-table-move-row' or
  18952. `org-move-item-up', depending on context. See the individual commands
  18953. for more information."
  18954. (interactive "P")
  18955. (cond
  18956. ((run-hook-with-args-until-success 'org-metaup-hook))
  18957. ((org-region-active-p)
  18958. (let* ((a (min (region-beginning) (region-end)))
  18959. (b (1- (max (region-beginning) (region-end))))
  18960. (c (save-excursion (goto-char a)
  18961. (move-beginning-of-line 0)))
  18962. (d (save-excursion (goto-char a)
  18963. (move-end-of-line 0) (point))))
  18964. (transpose-regions a b c d)
  18965. (goto-char c)))
  18966. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18967. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18968. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18969. (t (org-drag-element-backward))))
  18970. (defun org-metadown (&optional _arg)
  18971. "Move subtree down or move table row down.
  18972. Calls `org-move-subtree-down' or `org-table-move-row' or
  18973. `org-move-item-down', depending on context. See the individual
  18974. commands for more information."
  18975. (interactive "P")
  18976. (cond
  18977. ((run-hook-with-args-until-success 'org-metadown-hook))
  18978. ((org-region-active-p)
  18979. (let* ((a (min (region-beginning) (region-end)))
  18980. (b (max (region-beginning) (region-end)))
  18981. (c (save-excursion (goto-char b)
  18982. (move-beginning-of-line 1)))
  18983. (d (save-excursion (goto-char b)
  18984. (move-end-of-line 1) (1+ (point)))))
  18985. (transpose-regions a b c d)
  18986. (goto-char d)))
  18987. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18988. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18989. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18990. (t (org-drag-element-forward))))
  18991. (defun org-shiftup (&optional arg)
  18992. "Increase item in timestamp or increase priority of current headline.
  18993. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18994. depending on context. See the individual commands for more information."
  18995. (interactive "P")
  18996. (cond
  18997. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18998. ((and org-support-shift-select (org-region-active-p))
  18999. (org-call-for-shift-select 'previous-line))
  19000. ((org-at-timestamp-p t)
  19001. (call-interactively (if org-edit-timestamp-down-means-later
  19002. 'org-timestamp-down 'org-timestamp-up)))
  19003. ((and (not (eq org-support-shift-select 'always))
  19004. org-enable-priority-commands
  19005. (org-at-heading-p))
  19006. (call-interactively 'org-priority-up))
  19007. ((and (not org-support-shift-select) (org-at-item-p))
  19008. (call-interactively 'org-previous-item))
  19009. ((org-clocktable-try-shift 'up arg))
  19010. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  19011. (org-support-shift-select
  19012. (org-call-for-shift-select 'previous-line))
  19013. (t (org-shiftselect-error))))
  19014. (defun org-shiftdown (&optional arg)
  19015. "Decrease item in timestamp or decrease priority of current headline.
  19016. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  19017. depending on context. See the individual commands for more information."
  19018. (interactive "P")
  19019. (cond
  19020. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  19021. ((and org-support-shift-select (org-region-active-p))
  19022. (org-call-for-shift-select 'next-line))
  19023. ((org-at-timestamp-p t)
  19024. (call-interactively (if org-edit-timestamp-down-means-later
  19025. 'org-timestamp-up 'org-timestamp-down)))
  19026. ((and (not (eq org-support-shift-select 'always))
  19027. org-enable-priority-commands
  19028. (org-at-heading-p))
  19029. (call-interactively 'org-priority-down))
  19030. ((and (not org-support-shift-select) (org-at-item-p))
  19031. (call-interactively 'org-next-item))
  19032. ((org-clocktable-try-shift 'down arg))
  19033. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19034. (org-support-shift-select
  19035. (org-call-for-shift-select 'next-line))
  19036. (t (org-shiftselect-error))))
  19037. (defun org-shiftright (&optional arg)
  19038. "Cycle the thing at point or in the current line, depending on context.
  19039. Depending on context, this does one of the following:
  19040. - switch a timestamp at point one day into the future
  19041. - on a headline, switch to the next TODO keyword.
  19042. - on an item, switch entire list to the next bullet type
  19043. - on a property line, switch to the next allowed value
  19044. - on a clocktable definition line, move time block into the future"
  19045. (interactive "P")
  19046. (cond
  19047. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19048. ((and org-support-shift-select (org-region-active-p))
  19049. (org-call-for-shift-select 'forward-char))
  19050. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19051. ((and (not (eq org-support-shift-select 'always))
  19052. (org-at-heading-p))
  19053. (let ((org-inhibit-logging
  19054. (not org-treat-S-cursor-todo-selection-as-state-change))
  19055. (org-inhibit-blocking
  19056. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19057. (org-call-with-arg 'org-todo 'right)))
  19058. ((or (and org-support-shift-select
  19059. (not (eq org-support-shift-select 'always))
  19060. (org-at-item-bullet-p))
  19061. (and (not org-support-shift-select) (org-at-item-p)))
  19062. (org-call-with-arg 'org-cycle-list-bullet nil))
  19063. ((and (not (eq org-support-shift-select 'always))
  19064. (org-at-property-p))
  19065. (call-interactively 'org-property-next-allowed-value))
  19066. ((org-clocktable-try-shift 'right arg))
  19067. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19068. (org-support-shift-select
  19069. (org-call-for-shift-select 'forward-char))
  19070. (t (org-shiftselect-error))))
  19071. (defun org-shiftleft (&optional arg)
  19072. "Cycle the thing at point or in the current line, depending on context.
  19073. Depending on context, this does one of the following:
  19074. - switch a timestamp at point one day into the past
  19075. - on a headline, switch to the previous TODO keyword.
  19076. - on an item, switch entire list to the previous bullet type
  19077. - on a property line, switch to the previous allowed value
  19078. - on a clocktable definition line, move time block into the past"
  19079. (interactive "P")
  19080. (cond
  19081. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19082. ((and org-support-shift-select (org-region-active-p))
  19083. (org-call-for-shift-select 'backward-char))
  19084. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19085. ((and (not (eq org-support-shift-select 'always))
  19086. (org-at-heading-p))
  19087. (let ((org-inhibit-logging
  19088. (not org-treat-S-cursor-todo-selection-as-state-change))
  19089. (org-inhibit-blocking
  19090. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19091. (org-call-with-arg 'org-todo 'left)))
  19092. ((or (and org-support-shift-select
  19093. (not (eq org-support-shift-select 'always))
  19094. (org-at-item-bullet-p))
  19095. (and (not org-support-shift-select) (org-at-item-p)))
  19096. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19097. ((and (not (eq org-support-shift-select 'always))
  19098. (org-at-property-p))
  19099. (call-interactively 'org-property-previous-allowed-value))
  19100. ((org-clocktable-try-shift 'left arg))
  19101. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19102. (org-support-shift-select
  19103. (org-call-for-shift-select 'backward-char))
  19104. (t (org-shiftselect-error))))
  19105. (defun org-shiftcontrolright ()
  19106. "Switch to next TODO set."
  19107. (interactive)
  19108. (cond
  19109. ((and org-support-shift-select (org-region-active-p))
  19110. (org-call-for-shift-select 'forward-word))
  19111. ((and (not (eq org-support-shift-select 'always))
  19112. (org-at-heading-p))
  19113. (org-call-with-arg 'org-todo 'nextset))
  19114. (org-support-shift-select
  19115. (org-call-for-shift-select 'forward-word))
  19116. (t (org-shiftselect-error))))
  19117. (defun org-shiftcontrolleft ()
  19118. "Switch to previous TODO set."
  19119. (interactive)
  19120. (cond
  19121. ((and org-support-shift-select (org-region-active-p))
  19122. (org-call-for-shift-select 'backward-word))
  19123. ((and (not (eq org-support-shift-select 'always))
  19124. (org-at-heading-p))
  19125. (org-call-with-arg 'org-todo 'previousset))
  19126. (org-support-shift-select
  19127. (org-call-for-shift-select 'backward-word))
  19128. (t (org-shiftselect-error))))
  19129. (defun org-shiftcontrolup (&optional n)
  19130. "Change timestamps synchronously up in CLOCK log lines.
  19131. Optional argument N tells to change by that many units."
  19132. (interactive "P")
  19133. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19134. (let (org-support-shift-select)
  19135. (org-clock-timestamps-up n))
  19136. (user-error "Not at a clock log")))
  19137. (defun org-shiftcontroldown (&optional n)
  19138. "Change timestamps synchronously down in CLOCK log lines.
  19139. Optional argument N tells to change by that many units."
  19140. (interactive "P")
  19141. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19142. (let (org-support-shift-select)
  19143. (org-clock-timestamps-down n))
  19144. (user-error "Not at a clock log")))
  19145. (defun org-increase-number-at-point (&optional inc)
  19146. "Increment the number at point.
  19147. With an optional prefix numeric argument INC, increment using
  19148. this numeric value."
  19149. (interactive "p")
  19150. (if (not (number-at-point))
  19151. (user-error "Not on a number")
  19152. (unless inc (setq inc 1))
  19153. (let ((pos (point))
  19154. (beg (skip-chars-backward "-+^/*0-9eE."))
  19155. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19156. (setq nap (buffer-substring-no-properties
  19157. (+ pos beg) (+ pos beg end)))
  19158. (delete-region (+ pos beg) (+ pos beg end))
  19159. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19160. (when (org-at-table-p)
  19161. (org-table-align)
  19162. (org-table-end-of-field 1))))
  19163. (defun org-decrease-number-at-point (&optional inc)
  19164. "Decrement the number at point.
  19165. With an optional prefix numeric argument INC, decrement using
  19166. this numeric value."
  19167. (interactive "p")
  19168. (org-increase-number-at-point (- (or inc 1))))
  19169. (defun org-ctrl-c-ret ()
  19170. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19171. (interactive)
  19172. (cond
  19173. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19174. (t (call-interactively 'org-insert-heading))))
  19175. (defun org-find-visible ()
  19176. (let ((s (point)))
  19177. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19178. (get-char-property s 'invisible)))
  19179. s))
  19180. (defun org-find-invisible ()
  19181. (let ((s (point)))
  19182. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19183. (not (get-char-property s 'invisible))))
  19184. s))
  19185. (defun org-copy-visible (beg end)
  19186. "Copy the visible parts of the region."
  19187. (interactive "r")
  19188. (let (snippets s)
  19189. (save-excursion
  19190. (save-restriction
  19191. (narrow-to-region beg end)
  19192. (setq s (goto-char (point-min)))
  19193. (while (not (= (point) (point-max)))
  19194. (goto-char (org-find-invisible))
  19195. (push (buffer-substring s (point)) snippets)
  19196. (setq s (goto-char (org-find-visible))))))
  19197. (kill-new (apply 'concat (nreverse snippets)))))
  19198. (defun org-copy-special ()
  19199. "Copy region in table or copy current subtree.
  19200. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19201. context. See the individual commands for more information."
  19202. (interactive)
  19203. (call-interactively
  19204. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19205. (defun org-cut-special ()
  19206. "Cut region in table or cut current subtree.
  19207. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19208. context. See the individual commands for more information."
  19209. (interactive)
  19210. (call-interactively
  19211. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19212. (defun org-paste-special (arg)
  19213. "Paste rectangular region into table, or past subtree relative to level.
  19214. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19215. See the individual commands for more information."
  19216. (interactive "P")
  19217. (if (org-at-table-p)
  19218. (org-table-paste-rectangle)
  19219. (org-paste-subtree arg)))
  19220. (defun org-edit-special (&optional arg)
  19221. "Call a special editor for the element at point.
  19222. When at a table, call the formula editor with `org-table-edit-formulas'.
  19223. When in a source code block, call `org-edit-src-code'.
  19224. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19225. When in an export block, call `org-edit-export-block'.
  19226. When at an #+INCLUDE keyword, visit the included file.
  19227. When at a footnote reference, call `org-edit-footnote-reference'
  19228. On a link, call `ffap' to visit the link at point.
  19229. Otherwise, return a user error."
  19230. (interactive "P")
  19231. (let ((element (org-element-at-point)))
  19232. (barf-if-buffer-read-only)
  19233. (pcase (org-element-type element)
  19234. (`src-block
  19235. (if (not arg) (org-edit-src-code)
  19236. (let* ((info (org-babel-get-src-block-info))
  19237. (lang (nth 0 info))
  19238. (params (nth 2 info))
  19239. (session (cdr (assq :session params))))
  19240. (if (not session) (org-edit-src-code)
  19241. ;; At a src-block with a session and function called with
  19242. ;; an ARG: switch to the buffer related to the inferior
  19243. ;; process.
  19244. (switch-to-buffer
  19245. (funcall (intern (concat "org-babel-prep-session:" lang))
  19246. session params))))))
  19247. (`keyword
  19248. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19249. (org-open-link-from-string
  19250. (format "[[%s]]"
  19251. (expand-file-name
  19252. (let ((value (org-element-property :value element)))
  19253. (cond ((not (org-string-nw-p value))
  19254. (user-error "No file to edit"))
  19255. ((string-match "\\`\"\\(.*?\\)\"" value)
  19256. (match-string 1 value))
  19257. ((string-match "\\`[^ \t\"]\\S-*" value)
  19258. (match-string 0 value))
  19259. (t (user-error "No valid file specified")))))))
  19260. (user-error "No special environment to edit here")))
  19261. (`table
  19262. (if (eq (org-element-property :type element) 'table.el)
  19263. (org-edit-table.el)
  19264. (call-interactively 'org-table-edit-formulas)))
  19265. ;; Only Org tables contain `table-row' type elements.
  19266. (`table-row (call-interactively 'org-table-edit-formulas))
  19267. (`example-block (org-edit-src-code))
  19268. (`export-block (org-edit-export-block))
  19269. (`fixed-width (org-edit-fixed-width-region))
  19270. (_
  19271. ;; No notable element at point. Though, we may be at a link or
  19272. ;; a footnote reference, which are objects. Thus, scan deeper.
  19273. (let ((context (org-element-context element)))
  19274. (pcase (org-element-type context)
  19275. (`footnote-reference (org-edit-footnote-reference))
  19276. (`inline-src-block (org-edit-inline-src-code))
  19277. (`link (call-interactively #'ffap))
  19278. (_ (user-error "No special environment to edit here"))))))))
  19279. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19280. (defun org-ctrl-c-ctrl-c (&optional arg)
  19281. "Set tags in headline, or update according to changed information at point.
  19282. This command does many different things, depending on context:
  19283. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19284. this is what we do.
  19285. - If the cursor is on a statistics cookie, update it.
  19286. - If the cursor is in a headline, prompt for tags and insert them
  19287. into the current line, aligned to `org-tags-column'. When called
  19288. with prefix arg, realign all tags in the current buffer.
  19289. - If the cursor is in one of the special #+KEYWORD lines, this
  19290. triggers scanning the buffer for these lines and updating the
  19291. information.
  19292. - If the cursor is inside a table, realign the table. This command
  19293. works even if the automatic table editor has been turned off.
  19294. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19295. the entire table.
  19296. - If the cursor is at a footnote reference or definition, jump to
  19297. the corresponding definition or references, respectively.
  19298. - If the cursor is a the beginning of a dynamic block, update it.
  19299. - If the current buffer is a capture buffer, close note and file it.
  19300. - If the cursor is on a <<<target>>>, update radio targets and
  19301. corresponding links in this buffer.
  19302. - If the cursor is on a numbered item in a plain list, renumber the
  19303. ordered list.
  19304. - If the cursor is on a checkbox, toggle it.
  19305. - If the cursor is on a code block, evaluate it. The variable
  19306. `org-confirm-babel-evaluate' can be used to control prompting
  19307. before code block evaluation, by default every code block
  19308. evaluation requires confirmation. Code block evaluation can be
  19309. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19310. (interactive "P")
  19311. (cond
  19312. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19313. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19314. (org-remove-occur-highlights)
  19315. (message "Temporary highlights/overlays removed from current buffer"))
  19316. ((and (local-variable-p 'org-finish-function)
  19317. (fboundp org-finish-function))
  19318. (funcall org-finish-function))
  19319. ((org-babel-hash-at-point))
  19320. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19321. (t
  19322. (let* ((context
  19323. (org-element-lineage
  19324. (org-element-context)
  19325. ;; Limit to supported contexts.
  19326. '(babel-call clock dynamic-block footnote-definition
  19327. footnote-reference inline-babel-call inline-src-block
  19328. inlinetask item keyword node-property paragraph
  19329. plain-list property-drawer radio-target src-block
  19330. statistics-cookie table table-cell table-row
  19331. timestamp)
  19332. t))
  19333. (type (org-element-type context)))
  19334. ;; For convenience: at the first line of a paragraph on the same
  19335. ;; line as an item, apply function on that item instead.
  19336. (when (eq type 'paragraph)
  19337. (let ((parent (org-element-property :parent context)))
  19338. (when (and (eq (org-element-type parent) 'item)
  19339. (= (line-beginning-position)
  19340. (org-element-property :begin parent)))
  19341. (setq context parent)
  19342. (setq type 'item))))
  19343. ;; Act according to type of element or object at point.
  19344. ;;
  19345. ;; Do nothing on a blank line, except if it is contained in
  19346. ;; a src block. Hence, we first check if point is in such
  19347. ;; a block and then if it is at a blank line.
  19348. (pcase type
  19349. ((or `inline-src-block `src-block)
  19350. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19351. (org-babel-eval-wipe-error-buffer)
  19352. (org-babel-execute-src-block
  19353. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19354. ((guard (org-match-line "[ \t]*$"))
  19355. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19356. (user-error
  19357. (substitute-command-keys
  19358. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19359. ((or `babel-call `inline-babel-call)
  19360. (let ((info (org-babel-lob-get-info context)))
  19361. (when info (org-babel-execute-src-block nil info))))
  19362. (`clock (org-clock-update-time-maybe))
  19363. (`dynamic-block
  19364. (save-excursion
  19365. (goto-char (org-element-property :post-affiliated context))
  19366. (org-update-dblock)))
  19367. (`footnote-definition
  19368. (goto-char (org-element-property :post-affiliated context))
  19369. (call-interactively 'org-footnote-action))
  19370. (`footnote-reference (call-interactively #'org-footnote-action))
  19371. ((or `headline `inlinetask)
  19372. (save-excursion (goto-char (org-element-property :begin context))
  19373. (call-interactively #'org-set-tags)))
  19374. (`item
  19375. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19376. ;; unconditionally, whereas `C-u' will toggle its presence.
  19377. ;; Without a universal argument, if the item has a checkbox,
  19378. ;; toggle it. Otherwise repair the list.
  19379. (let* ((box (org-element-property :checkbox context))
  19380. (struct (org-element-property :structure context))
  19381. (old-struct (copy-tree struct))
  19382. (parents (org-list-parents-alist struct))
  19383. (prevs (org-list-prevs-alist struct))
  19384. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19385. (org-list-set-checkbox
  19386. (org-element-property :begin context) struct
  19387. (cond ((equal arg '(16)) "[-]")
  19388. ((and (not box) (equal arg '(4))) "[ ]")
  19389. ((or (not box) (equal arg '(4))) nil)
  19390. ((eq box 'on) "[ ]")
  19391. (t "[X]")))
  19392. ;; Mimic `org-list-write-struct' but with grabbing a return
  19393. ;; value from `org-list-struct-fix-box'.
  19394. (org-list-struct-fix-ind struct parents 2)
  19395. (org-list-struct-fix-item-end struct)
  19396. (org-list-struct-fix-bul struct prevs)
  19397. (org-list-struct-fix-ind struct parents)
  19398. (let ((block-item
  19399. (org-list-struct-fix-box struct parents prevs orderedp)))
  19400. (if (and box (equal struct old-struct))
  19401. (if (equal arg '(16))
  19402. (message "Checkboxes already reset")
  19403. (user-error "Cannot toggle this checkbox: %s"
  19404. (if (eq box 'on)
  19405. "all subitems checked"
  19406. "unchecked subitems")))
  19407. (org-list-struct-apply-struct struct old-struct)
  19408. (org-update-checkbox-count-maybe))
  19409. (when block-item
  19410. (message "Checkboxes were removed due to empty box at line %d"
  19411. (org-current-line block-item))))))
  19412. (`keyword
  19413. (let ((org-inhibit-startup-visibility-stuff t)
  19414. (org-startup-align-all-tables nil))
  19415. (when (boundp 'org-table-coordinate-overlays)
  19416. (mapc #'delete-overlay org-table-coordinate-overlays)
  19417. (setq org-table-coordinate-overlays nil))
  19418. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19419. (message "Local setup has been refreshed"))
  19420. (`plain-list
  19421. ;; At a plain list, with a double C-u argument, set
  19422. ;; checkboxes of each item to "[-]", whereas a single one
  19423. ;; will toggle their presence according to the state of the
  19424. ;; first item in the list. Without an argument, repair the
  19425. ;; list.
  19426. (let* ((begin (org-element-property :contents-begin context))
  19427. (beginm (move-marker (make-marker) begin))
  19428. (struct (org-element-property :structure context))
  19429. (old-struct (copy-tree struct))
  19430. (first-box (save-excursion
  19431. (goto-char begin)
  19432. (looking-at org-list-full-item-re)
  19433. (match-string-no-properties 3)))
  19434. (new-box (cond ((equal arg '(16)) "[-]")
  19435. ((equal arg '(4)) (unless first-box "[ ]"))
  19436. ((equal first-box "[X]") "[ ]")
  19437. (t "[X]"))))
  19438. (cond
  19439. (arg
  19440. (dolist (pos
  19441. (org-list-get-all-items
  19442. begin struct (org-list-prevs-alist struct)))
  19443. (org-list-set-checkbox pos struct new-box)))
  19444. ((and first-box (eq (point) begin))
  19445. ;; For convenience, when point is at bol on the first
  19446. ;; item of the list and no argument is provided, simply
  19447. ;; toggle checkbox of that item, if any.
  19448. (org-list-set-checkbox begin struct new-box)))
  19449. (org-list-write-struct
  19450. struct (org-list-parents-alist struct) old-struct)
  19451. (org-update-checkbox-count-maybe)
  19452. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19453. ((or `property-drawer `node-property)
  19454. (call-interactively #'org-property-action))
  19455. (`radio-target
  19456. (call-interactively #'org-update-radio-target-regexp))
  19457. (`statistics-cookie
  19458. (call-interactively #'org-update-statistics-cookies))
  19459. ((or `table `table-cell `table-row)
  19460. ;; At a table, recalculate every field and align it. Also
  19461. ;; send the table if necessary. If the table has
  19462. ;; a `table.el' type, just give up. At a table row or cell,
  19463. ;; maybe recalculate line but always align table.
  19464. (if (eq (org-element-property :type context) 'table.el)
  19465. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19466. Use `\\[org-edit-special]' to edit table.el tables"))
  19467. (let ((org-enable-table-editor t))
  19468. (if (or (eq type 'table)
  19469. ;; Check if point is at a TBLFM line.
  19470. (and (eq type 'table-row)
  19471. (= (point) (org-element-property :end context))))
  19472. (save-excursion
  19473. (if (org-at-TBLFM-p)
  19474. (progn (require 'org-table)
  19475. (org-table-calc-current-TBLFM))
  19476. (goto-char (org-element-property :contents-begin context))
  19477. (org-call-with-arg 'org-table-recalculate (or arg t))
  19478. (orgtbl-send-table 'maybe)))
  19479. (org-table-maybe-eval-formula)
  19480. (cond (arg (call-interactively #'org-table-recalculate))
  19481. ((org-table-maybe-recalculate-line))
  19482. (t (org-table-align)))))))
  19483. (`timestamp (org-timestamp-change 0 'day))
  19484. ((and `nil (guard (org-at-heading-p)))
  19485. ;; When point is on an unsupported object type, we can miss
  19486. ;; the fact that it also is at a heading. Handle it here.
  19487. (call-interactively #'org-set-tags))
  19488. ((guard
  19489. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19490. (_
  19491. (user-error
  19492. (substitute-command-keys
  19493. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19494. (defun org-mode-restart ()
  19495. (interactive)
  19496. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19497. (funcall major-mode)
  19498. (hack-local-variables)
  19499. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19500. (org-indent-mode -1)))
  19501. (message "%s restarted" major-mode))
  19502. (defun org-kill-note-or-show-branches ()
  19503. "Abort storing current note, or call `outline-show-branches'."
  19504. (interactive)
  19505. (if (not org-finish-function)
  19506. (progn
  19507. (outline-hide-subtree)
  19508. (call-interactively 'outline-show-branches))
  19509. (let ((org-note-abort t))
  19510. (funcall org-finish-function))))
  19511. (defun org-delete-indentation (&optional arg)
  19512. "Join current line to previous and fix whitespace at join.
  19513. If previous line is a headline add to headline title. Otherwise
  19514. the function calls `delete-indentation'.
  19515. With a non-nil optional argument, join it to the following one."
  19516. (interactive "*P")
  19517. (if (save-excursion
  19518. (beginning-of-line (if arg 1 0))
  19519. (let ((case-fold-search nil))
  19520. (looking-at org-complex-heading-regexp)))
  19521. ;; At headline.
  19522. (let ((tags-column (when (match-beginning 5)
  19523. (save-excursion (goto-char (match-beginning 5))
  19524. (current-column))))
  19525. (string (concat " " (progn (when arg (forward-line 1))
  19526. (org-trim (delete-and-extract-region
  19527. (line-beginning-position)
  19528. (line-end-position)))))))
  19529. (unless (bobp) (delete-region (point) (1- (point))))
  19530. (goto-char (or (match-end 4)
  19531. (match-beginning 5)
  19532. (match-end 0)))
  19533. (skip-chars-backward " \t")
  19534. (save-excursion (insert string))
  19535. ;; Adjust alignment of tags.
  19536. (cond
  19537. ((not tags-column)) ;no tags
  19538. (org-auto-align-tags (org-set-tags nil t))
  19539. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19540. (delete-indentation arg)))
  19541. (defun org-open-line (n)
  19542. "Insert a new row in tables, call `open-line' elsewhere.
  19543. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19544. As a special case, when a document starts with a table, allow to
  19545. call `open-line' on the very first character."
  19546. (interactive "*p")
  19547. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19548. (org-table-insert-row)
  19549. (open-line n)))
  19550. (defun org-return (&optional indent)
  19551. "Goto next table row or insert a newline.
  19552. Calls `org-table-next-row' or `newline', depending on context.
  19553. When optional INDENT argument is non-nil, call
  19554. `newline-and-indent' instead of `newline'.
  19555. When `org-return-follows-link' is non-nil and point is on
  19556. a timestamp or a link, call `org-open-at-point'. However, it
  19557. will not happen if point is in a table or on a \"dead\"
  19558. object (e.g., within a comment). In these case, you need to use
  19559. `org-open-at-point' directly."
  19560. (interactive)
  19561. (let ((context (if org-return-follows-link (org-element-context)
  19562. (org-element-at-point))))
  19563. (cond
  19564. ;; In a table, call `org-table-next-row'.
  19565. ((or (and (eq (org-element-type context) 'table)
  19566. (>= (point) (org-element-property :contents-begin context))
  19567. (< (point) (org-element-property :contents-end context)))
  19568. (org-element-lineage context '(table-row table-cell) t))
  19569. (org-table-justify-field-maybe)
  19570. (call-interactively #'org-table-next-row))
  19571. ;; On a link or a timestamp, call `org-open-at-point' if
  19572. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19573. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19574. ((and org-return-follows-link
  19575. (or (org-in-regexp org-ts-regexp-both nil t)
  19576. (org-in-regexp org-tsr-regexp-both nil t)
  19577. (org-in-regexp org-any-link-re nil t)))
  19578. (call-interactively #'org-open-at-point))
  19579. ;; Insert newline in heading, but preserve tags.
  19580. ((and (not (bolp))
  19581. (save-excursion (beginning-of-line)
  19582. (let ((case-fold-search nil))
  19583. (looking-at org-complex-heading-regexp))))
  19584. ;; At headline. Split line. However, if point is on keyword,
  19585. ;; priority cookie or tags, do not break any of them: add
  19586. ;; a newline after the headline instead.
  19587. (let ((tags-column (and (match-beginning 5)
  19588. (save-excursion (goto-char (match-beginning 5))
  19589. (current-column))))
  19590. (string
  19591. (when (and (match-end 4) (org-point-in-group (point) 4))
  19592. (delete-and-extract-region (point) (match-end 4)))))
  19593. ;; Adjust tag alignment.
  19594. (cond
  19595. ((not (and tags-column string)))
  19596. (org-auto-align-tags (org-set-tags nil t))
  19597. (t (org--align-tags-here tags-column))) ;preserve tags column
  19598. (end-of-line)
  19599. (org-show-entry)
  19600. (if indent (newline-and-indent) (newline))
  19601. (when string (save-excursion (insert (org-trim string))))))
  19602. ;; In a list, make sure indenting keeps trailing text within.
  19603. ((and indent
  19604. (not (eolp))
  19605. (org-element-lineage context '(item)))
  19606. (let ((trailing-data
  19607. (delete-and-extract-region (point) (line-end-position))))
  19608. (newline-and-indent)
  19609. (save-excursion (insert trailing-data))))
  19610. (t (if indent (newline-and-indent) (newline))))))
  19611. (defun org-return-indent ()
  19612. "Goto next table row or insert a newline and indent.
  19613. Calls `org-table-next-row' or `newline-and-indent', depending on
  19614. context. See the individual commands for more information."
  19615. (interactive)
  19616. (org-return t))
  19617. (defun org-ctrl-c-star ()
  19618. "Compute table, or change heading status of lines.
  19619. Calls `org-table-recalculate' or `org-toggle-heading',
  19620. depending on context."
  19621. (interactive)
  19622. (cond
  19623. ((org-at-table-p)
  19624. (call-interactively 'org-table-recalculate))
  19625. (t
  19626. ;; Convert all lines in region to list items
  19627. (call-interactively 'org-toggle-heading))))
  19628. (defun org-ctrl-c-minus ()
  19629. "Insert separator line in table or modify bullet status of line.
  19630. Also turns a plain line or a region of lines into list items.
  19631. Calls `org-table-insert-hline', `org-toggle-item', or
  19632. `org-cycle-list-bullet', depending on context."
  19633. (interactive)
  19634. (cond
  19635. ((org-at-table-p)
  19636. (call-interactively 'org-table-insert-hline))
  19637. ((org-region-active-p)
  19638. (call-interactively 'org-toggle-item))
  19639. ((org-in-item-p)
  19640. (call-interactively 'org-cycle-list-bullet))
  19641. (t
  19642. (call-interactively 'org-toggle-item))))
  19643. (defun org-toggle-heading (&optional nstars)
  19644. "Convert headings to normal text, or items or text to headings.
  19645. If there is no active region, only convert the current line.
  19646. With a `\\[universal-argument]' prefix, convert the whole list at
  19647. point into heading.
  19648. In a region:
  19649. - If the first non blank line is a headline, remove the stars
  19650. from all headlines in the region.
  19651. - If it is a normal line, turn each and every normal line (i.e.,
  19652. not an heading or an item) in the region into headings. If you
  19653. want to convert only the first line of this region, use one
  19654. universal prefix argument.
  19655. - If it is a plain list item, turn all plain list items into headings.
  19656. When converting a line into a heading, the number of stars is chosen
  19657. such that the lines become children of the current entry. However,
  19658. when a numeric prefix argument is given, its value determines the
  19659. number of stars to add."
  19660. (interactive "P")
  19661. (let ((skip-blanks
  19662. (function
  19663. ;; Return beginning of first non-blank line, starting from
  19664. ;; line at POS.
  19665. (lambda (pos)
  19666. (save-excursion
  19667. (goto-char pos)
  19668. (while (org-at-comment-p) (forward-line))
  19669. (skip-chars-forward " \r\t\n")
  19670. (point-at-bol)))))
  19671. beg end toggled)
  19672. ;; Determine boundaries of changes. If a universal prefix has
  19673. ;; been given, put the list in a region. If region ends at a bol,
  19674. ;; do not consider the last line to be in the region.
  19675. (when (and current-prefix-arg (org-at-item-p))
  19676. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19677. (org-mark-element))
  19678. (if (org-region-active-p)
  19679. (setq beg (funcall skip-blanks (region-beginning))
  19680. end (copy-marker (save-excursion
  19681. (goto-char (region-end))
  19682. (if (bolp) (point) (point-at-eol)))))
  19683. (setq beg (funcall skip-blanks (point-at-bol))
  19684. end (copy-marker (point-at-eol))))
  19685. ;; Ensure inline tasks don't count as headings.
  19686. (org-with-limited-levels
  19687. (save-excursion
  19688. (goto-char beg)
  19689. (cond
  19690. ;; Case 1. Started at an heading: de-star headings.
  19691. ((org-at-heading-p)
  19692. (while (< (point) end)
  19693. (when (org-at-heading-p t)
  19694. (looking-at org-outline-regexp) (replace-match "")
  19695. (setq toggled t))
  19696. (forward-line)))
  19697. ;; Case 2. Started at an item: change items into headlines.
  19698. ;; One star will be added by `org-list-to-subtree'.
  19699. ((org-at-item-p)
  19700. (while (< (point) end)
  19701. (when (org-at-item-p)
  19702. ;; Pay attention to cases when region ends before list.
  19703. (let* ((struct (org-list-struct))
  19704. (list-end
  19705. (min (org-list-get-bottom-point struct) (1+ end))))
  19706. (save-restriction
  19707. (narrow-to-region (point) list-end)
  19708. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19709. (setq toggled t))
  19710. (forward-line)))
  19711. ;; Case 3. Started at normal text: make every line an heading,
  19712. ;; skipping headlines and items.
  19713. (t (let* ((stars
  19714. (make-string
  19715. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19716. (add-stars
  19717. (cond (nstars "") ; stars from prefix only
  19718. ((equal stars "") "*") ; before first heading
  19719. (org-odd-levels-only "**") ; inside heading, odd
  19720. (t "*"))) ; inside heading, oddeven
  19721. (rpl (concat stars add-stars " "))
  19722. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19723. (while (< (point) (if (equal nstars '(4)) lend end))
  19724. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19725. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19726. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19727. (forward-line)))))))
  19728. (unless toggled (message "Cannot toggle heading from here"))))
  19729. (defun org-meta-return (&optional _arg)
  19730. "Insert a new heading or wrap a region in a table.
  19731. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19732. on context. See the individual commands for more information."
  19733. (interactive)
  19734. (org-check-before-invisible-edit 'insert)
  19735. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19736. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19737. #'org-insert-heading))))
  19738. ;;; Menu entries
  19739. (defsubst org-in-subtree-not-table-p ()
  19740. "Are we in a subtree and not in a table?"
  19741. (and (not (org-before-first-heading-p))
  19742. (not (org-at-table-p))))
  19743. ;; Define the Org mode menus
  19744. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19745. '("Tbl"
  19746. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19747. ["Next Field" org-cycle (org-at-table-p)]
  19748. ["Previous Field" org-shifttab (org-at-table-p)]
  19749. ["Next Row" org-return (org-at-table-p)]
  19750. "--"
  19751. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19752. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19753. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19754. "--"
  19755. ("Column"
  19756. ["Move Column Left" org-metaleft (org-at-table-p)]
  19757. ["Move Column Right" org-metaright (org-at-table-p)]
  19758. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19759. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19760. ("Row"
  19761. ["Move Row Up" org-metaup (org-at-table-p)]
  19762. ["Move Row Down" org-metadown (org-at-table-p)]
  19763. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19764. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19765. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19766. "--"
  19767. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19768. ("Rectangle"
  19769. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19770. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19771. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19772. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19773. "--"
  19774. ("Calculate"
  19775. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19776. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19777. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19778. "--"
  19779. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19780. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19781. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19782. "--"
  19783. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19784. "--"
  19785. ["Sum Column/Rectangle" org-table-sum
  19786. (or (org-at-table-p) (org-region-active-p))]
  19787. ["Which Column?" org-table-current-column (org-at-table-p)])
  19788. ["Debug Formulas"
  19789. org-table-toggle-formula-debugger
  19790. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19791. ["Show Col/Row Numbers"
  19792. org-table-toggle-coordinate-overlays
  19793. :style toggle
  19794. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19795. "--"
  19796. ["Create" org-table-create (and (not (org-at-table-p))
  19797. org-enable-table-editor)]
  19798. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19799. ["Import from File" org-table-import (not (org-at-table-p))]
  19800. ["Export to File" org-table-export (org-at-table-p)]
  19801. "--"
  19802. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19803. "--"
  19804. ("Plot"
  19805. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19806. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19807. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19808. '("Org"
  19809. ("Show/Hide"
  19810. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19811. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19812. ["Sparse Tree..." org-sparse-tree t]
  19813. ["Reveal Context" org-reveal t]
  19814. ["Show All" outline-show-all t]
  19815. "--"
  19816. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19817. "--"
  19818. ["New Heading" org-insert-heading t]
  19819. ("Navigate Headings"
  19820. ["Up" outline-up-heading t]
  19821. ["Next" outline-next-visible-heading t]
  19822. ["Previous" outline-previous-visible-heading t]
  19823. ["Next Same Level" outline-forward-same-level t]
  19824. ["Previous Same Level" outline-backward-same-level t]
  19825. "--"
  19826. ["Jump" org-goto t])
  19827. ("Edit Structure"
  19828. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19829. "--"
  19830. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19831. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19832. "--"
  19833. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19834. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19835. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19836. "--"
  19837. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19838. "--"
  19839. ["Copy visible text" org-copy-visible t]
  19840. "--"
  19841. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19842. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19843. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19844. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19845. "--"
  19846. ["Sort Region/Children" org-sort t]
  19847. "--"
  19848. ["Convert to odd levels" org-convert-to-odd-levels t]
  19849. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19850. ("Editing"
  19851. ["Emphasis..." org-emphasize t]
  19852. ["Edit Source Example" org-edit-special t]
  19853. "--"
  19854. ["Footnote new/jump" org-footnote-action t]
  19855. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19856. ("Archive"
  19857. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19858. "--"
  19859. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19860. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19861. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19862. )
  19863. "--"
  19864. ("Hyperlinks"
  19865. ["Store Link (Global)" org-store-link t]
  19866. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19867. ["Insert Link" org-insert-link t]
  19868. ["Follow Link" org-open-at-point t]
  19869. "--"
  19870. ["Next link" org-next-link t]
  19871. ["Previous link" org-previous-link t]
  19872. "--"
  19873. ["Descriptive Links"
  19874. org-toggle-link-display
  19875. :style radio
  19876. :selected org-descriptive-links
  19877. ]
  19878. ["Literal Links"
  19879. org-toggle-link-display
  19880. :style radio
  19881. :selected (not org-descriptive-links)])
  19882. "--"
  19883. ("TODO Lists"
  19884. ["TODO/DONE/-" org-todo t]
  19885. ("Select keyword"
  19886. ["Next keyword" org-shiftright (org-at-heading-p)]
  19887. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19888. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19889. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19890. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19891. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19892. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19893. "--"
  19894. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19895. :selected org-enforce-todo-dependencies :style toggle :active t]
  19896. "Settings for tree at point"
  19897. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19898. :selected (org-entry-get nil "ORDERED")
  19899. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19900. ["Do Children parallel" org-toggle-ordered-property :style radio
  19901. :selected (not (org-entry-get nil "ORDERED"))
  19902. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19903. "--"
  19904. ["Set Priority" org-priority t]
  19905. ["Priority Up" org-shiftup t]
  19906. ["Priority Down" org-shiftdown t]
  19907. "--"
  19908. ["Get news from all feeds" org-feed-update-all t]
  19909. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19910. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19911. ("TAGS and Properties"
  19912. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19913. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19914. "--"
  19915. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19916. ["Column view of properties" org-columns t]
  19917. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19918. ("Dates and Scheduling"
  19919. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19920. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19921. ("Change Date"
  19922. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19923. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19924. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19925. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19926. ["Compute Time Range" org-evaluate-time-range t]
  19927. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19928. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19929. "--"
  19930. ["Custom time format" org-toggle-time-stamp-overlays
  19931. :style radio :selected org-display-custom-times]
  19932. "--"
  19933. ["Goto Calendar" org-goto-calendar t]
  19934. ["Date from Calendar" org-date-from-calendar t]
  19935. "--"
  19936. ["Start/Restart Timer" org-timer-start t]
  19937. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19938. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19939. ["Insert Timer String" org-timer t]
  19940. ["Insert Timer Item" org-timer-item t])
  19941. ("Logging work"
  19942. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19943. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19944. ["Clock out" org-clock-out t]
  19945. ["Clock cancel" org-clock-cancel t]
  19946. "--"
  19947. ["Mark as default task" org-clock-mark-default-task t]
  19948. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19949. ["Goto running clock" org-clock-goto t]
  19950. "--"
  19951. ["Display times" org-clock-display t]
  19952. ["Create clock table" org-clock-report t]
  19953. "--"
  19954. ["Record DONE time"
  19955. (progn (setq org-log-done (not org-log-done))
  19956. (message "Switching to %s will %s record a timestamp"
  19957. (car org-done-keywords)
  19958. (if org-log-done "automatically" "not")))
  19959. :style toggle :selected org-log-done])
  19960. "--"
  19961. ["Agenda Command..." org-agenda t]
  19962. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19963. ("File List for Agenda")
  19964. ("Special views current file"
  19965. ["TODO Tree" org-show-todo-tree t]
  19966. ["Check Deadlines" org-check-deadlines t]
  19967. ["Timeline" org-timeline t]
  19968. ["Tags/Property tree" org-match-sparse-tree t])
  19969. "--"
  19970. ["Export/Publish..." org-export-dispatch t]
  19971. ("LaTeX"
  19972. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19973. :selected org-cdlatex-mode]
  19974. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19975. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19976. ["Modify math symbol" org-cdlatex-math-modify
  19977. (org-inside-LaTeX-fragment-p)]
  19978. ["Insert citation" org-reftex-citation t])
  19979. "--"
  19980. ("MobileOrg"
  19981. ["Push Files and Views" org-mobile-push t]
  19982. ["Get Captured and Flagged" org-mobile-pull t]
  19983. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19984. "--"
  19985. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19986. "--"
  19987. ("Documentation"
  19988. ["Show Version" org-version t]
  19989. ["Info Documentation" org-info t])
  19990. ("Customize"
  19991. ["Browse Org Group" org-customize t]
  19992. "--"
  19993. ["Expand This Menu" org-create-customize-menu
  19994. (fboundp 'customize-menu-create)])
  19995. ["Send bug report" org-submit-bug-report t]
  19996. "--"
  19997. ("Refresh/Reload"
  19998. ["Refresh setup current buffer" org-mode-restart t]
  19999. ["Reload Org (after update)" org-reload t]
  20000. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20001. ))
  20002. (defun org-info (&optional node)
  20003. "Read documentation for Org in the info system.
  20004. With optional NODE, go directly to that node."
  20005. (interactive)
  20006. (info (format "(org)%s" (or node ""))))
  20007. ;;;###autoload
  20008. (defun org-submit-bug-report ()
  20009. "Submit a bug report on Org via mail.
  20010. Don't hesitate to report any problems or inaccurate documentation.
  20011. If you don't have setup sending mail from (X)Emacs, please copy the
  20012. output buffer into your mail program, as it gives us important
  20013. information about your Org version and configuration."
  20014. (interactive)
  20015. (require 'reporter)
  20016. (defvar reporter-prompt-for-summary-p)
  20017. (org-load-modules-maybe)
  20018. (org-require-autoloaded-modules)
  20019. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20020. (reporter-submit-bug-report
  20021. "emacs-orgmode@gnu.org"
  20022. (org-version nil 'full)
  20023. (let (list)
  20024. (save-window-excursion
  20025. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20026. (delete-other-windows)
  20027. (erase-buffer)
  20028. (insert "You are about to submit a bug report to the Org mailing list.
  20029. We would like to add your full Org and Outline configuration to the
  20030. bug report. This greatly simplifies the work of the maintainer and
  20031. other experts on the mailing list.
  20032. HOWEVER, some variables you have customized may contain private
  20033. information. The names of customers, colleagues, or friends, might
  20034. appear in the form of file names, tags, todo states, or search strings.
  20035. If you answer yes to the prompt, you might want to check and remove
  20036. such private information before sending the email.")
  20037. (add-text-properties (point-min) (point-max) '(face org-warning))
  20038. (when (yes-or-no-p "Include your Org configuration ")
  20039. (mapatoms
  20040. (lambda (v)
  20041. (and (boundp v)
  20042. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20043. (or (and (symbol-value v)
  20044. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20045. (and
  20046. (get v 'custom-type) (get v 'standard-value)
  20047. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20048. (push v list)))))
  20049. (kill-buffer (get-buffer "*Warn about privacy*"))
  20050. list))
  20051. nil nil
  20052. "Remember to cover the basics, that is, what you expected to happen and
  20053. what in fact did happen. You don't know how to make a good report? See
  20054. http://orgmode.org/manual/Feedback.html#Feedback
  20055. Your bug report will be posted to the Org mailing list.
  20056. ------------------------------------------------------------------------")
  20057. (save-excursion
  20058. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20059. (replace-match "\\1Bug: \\3 [\\2]")))))
  20060. (defun org-install-agenda-files-menu ()
  20061. (let ((bl (buffer-list)))
  20062. (save-excursion
  20063. (while bl
  20064. (set-buffer (pop bl))
  20065. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20066. (when (derived-mode-p 'org-mode)
  20067. (easy-menu-change
  20068. '("Org") "File List for Agenda"
  20069. (append
  20070. (list
  20071. ["Edit File List" (org-edit-agenda-file-list) t]
  20072. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20073. ["Remove Current File from List" org-remove-file t]
  20074. ["Cycle through agenda files" org-cycle-agenda-files t]
  20075. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20076. "--")
  20077. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20078. ;;;; Documentation
  20079. (defun org-require-autoloaded-modules ()
  20080. (interactive)
  20081. (mapc #'require
  20082. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20083. org-table org-timer)))
  20084. ;;;###autoload
  20085. (defun org-reload (&optional uncompiled)
  20086. "Reload all org lisp files.
  20087. With prefix arg UNCOMPILED, load the uncompiled versions."
  20088. (interactive "P")
  20089. (require 'loadhist)
  20090. (let* ((org-dir (org-find-library-dir "org"))
  20091. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20092. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20093. (remove-re (format "\\`%s\\'"
  20094. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20095. (feats (delete-dups
  20096. (mapcar 'file-name-sans-extension
  20097. (mapcar 'file-name-nondirectory
  20098. (delq nil
  20099. (mapcar 'feature-file
  20100. features))))))
  20101. (lfeat (append
  20102. (sort
  20103. (setq feats
  20104. (delq nil (mapcar
  20105. (lambda (f)
  20106. (if (and (string-match feature-re f)
  20107. (not (string-match remove-re f)))
  20108. f nil))
  20109. feats)))
  20110. 'string-lessp)
  20111. (list "org-version" "org")))
  20112. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20113. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20114. load-uncore load-misses)
  20115. (setq load-misses
  20116. (delq 't
  20117. (mapcar (lambda (f)
  20118. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20119. (and (string= org-dir contrib-dir)
  20120. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20121. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20122. (add-to-list 'load-uncore f 'append)
  20123. 't)
  20124. f))
  20125. lfeat)))
  20126. (when load-uncore
  20127. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20128. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20129. (if load-misses
  20130. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20131. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20132. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20133. ;;;###autoload
  20134. (defun org-customize ()
  20135. "Call the customize function with org as argument."
  20136. (interactive)
  20137. (org-load-modules-maybe)
  20138. (org-require-autoloaded-modules)
  20139. (customize-browse 'org))
  20140. (defun org-create-customize-menu ()
  20141. "Create a full customization menu for Org mode, insert it into the menu."
  20142. (interactive)
  20143. (org-load-modules-maybe)
  20144. (org-require-autoloaded-modules)
  20145. (if (fboundp 'customize-menu-create)
  20146. (progn
  20147. (easy-menu-change
  20148. '("Org") "Customize"
  20149. `(["Browse Org group" org-customize t]
  20150. "--"
  20151. ,(customize-menu-create 'org)
  20152. ["Set" Custom-set t]
  20153. ["Save" Custom-save t]
  20154. ["Reset to Current" Custom-reset-current t]
  20155. ["Reset to Saved" Custom-reset-saved t]
  20156. ["Reset to Standard Settings" Custom-reset-standard t]))
  20157. (message "\"Org\"-menu now contains full customization menu"))
  20158. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20159. ;;;; Miscellaneous stuff
  20160. ;;; Generally useful functions
  20161. (defun org-get-at-eol (property n)
  20162. "Get text property PROPERTY at the end of line less N characters."
  20163. (get-text-property (- (point-at-eol) n) property))
  20164. (defun org-find-text-property-in-string (prop s)
  20165. "Return the first non-nil value of property PROP in string S."
  20166. (or (get-text-property 0 prop s)
  20167. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20168. prop s)))
  20169. (defun org-display-warning (message)
  20170. "Display the given MESSAGE as a warning."
  20171. (display-warning 'org message :warning))
  20172. (defun org-eval (form)
  20173. "Eval FORM and return result."
  20174. (condition-case error
  20175. (eval form)
  20176. (error (format "%%![Error: %s]" error))))
  20177. (defun org-in-clocktable-p ()
  20178. "Check if the cursor is in a clocktable."
  20179. (let ((pos (point)) start)
  20180. (save-excursion
  20181. (end-of-line 1)
  20182. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20183. (setq start (match-beginning 0))
  20184. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20185. (>= (match-end 0) pos)
  20186. start))))
  20187. (defun org-in-verbatim-emphasis ()
  20188. (save-match-data
  20189. (and (org-in-regexp org-emph-re 2)
  20190. (>= (point) (match-beginning 3))
  20191. (<= (point) (match-end 4))
  20192. (member (match-string 3) '("=" "~")))))
  20193. (defun org-overlay-display (ovl text &optional face evap)
  20194. "Make overlay OVL display TEXT with face FACE."
  20195. (overlay-put ovl 'display text)
  20196. (if face (overlay-put ovl 'face face))
  20197. (if evap (overlay-put ovl 'evaporate t)))
  20198. (defun org-overlay-before-string (ovl text &optional face evap)
  20199. "Make overlay OVL display TEXT with face FACE."
  20200. (if face (org-add-props text nil 'face face))
  20201. (overlay-put ovl 'before-string text)
  20202. (if evap (overlay-put ovl 'evaporate t)))
  20203. (defun org-find-overlays (prop &optional pos delete)
  20204. "Find all overlays specifying PROP at POS or point.
  20205. If DELETE is non-nil, delete all those overlays."
  20206. (let (found)
  20207. (dolist (ov (overlays-at (or pos (point))) found)
  20208. (cond ((not (overlay-get ov prop)))
  20209. (delete (delete-overlay ov))
  20210. (t (push ov found))))))
  20211. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20212. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20213. (if (and marker (marker-buffer marker)
  20214. (buffer-live-p (marker-buffer marker)))
  20215. (progn
  20216. (pop-to-buffer-same-window (marker-buffer marker))
  20217. (when (or (> marker (point-max)) (< marker (point-min)))
  20218. (widen))
  20219. (goto-char marker)
  20220. (org-show-context 'org-goto))
  20221. (if bookmark
  20222. (bookmark-jump bookmark)
  20223. (error "Cannot find location"))))
  20224. (defun org-quote-csv-field (s)
  20225. "Quote field for inclusion in CSV material."
  20226. (if (string-match "[\",]" s)
  20227. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20228. s))
  20229. (defun org-force-self-insert (N)
  20230. "Needed to enforce self-insert under remapping."
  20231. (interactive "p")
  20232. (self-insert-command N))
  20233. (defun org-string-width (s)
  20234. "Compute width of string, ignoring invisible characters.
  20235. This ignores character with invisibility property `org-link', and also
  20236. characters with property `org-cwidth', because these will become invisible
  20237. upon the next fontification round."
  20238. (let (b l)
  20239. (when (or (eq t buffer-invisibility-spec)
  20240. (assq 'org-link buffer-invisibility-spec))
  20241. (while (setq b (text-property-any 0 (length s)
  20242. 'invisible 'org-link s))
  20243. (setq s (concat (substring s 0 b)
  20244. (substring s (or (next-single-property-change
  20245. b 'invisible s)
  20246. (length s)))))))
  20247. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20248. (setq s (concat (substring s 0 b)
  20249. (substring s (or (next-single-property-change
  20250. b 'org-cwidth s)
  20251. (length s))))))
  20252. (setq l (string-width s) b -1)
  20253. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20254. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20255. l))
  20256. (defun org-shorten-string (s maxlength)
  20257. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20258. If the string is shorter or has length MAXLENGTH, just return the
  20259. original string. If it is longer, the functions finds a space in the
  20260. string, breaks this string off at that locations and adds three dots
  20261. as ellipsis. Including the ellipsis, the string will not be longer
  20262. than MAXLENGTH. If finding a good breaking point in the string does
  20263. not work, the string is just chopped off in the middle of a word
  20264. if necessary."
  20265. (if (<= (length s) maxlength)
  20266. s
  20267. (let* ((n (max (- maxlength 4) 1))
  20268. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20269. (if (string-match re s)
  20270. (concat (match-string 1 s) "...")
  20271. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20272. (defun org-get-indentation (&optional line)
  20273. "Get the indentation of the current line, interpreting tabs.
  20274. When LINE is given, assume it represents a line and compute its indentation."
  20275. (if line
  20276. (when (string-match "^ *" (org-remove-tabs line))
  20277. (match-end 0))
  20278. (save-excursion
  20279. (beginning-of-line 1)
  20280. (skip-chars-forward " \t")
  20281. (current-column))))
  20282. (defun org-get-string-indentation (s)
  20283. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20284. (let ((n -1) (i 0) (w tab-width) c)
  20285. (catch 'exit
  20286. (while (< (setq n (1+ n)) (length s))
  20287. (setq c (aref s n))
  20288. (cond ((= c ?\ ) (setq i (1+ i)))
  20289. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20290. (t (throw 'exit t)))))
  20291. i))
  20292. (defun org-remove-tabs (s &optional width)
  20293. "Replace tabulators in S with spaces.
  20294. Assumes that s is a single line, starting in column 0."
  20295. (setq width (or width tab-width))
  20296. (while (string-match "\t" s)
  20297. (setq s (replace-match
  20298. (make-string
  20299. (- (* width (/ (+ (match-beginning 0) width) width))
  20300. (match-beginning 0)) ?\ )
  20301. t t s)))
  20302. s)
  20303. (defun org-fix-indentation (line ind)
  20304. "Fix indentation in LINE.
  20305. IND is a cons cell with target and minimum indentation.
  20306. If the current indentation in LINE is smaller than the minimum,
  20307. leave it alone. If it is larger than ind, set it to the target."
  20308. (let* ((l (org-remove-tabs line))
  20309. (i (org-get-indentation l))
  20310. (i1 (car ind)) (i2 (cdr ind)))
  20311. (when (>= i i2) (setq l (substring line i2)))
  20312. (if (> i1 0)
  20313. (concat (make-string i1 ?\ ) l)
  20314. l)))
  20315. (defun org-remove-indentation (code &optional n)
  20316. "Remove maximum common indentation in string CODE and return it.
  20317. N may optionally be the number of columns to remove. Return CODE
  20318. as-is if removal failed."
  20319. (with-temp-buffer
  20320. (insert code)
  20321. (if (org-do-remove-indentation n) (buffer-string) code)))
  20322. (defun org-do-remove-indentation (&optional n)
  20323. "Remove the maximum common indentation from the buffer.
  20324. When optional argument N is a positive integer, remove exactly
  20325. that much characters from indentation, if possible. Return nil
  20326. if it fails."
  20327. (catch :exit
  20328. (goto-char (point-min))
  20329. ;; Find maximum common indentation, if not specified.
  20330. (let ((n (or n
  20331. (let ((min-ind (point-max)))
  20332. (save-excursion
  20333. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20334. (let ((ind (1- (current-column))))
  20335. (if (zerop ind) (throw :exit nil)
  20336. (setq min-ind (min min-ind ind))))))
  20337. min-ind))))
  20338. (if (zerop n) (throw :exit nil)
  20339. ;; Remove exactly N indentation, but give up if not possible.
  20340. (while (not (eobp))
  20341. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20342. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20343. ((< ind n) (throw :exit nil))
  20344. (t (indent-line-to (- ind n))))
  20345. (forward-line)))
  20346. ;; Signal success.
  20347. t))))
  20348. (defun org-fill-template (template alist)
  20349. "Find each %key of ALIST in TEMPLATE and replace it."
  20350. (let ((case-fold-search nil))
  20351. (dolist (entry (sort (copy-sequence alist)
  20352. (lambda (a b) (< (length (car a)) (length (car b))))))
  20353. (setq template
  20354. (replace-regexp-in-string
  20355. (concat "%" (regexp-quote (car entry)))
  20356. (or (cdr entry) "") template t t)))
  20357. template))
  20358. (defun org-base-buffer (buffer)
  20359. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20360. (if (not buffer)
  20361. buffer
  20362. (or (buffer-base-buffer buffer)
  20363. buffer)))
  20364. (defun org-wrap (string &optional width lines)
  20365. "Wrap string to either a number of lines, or a width in characters.
  20366. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20367. that costs. If there is a word longer than WIDTH, the text is actually
  20368. wrapped to the length of that word.
  20369. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20370. many lines, whatever width that takes.
  20371. The return value is a list of lines, without newlines at the end."
  20372. (let* ((words (org-split-string string "[ \t\n]+"))
  20373. (maxword (apply 'max (mapcar 'org-string-width words)))
  20374. w ll)
  20375. (cond (width
  20376. (org-do-wrap words (max maxword width)))
  20377. (lines
  20378. (setq w maxword)
  20379. (setq ll (org-do-wrap words maxword))
  20380. (if (<= (length ll) lines)
  20381. ll
  20382. (setq ll words)
  20383. (while (> (length ll) lines)
  20384. (setq w (1+ w))
  20385. (setq ll (org-do-wrap words w)))
  20386. ll))
  20387. (t (error "Cannot wrap this")))))
  20388. (defun org-do-wrap (words width)
  20389. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20390. (let (lines line)
  20391. (while words
  20392. (setq line (pop words))
  20393. (while (and words (< (+ (length line) (length (car words))) width))
  20394. (setq line (concat line " " (pop words))))
  20395. (setq lines (push line lines)))
  20396. (nreverse lines)))
  20397. (defun org-split-string (string &optional separators)
  20398. "Splits STRING into substrings at SEPARATORS.
  20399. SEPARATORS is a regular expression.
  20400. No empty strings are returned if there are matches at the beginning
  20401. and end of string."
  20402. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20403. (let ((start 0) notfirst list)
  20404. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20405. (if (and notfirst
  20406. (= start (match-beginning 0))
  20407. (< start (length string)))
  20408. (1+ start) start))
  20409. (< (match-beginning 0) (length string)))
  20410. (setq notfirst t)
  20411. (or (eq (match-beginning 0) 0)
  20412. (and (eq (match-beginning 0) (match-end 0))
  20413. (eq (match-beginning 0) start))
  20414. (push (substring string start (match-beginning 0)) list))
  20415. (setq start (match-end 0)))
  20416. (or (eq start (length string))
  20417. (push (substring string start) list))
  20418. (nreverse list)))
  20419. (defun org-quote-vert (s)
  20420. "Replace \"|\" with \"\\vert\"."
  20421. (while (string-match "|" s)
  20422. (setq s (replace-match "\\vert" t t s)))
  20423. s)
  20424. (defun org-uuidgen-p (s)
  20425. "Is S an ID created by UUIDGEN?"
  20426. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20427. (defun org-in-src-block-p (&optional inside)
  20428. "Whether point is in a code source block.
  20429. When INSIDE is non-nil, don't consider we are within a src block
  20430. when point is at #+BEGIN_SRC or #+END_SRC."
  20431. (let ((case-fold-search t))
  20432. (or (and (eq (get-char-property (point) 'src-block) t))
  20433. (and (not inside)
  20434. (save-match-data
  20435. (save-excursion
  20436. (beginning-of-line)
  20437. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20438. (defun org-context ()
  20439. "Return a list of contexts of the current cursor position.
  20440. If several contexts apply, all are returned.
  20441. Each context entry is a list with a symbol naming the context, and
  20442. two positions indicating start and end of the context. Possible
  20443. contexts are:
  20444. :headline anywhere in a headline
  20445. :headline-stars on the leading stars in a headline
  20446. :todo-keyword on a TODO keyword (including DONE) in a headline
  20447. :tags on the TAGS in a headline
  20448. :priority on the priority cookie in a headline
  20449. :item on the first line of a plain list item
  20450. :item-bullet on the bullet/number of a plain list item
  20451. :checkbox on the checkbox in a plain list item
  20452. :table in an Org table
  20453. :table-special on a special filed in a table
  20454. :table-table in a table.el table
  20455. :clocktable in a clocktable
  20456. :src-block in a source block
  20457. :link on a hyperlink
  20458. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20459. :target on a <<target>>
  20460. :radio-target on a <<<radio-target>>>
  20461. :latex-fragment on a LaTeX fragment
  20462. :latex-preview on a LaTeX fragment with overlaid preview image
  20463. This function expects the position to be visible because it uses font-lock
  20464. faces as a help to recognize the following contexts: :table-special, :link,
  20465. and :keyword."
  20466. (let* ((f (get-text-property (point) 'face))
  20467. (faces (if (listp f) f (list f)))
  20468. (case-fold-search t)
  20469. (p (point)) clist o)
  20470. ;; First the large context
  20471. (cond
  20472. ((org-at-heading-p t)
  20473. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20474. (when (progn
  20475. (beginning-of-line 1)
  20476. (looking-at org-todo-line-tags-regexp))
  20477. (push (org-point-in-group p 1 :headline-stars) clist)
  20478. (push (org-point-in-group p 2 :todo-keyword) clist)
  20479. (push (org-point-in-group p 4 :tags) clist))
  20480. (goto-char p)
  20481. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20482. (when (looking-at "\\[#[A-Z0-9]\\]")
  20483. (push (org-point-in-group p 0 :priority) clist)))
  20484. ((org-at-item-p)
  20485. (push (org-point-in-group p 2 :item-bullet) clist)
  20486. (push (list :item (point-at-bol)
  20487. (save-excursion (org-end-of-item) (point)))
  20488. clist)
  20489. (and (org-at-item-checkbox-p)
  20490. (push (org-point-in-group p 0 :checkbox) clist)))
  20491. ((org-at-table-p)
  20492. (push (list :table (org-table-begin) (org-table-end)) clist)
  20493. (when (memq 'org-formula faces)
  20494. (push (list :table-special
  20495. (previous-single-property-change p 'face)
  20496. (next-single-property-change p 'face)) clist)))
  20497. ((org-at-table-p 'any)
  20498. (push (list :table-table) clist)))
  20499. (goto-char p)
  20500. (let ((case-fold-search t))
  20501. ;; New the "medium" contexts: clocktables, source blocks
  20502. (cond ((org-in-clocktable-p)
  20503. (push (list :clocktable
  20504. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20505. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20506. (match-beginning 1))
  20507. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20508. (match-end 0))) clist))
  20509. ((org-in-src-block-p)
  20510. (push (list :src-block
  20511. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20512. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20513. (match-beginning 1))
  20514. (and (search-forward "#+END_SRC" nil t)
  20515. (match-beginning 0))) clist))))
  20516. (goto-char p)
  20517. ;; Now the small context
  20518. (cond
  20519. ((org-at-timestamp-p)
  20520. (push (org-point-in-group p 0 :timestamp) clist))
  20521. ((memq 'org-link faces)
  20522. (push (list :link
  20523. (previous-single-property-change p 'face)
  20524. (next-single-property-change p 'face)) clist))
  20525. ((memq 'org-special-keyword faces)
  20526. (push (list :keyword
  20527. (previous-single-property-change p 'face)
  20528. (next-single-property-change p 'face)) clist))
  20529. ((org-at-target-p)
  20530. (push (org-point-in-group p 0 :target) clist)
  20531. (goto-char (1- (match-beginning 0)))
  20532. (when (looking-at org-radio-target-regexp)
  20533. (push (org-point-in-group p 0 :radio-target) clist))
  20534. (goto-char p))
  20535. ((setq o (cl-some
  20536. (lambda (o)
  20537. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20538. o))
  20539. (overlays-at (point))))
  20540. (push (list :latex-fragment
  20541. (overlay-start o) (overlay-end o)) clist)
  20542. (push (list :latex-preview
  20543. (overlay-start o) (overlay-end o)) clist))
  20544. ((org-inside-LaTeX-fragment-p)
  20545. ;; FIXME: positions wrong.
  20546. (push (list :latex-fragment (point) (point)) clist)))
  20547. (setq clist (nreverse (delq nil clist)))
  20548. clist))
  20549. (defun org-in-regexp (regexp &optional nlines visually)
  20550. "Check if point is inside a match of REGEXP.
  20551. Normally only the current line is checked, but you can include
  20552. NLINES extra lines around point into the search. If VISUALLY is
  20553. set, require that the cursor is not after the match but really
  20554. on, so that the block visually is on the match.
  20555. Return nil or a cons cell (BEG . END) where BEG and END are,
  20556. respectively, the positions at the beginning and the end of the
  20557. match."
  20558. (catch :exit
  20559. (let ((pos (point))
  20560. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20561. (save-excursion
  20562. (beginning-of-line (- 1 (or nlines 0)))
  20563. (while (and (re-search-forward regexp eol t)
  20564. (<= (match-beginning 0) pos))
  20565. (let ((end (match-end 0)))
  20566. (when (or (> end pos) (and (= end pos) (not visually)))
  20567. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20568. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20569. "Non-nil when point is between matches of START-RE and END-RE.
  20570. Also return a non-nil value when point is on one of the matches.
  20571. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20572. buffer positions. Default values are the positions of headlines
  20573. surrounding the point.
  20574. The functions returns a cons cell whose car (resp. cdr) is the
  20575. position before START-RE (resp. after END-RE)."
  20576. (save-match-data
  20577. (let ((pos (point))
  20578. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20579. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20580. beg end)
  20581. (save-excursion
  20582. ;; Point is on a block when on START-RE or if START-RE can be
  20583. ;; found before it...
  20584. (and (or (org-in-regexp start-re)
  20585. (re-search-backward start-re limit-up t))
  20586. (setq beg (match-beginning 0))
  20587. ;; ... and END-RE after it...
  20588. (goto-char (match-end 0))
  20589. (re-search-forward end-re limit-down t)
  20590. (> (setq end (match-end 0)) pos)
  20591. ;; ... without another START-RE in-between.
  20592. (goto-char (match-beginning 0))
  20593. (not (re-search-backward start-re (1+ beg) t))
  20594. ;; Return value.
  20595. (cons beg end))))))
  20596. (defun org-in-block-p (names)
  20597. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20598. NAMES is a list of strings containing names of blocks.
  20599. Return first block name matched, or nil. Beware that in case of
  20600. nested blocks, the returned name may not belong to the closest
  20601. block from point."
  20602. (save-match-data
  20603. (catch 'exit
  20604. (let ((case-fold-search t)
  20605. (lim-up (save-excursion (outline-previous-heading)))
  20606. (lim-down (save-excursion (outline-next-heading))))
  20607. (dolist (name names)
  20608. (let ((n (regexp-quote name)))
  20609. (when (org-between-regexps-p
  20610. (concat "^[ \t]*#\\+begin_" n)
  20611. (concat "^[ \t]*#\\+end_" n)
  20612. lim-up lim-down)
  20613. (throw 'exit n)))))
  20614. nil)))
  20615. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20616. "Call `multi-occur' with buffers for all agenda files."
  20617. (interactive "sOrg-files matching: ")
  20618. (let* ((files (org-agenda-files))
  20619. (tnames (mapcar #'file-truename files))
  20620. (extra org-agenda-text-search-extra-files))
  20621. (when (eq (car extra) 'agenda-archives)
  20622. (setq extra (cdr extra))
  20623. (setq files (org-add-archive-files files)))
  20624. (dolist (f extra)
  20625. (unless (member (file-truename f) tnames)
  20626. (unless (member f files) (setq files (append files (list f))))
  20627. (setq tnames (append tnames (list (file-truename f))))))
  20628. (multi-occur
  20629. (mapcar (lambda (x)
  20630. (with-current-buffer
  20631. ;; FIXME: Why not just (find-file-noselect x)?
  20632. ;; Is it to avoid the "revert buffer" prompt?
  20633. (or (get-file-buffer x) (find-file-noselect x))
  20634. (widen)
  20635. (current-buffer)))
  20636. files)
  20637. regexp)))
  20638. (add-hook 'occur-mode-find-occurrence-hook
  20639. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20640. (defun org-occur-link-in-agenda-files ()
  20641. "Create a link and search for it in the agendas.
  20642. The link is not stored in `org-stored-links', it is just created
  20643. for the search purpose."
  20644. (interactive)
  20645. (let ((link (condition-case nil
  20646. (org-store-link nil)
  20647. (error "Unable to create a link to here"))))
  20648. (org-occur-in-agenda-files (regexp-quote link))))
  20649. (defun org-reverse-string (string)
  20650. "Return the reverse of STRING."
  20651. (apply 'string (reverse (string-to-list string))))
  20652. ;; defsubst org-uniquify must be defined before first use
  20653. (defun org-uniquify-alist (alist)
  20654. "Merge elements of ALIST with the same key.
  20655. For example, in this alist:
  20656. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20657. => \\='((a 1 3) (b 2))
  20658. merge (a 1) and (a 3) into (a 1 3).
  20659. The function returns the new ALIST."
  20660. (let (rtn)
  20661. (dolist (e alist rtn)
  20662. (let (n)
  20663. (if (not (assoc (car e) rtn))
  20664. (push e rtn)
  20665. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20666. (setq rtn (assq-delete-all (car e) rtn))
  20667. (push n rtn))))))
  20668. (defun org-delete-all (elts list)
  20669. "Remove all elements in ELTS from LIST.
  20670. Comparison is done with `equal'. It is a destructive operation
  20671. that may remove elements by altering the list structure."
  20672. (while elts
  20673. (setq list (delete (pop elts) list)))
  20674. list)
  20675. (defun org-back-over-empty-lines ()
  20676. "Move backwards over whitespace, to the beginning of the first empty line.
  20677. Returns the number of empty lines passed."
  20678. (let ((pos (point)))
  20679. (if (cdr (assq 'heading org-blank-before-new-entry))
  20680. (skip-chars-backward " \t\n\r")
  20681. (unless (eobp)
  20682. (forward-line -1)))
  20683. (beginning-of-line 2)
  20684. (goto-char (min (point) pos))
  20685. (count-lines (point) pos)))
  20686. (defun org-skip-whitespace ()
  20687. (skip-chars-forward " \t\n\r"))
  20688. (defun org-point-in-group (point group &optional context)
  20689. "Check if POINT is in match-group GROUP.
  20690. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20691. match. If the match group does not exist or point is not inside it,
  20692. return nil."
  20693. (and (match-beginning group)
  20694. (>= point (match-beginning group))
  20695. (<= point (match-end group))
  20696. (if context
  20697. (list context (match-beginning group) (match-end group))
  20698. t)))
  20699. (defun org-switch-to-buffer-other-window (&rest args)
  20700. "Switch to buffer in a second window on the current frame.
  20701. In particular, do not allow pop-up frames.
  20702. Returns the newly created buffer."
  20703. (org-no-popups
  20704. (apply 'switch-to-buffer-other-window args)))
  20705. (defun org-combine-plists (&rest plists)
  20706. "Create a single property list from all plists in PLISTS.
  20707. The process starts by copying the first list, and then setting properties
  20708. from the other lists. Settings in the last list are the most significant
  20709. ones and overrule settings in the other lists."
  20710. (let ((rtn (copy-sequence (pop plists)))
  20711. p v ls)
  20712. (while plists
  20713. (setq ls (pop plists))
  20714. (while ls
  20715. (setq p (pop ls) v (pop ls))
  20716. (setq rtn (plist-put rtn p v))))
  20717. rtn))
  20718. (defun org-replace-escapes (string table)
  20719. "Replace %-escapes in STRING with values in TABLE.
  20720. TABLE is an association list with keys like \"%a\" and string values.
  20721. The sequences in STRING may contain normal field width and padding information,
  20722. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20723. so values can contain further %-escapes if they are define later in TABLE."
  20724. (let ((tbl (copy-alist table))
  20725. (case-fold-search nil)
  20726. (pchg 0)
  20727. re rpl)
  20728. (dolist (e tbl)
  20729. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20730. (when (and (cdr e) (string-match re (cdr e)))
  20731. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20732. (safe "SREF"))
  20733. (add-text-properties 0 3 (list 'sref sref) safe)
  20734. (setcdr e (replace-match safe t t (cdr e)))))
  20735. (while (string-match re string)
  20736. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20737. (cdr e)))
  20738. (setq string (replace-match rpl t t string))))
  20739. (while (setq pchg (next-property-change pchg string))
  20740. (let ((sref (get-text-property pchg 'sref string)))
  20741. (when (and sref (string-match "SREF" string pchg))
  20742. (setq string (replace-match sref t t string)))))
  20743. string))
  20744. (defun org-find-base-buffer-visiting (file)
  20745. "Like `find-buffer-visiting' but always return the base buffer and
  20746. not an indirect buffer."
  20747. (let ((buf (or (get-file-buffer file)
  20748. (find-buffer-visiting file))))
  20749. (if buf
  20750. (or (buffer-base-buffer buf) buf)
  20751. nil)))
  20752. ;;; TODO: Only called once, from ox-odt which should probably use
  20753. ;;; org-export-inline-image-p or something.
  20754. (defun org-file-image-p (file)
  20755. "Return non-nil if FILE is an image."
  20756. (save-match-data
  20757. (string-match (image-file-name-regexp) file)))
  20758. (defun org-get-cursor-date (&optional with-time)
  20759. "Return the date at cursor in as a time.
  20760. This works in the calendar and in the agenda, anywhere else it just
  20761. returns the current time.
  20762. If WITH-TIME is non-nil, returns the time of the event at point (in
  20763. the agenda) or the current time of the day."
  20764. (let (date day defd tp hod mod)
  20765. (when with-time
  20766. (setq tp (get-text-property (point) 'time))
  20767. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20768. (setq hod (string-to-number (match-string 1 tp))
  20769. mod (string-to-number (match-string 2 tp))))
  20770. (or tp (let ((now (decode-time)))
  20771. (setq hod (nth 2 now)
  20772. mod (nth 1 now)))))
  20773. (cond
  20774. ((eq major-mode 'calendar-mode)
  20775. (setq date (calendar-cursor-to-date)
  20776. defd (encode-time 0 (or mod 0) (or hod 0)
  20777. (nth 1 date) (nth 0 date) (nth 2 date))))
  20778. ((eq major-mode 'org-agenda-mode)
  20779. (setq day (get-text-property (point) 'day))
  20780. (when day
  20781. (setq date (calendar-gregorian-from-absolute day)
  20782. defd (encode-time 0 (or mod 0) (or hod 0)
  20783. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20784. (or defd (current-time))))
  20785. (defun org-mark-subtree (&optional up)
  20786. "Mark the current subtree.
  20787. This puts point at the start of the current subtree, and mark at
  20788. the end. If a numeric prefix UP is given, move up into the
  20789. hierarchy of headlines by UP levels before marking the subtree."
  20790. (interactive "P")
  20791. (org-with-limited-levels
  20792. (cond ((org-at-heading-p) (beginning-of-line))
  20793. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20794. (t (outline-previous-visible-heading 1))))
  20795. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20796. (if (called-interactively-p 'any)
  20797. (call-interactively 'org-mark-element)
  20798. (org-mark-element)))
  20799. (defun org-file-newer-than-p (file time)
  20800. "Non-nil if FILE is newer than TIME.
  20801. FILE is a filename, as a string, TIME is a list of integers, as
  20802. returned by, e.g., `current-time'."
  20803. (and (file-exists-p file)
  20804. ;; Only compare times up to whole seconds as some file-systems
  20805. ;; (e.g. HFS+) do not retain any finer granularity. As
  20806. ;; a consequence, make sure we return non-nil when the two
  20807. ;; times are equal.
  20808. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20809. (cl-subseq time 0 2)))))
  20810. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20811. "Compile a SOURCE file using PROCESS.
  20812. PROCESS is either a function or a list of shell commands, as
  20813. strings. EXT is a file extension, without the leading dot, as
  20814. a string. It is used to check if the process actually succeeded.
  20815. PROCESS must create a file with the same base name and directory
  20816. as SOURCE, but ending with EXT. The function then returns its
  20817. filename. Otherwise, it raises an error. The error message can
  20818. then be refined by providing string ERR-MSG, which is appended to
  20819. the standard message.
  20820. If PROCESS is a function, it is called with a single argument:
  20821. the SOURCE file.
  20822. If it is a list of commands, each of them is called using
  20823. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20824. %O are replaced with, respectively, SOURCE base name, name, full
  20825. name, directory and absolute output file name. It is possible,
  20826. however, to use more place-holders by specifying them in optional
  20827. argument SPEC, as an alist following the pattern
  20828. (CHARACTER . REPLACEMENT-STRING).
  20829. When PROCESS is a list of commands, optional argument LOG-BUF can
  20830. be set to a buffer or a buffer name. `shell-command' then uses
  20831. it for output."
  20832. (let* ((base-name (file-name-base source))
  20833. (full-name (file-truename source))
  20834. (out-dir (or (file-name-directory source) "./"))
  20835. (output (expand-file-name (concat base-name "." ext) out-dir))
  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. (?O . ,(shell-quote-argument output))))))
  20849. (dolist (command process)
  20850. (shell-command (format-spec command spec) log-buf))))
  20851. (_ (error "No valid command to process %S%s" source err-msg))))
  20852. ;; Check for process failure. Output file is expected to be
  20853. ;; located in the same directory as SOURCE.
  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 (org-match-line "[ \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. ((and (memq type org-element-greater-elements)
  20945. (let ((cend (org-element-property :contents-end element)))
  20946. (and cend (<= cend pos))))
  20947. ;; As a special case, if point is at the end of a footnote
  20948. ;; definition or an item, indent like the very last element
  20949. ;; within. If that last element is an item, indent like
  20950. ;; its contents.
  20951. (if (memq type '(footnote-definition item plain-list))
  20952. (let ((last (org-element-at-point)))
  20953. (goto-char pos)
  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 'latex-environment)
  21017. (>= (point) (org-element-property :post-affiliated element))
  21018. (< (point) (org-with-wide-buffer
  21019. (goto-char (org-element-property :end element))
  21020. (skip-chars-backward " \r\t\n")
  21021. (line-beginning-position 2))))
  21022. 'noindent)
  21023. ((and (eq type 'src-block)
  21024. org-src-tab-acts-natively
  21025. (> (line-beginning-position)
  21026. (org-element-property :post-affiliated element))
  21027. (< (line-beginning-position)
  21028. (org-with-wide-buffer
  21029. (goto-char (org-element-property :end element))
  21030. (skip-chars-backward " \r\t\n")
  21031. (line-beginning-position))))
  21032. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21033. (t
  21034. (let ((column (org--get-expected-indentation element nil)))
  21035. ;; Preserve current column.
  21036. (if (<= (current-column) (current-indentation))
  21037. (indent-line-to column)
  21038. (save-excursion (indent-line-to column))))
  21039. ;; Align node property. Also preserve current column.
  21040. (when (eq type 'node-property)
  21041. (let ((column (current-column)))
  21042. (org--align-node-property)
  21043. (org-move-to-column column)))))))))
  21044. (defun org-indent-region (start end)
  21045. "Indent each non-blank line in the region.
  21046. Called from a program, START and END specify the region to
  21047. indent. The function will not indent contents of example blocks,
  21048. verse blocks and export blocks as leading white spaces are
  21049. assumed to be significant there."
  21050. (interactive "r")
  21051. (save-excursion
  21052. (goto-char start)
  21053. (skip-chars-forward " \r\t\n")
  21054. (unless (eobp) (beginning-of-line))
  21055. (let ((indent-to
  21056. (lambda (ind pos)
  21057. ;; Set IND as indentation for all lines between point and
  21058. ;; POS. Blank lines are ignored. Leave point after POS
  21059. ;; once done.
  21060. (let ((limit (copy-marker pos)))
  21061. (while (< (point) limit)
  21062. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21063. (forward-line))
  21064. (set-marker limit nil))))
  21065. (end (copy-marker end)))
  21066. (while (< (point) end)
  21067. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21068. (let* ((element (org-element-at-point))
  21069. (type (org-element-type element))
  21070. (element-end (copy-marker (org-element-property :end element)))
  21071. (ind (org--get-expected-indentation element nil)))
  21072. (cond
  21073. ;; Element indented as a single block. Example blocks
  21074. ;; preserving indentation are a special case since the
  21075. ;; "contents" must not be indented whereas the block
  21076. ;; boundaries can.
  21077. ((or (memq type '(export-block latex-environment))
  21078. (and (eq type 'example-block)
  21079. (not
  21080. (or org-src-preserve-indentation
  21081. (org-element-property :preserve-indent element)))))
  21082. (let ((offset (- ind (org-get-indentation))))
  21083. (unless (zerop offset)
  21084. (indent-rigidly (org-element-property :begin element)
  21085. (org-element-property :end element)
  21086. offset)))
  21087. (goto-char element-end))
  21088. ;; Elements indented line wise. Be sure to exclude
  21089. ;; example blocks (preserving indentation) and source
  21090. ;; blocks from this category as they are treated
  21091. ;; specially later.
  21092. ((or (memq type '(paragraph table table-row))
  21093. (not (or (org-element-property :contents-begin element)
  21094. (memq type '(example-block src-block)))))
  21095. (when (eq type 'node-property)
  21096. (org--align-node-property)
  21097. (beginning-of-line))
  21098. (funcall indent-to ind (min element-end end)))
  21099. ;; Elements consisting of three parts: before the
  21100. ;; contents, the contents, and after the contents. The
  21101. ;; contents are treated specially, according to the
  21102. ;; element type, or not indented at all. Other parts are
  21103. ;; indented as a single block.
  21104. (t
  21105. (let* ((post (copy-marker
  21106. (org-element-property :post-affiliated element)))
  21107. (cbeg
  21108. (copy-marker
  21109. (cond
  21110. ((not (org-element-property :contents-begin element))
  21111. ;; Fake contents for source blocks.
  21112. (org-with-wide-buffer
  21113. (goto-char post)
  21114. (line-beginning-position 2)))
  21115. ((memq type '(footnote-definition item plain-list))
  21116. ;; Contents in these elements could start on
  21117. ;; the same line as the beginning of the
  21118. ;; element. Make sure we start indenting
  21119. ;; from the second line.
  21120. (org-with-wide-buffer
  21121. (goto-char post)
  21122. (end-of-line)
  21123. (skip-chars-forward " \r\t\n")
  21124. (if (eobp) (point) (line-beginning-position))))
  21125. (t (org-element-property :contents-begin element)))))
  21126. (cend (copy-marker
  21127. (or (org-element-property :contents-end element)
  21128. ;; Fake contents for source blocks.
  21129. (org-with-wide-buffer
  21130. (goto-char element-end)
  21131. (skip-chars-backward " \r\t\n")
  21132. (line-beginning-position)))
  21133. t)))
  21134. ;; Do not change items indentation individually as it
  21135. ;; might break the list as a whole. On the other
  21136. ;; hand, when at a plain list, indent it as a whole.
  21137. (cond ((eq type 'plain-list)
  21138. (let ((offset (- ind (org-get-indentation))))
  21139. (unless (zerop offset)
  21140. (indent-rigidly (org-element-property :begin element)
  21141. (org-element-property :end element)
  21142. offset))
  21143. (goto-char cbeg)))
  21144. ((eq type 'item) (goto-char cbeg))
  21145. (t (funcall indent-to ind (min cbeg end))))
  21146. (when (< (point) end)
  21147. (cl-case type
  21148. ((example-block verse-block))
  21149. (src-block
  21150. ;; In a source block, indent source code
  21151. ;; according to language major mode, but only if
  21152. ;; `org-src-tab-acts-natively' is non-nil.
  21153. (when (and (< (point) end) org-src-tab-acts-natively)
  21154. (ignore-errors
  21155. (org-babel-do-in-edit-buffer
  21156. (indent-region (point-min) (point-max))))))
  21157. (t (org-indent-region (point) (min cend end))))
  21158. (goto-char (min cend end))
  21159. (when (< (point) end)
  21160. (funcall indent-to ind (min element-end end))))
  21161. (set-marker post nil)
  21162. (set-marker cbeg nil)
  21163. (set-marker cend nil))))
  21164. (set-marker element-end nil))))
  21165. (set-marker end nil))))
  21166. (defun org-indent-drawer ()
  21167. "Indent the drawer at point."
  21168. (interactive)
  21169. (unless (save-excursion
  21170. (beginning-of-line)
  21171. (looking-at-p org-drawer-regexp))
  21172. (user-error "Not at a drawer"))
  21173. (let ((element (org-element-at-point)))
  21174. (unless (memq (org-element-type element) '(drawer property-drawer))
  21175. (user-error "Not at a drawer"))
  21176. (org-with-wide-buffer
  21177. (org-indent-region (org-element-property :begin element)
  21178. (org-element-property :end element))))
  21179. (message "Drawer at point indented"))
  21180. (defun org-indent-block ()
  21181. "Indent the block at point."
  21182. (interactive)
  21183. (unless (save-excursion
  21184. (beginning-of-line)
  21185. (let ((case-fold-search t))
  21186. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21187. (user-error "Not at a block"))
  21188. (let ((element (org-element-at-point)))
  21189. (unless (memq (org-element-type element)
  21190. '(comment-block center-block dynamic-block example-block
  21191. export-block quote-block special-block
  21192. src-block verse-block))
  21193. (user-error "Not at a block"))
  21194. (org-with-wide-buffer
  21195. (org-indent-region (org-element-property :begin element)
  21196. (org-element-property :end element))))
  21197. (message "Block at point indented"))
  21198. ;;; Filling
  21199. ;; We use our own fill-paragraph and auto-fill functions.
  21200. ;; `org-fill-paragraph' relies on adaptive filling and context
  21201. ;; checking. Appropriate `fill-prefix' is computed with
  21202. ;; `org-adaptive-fill-function'.
  21203. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21204. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21205. ;; `org-adaptive-fill-function' value. Internally,
  21206. ;; `org-comment-line-break-function' breaks the line.
  21207. ;; `org-setup-filling' installs filling and auto-filling related
  21208. ;; variables during `org-mode' initialization.
  21209. (defvar org-element-paragraph-separate) ; org-element.el
  21210. (defun org-setup-filling ()
  21211. (require 'org-element)
  21212. ;; Prevent auto-fill from inserting unwanted new items.
  21213. (when (boundp 'fill-nobreak-predicate)
  21214. (setq-local
  21215. fill-nobreak-predicate
  21216. (org-uniquify
  21217. (append fill-nobreak-predicate
  21218. '(org-fill-line-break-nobreak-p
  21219. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21220. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21221. (setq-local paragraph-start paragraph-ending)
  21222. (setq-local paragraph-separate paragraph-ending))
  21223. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21224. (setq-local auto-fill-inhibit-regexp nil)
  21225. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21226. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21227. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21228. (defun org-fill-line-break-nobreak-p ()
  21229. "Non-nil when a new line at point would create an Org line break."
  21230. (save-excursion
  21231. (skip-chars-backward "[ \t]")
  21232. (skip-chars-backward "\\\\")
  21233. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21234. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21235. "Non-nil when a new line at point would split a timestamp."
  21236. (and (org-at-timestamp-p t)
  21237. (not (looking-at org-ts-regexp-both))))
  21238. (declare-function message-in-body-p "message" ())
  21239. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21240. (defun org-adaptive-fill-function ()
  21241. "Compute a fill prefix for the current line.
  21242. Return fill prefix, as a string, or nil if current line isn't
  21243. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21244. matches in paragraphs or comments, use it."
  21245. (catch 'exit
  21246. (when (derived-mode-p 'message-mode)
  21247. (save-excursion
  21248. (beginning-of-line)
  21249. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21250. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21251. ((looking-at message-cite-prefix-regexp)
  21252. (throw 'exit (match-string-no-properties 0)))
  21253. ((looking-at org-outline-regexp)
  21254. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21255. (org-with-wide-buffer
  21256. (unless (org-at-heading-p)
  21257. (let* ((p (line-beginning-position))
  21258. (element (save-excursion
  21259. (beginning-of-line)
  21260. (org-element-at-point)))
  21261. (type (org-element-type element))
  21262. (post-affiliated (org-element-property :post-affiliated element)))
  21263. (unless (< p post-affiliated)
  21264. (cl-case type
  21265. (comment
  21266. (save-excursion
  21267. (beginning-of-line)
  21268. (looking-at "[ \t]*")
  21269. (concat (match-string 0) "# ")))
  21270. (footnote-definition "")
  21271. ((item plain-list)
  21272. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21273. (paragraph
  21274. ;; Fill prefix is usually the same as the current line,
  21275. ;; unless the paragraph is at the beginning of an item.
  21276. (let ((parent (org-element-property :parent element)))
  21277. (save-excursion
  21278. (beginning-of-line)
  21279. (cond ((eq (org-element-type parent) 'item)
  21280. (make-string (org-list-item-body-column
  21281. (org-element-property :begin parent))
  21282. ?\s))
  21283. ((and adaptive-fill-regexp
  21284. ;; Locally disable
  21285. ;; `adaptive-fill-function' to let
  21286. ;; `fill-context-prefix' handle
  21287. ;; `adaptive-fill-regexp' variable.
  21288. (let (adaptive-fill-function)
  21289. (fill-context-prefix
  21290. post-affiliated
  21291. (org-element-property :end element)))))
  21292. ((looking-at "[ \t]+") (match-string 0))
  21293. (t "")))))
  21294. (comment-block
  21295. ;; Only fill contents if P is within block boundaries.
  21296. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21297. (forward-line)
  21298. (point)))
  21299. (cend (save-excursion
  21300. (goto-char (org-element-property :end element))
  21301. (skip-chars-backward " \r\t\n")
  21302. (line-beginning-position))))
  21303. (when (and (>= p cbeg) (< p cend))
  21304. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21305. (match-string 0)
  21306. "")))))))))))
  21307. (declare-function message-goto-body "message" ())
  21308. (defvar message-cite-prefix-regexp) ; From message.el
  21309. (defun org-fill-paragraph (&optional justify)
  21310. "Fill element at point, when applicable.
  21311. This function only applies to comment blocks, comments, example
  21312. blocks and paragraphs. Also, as a special case, re-align table
  21313. when point is at one.
  21314. If JUSTIFY is non-nil (interactively, with prefix argument),
  21315. justify as well. If `sentence-end-double-space' is non-nil, then
  21316. period followed by one space does not end a sentence, so don't
  21317. break a line there. The variable `fill-column' controls the
  21318. width for filling.
  21319. For convenience, when point is at a plain list, an item or
  21320. a footnote definition, try to fill the first paragraph within."
  21321. (interactive)
  21322. (if (and (derived-mode-p 'message-mode)
  21323. (or (not (message-in-body-p))
  21324. (save-excursion (move-beginning-of-line 1)
  21325. (looking-at message-cite-prefix-regexp))))
  21326. ;; First ensure filling is correct in message-mode.
  21327. (let ((fill-paragraph-function
  21328. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21329. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21330. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21331. (paragraph-separate
  21332. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21333. (fill-paragraph nil))
  21334. (with-syntax-table org-mode-transpose-word-syntax-table
  21335. ;; Move to end of line in order to get the first paragraph
  21336. ;; within a plain list or a footnote definition.
  21337. (let ((element (save-excursion
  21338. (end-of-line)
  21339. (or (ignore-errors (org-element-at-point))
  21340. (user-error "An element cannot be parsed line %d"
  21341. (line-number-at-pos (point)))))))
  21342. ;; First check if point is in a blank line at the beginning of
  21343. ;; the buffer. In that case, ignore filling.
  21344. (cl-case (org-element-type element)
  21345. ;; Use major mode filling function is src blocks.
  21346. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21347. ;; Align Org tables, leave table.el tables as-is.
  21348. (table-row (org-table-align) t)
  21349. (table
  21350. (when (eq (org-element-property :type element) 'org)
  21351. (save-excursion
  21352. (goto-char (org-element-property :post-affiliated element))
  21353. (org-table-align)))
  21354. t)
  21355. (paragraph
  21356. ;; Paragraphs may contain `line-break' type objects.
  21357. (let ((beg (max (point-min)
  21358. (org-element-property :contents-begin element)))
  21359. (end (min (point-max)
  21360. (org-element-property :contents-end element))))
  21361. ;; Do nothing if point is at an affiliated keyword.
  21362. (if (< (line-end-position) beg) t
  21363. (when (derived-mode-p 'message-mode)
  21364. ;; In `message-mode', do not fill following citation
  21365. ;; in current paragraph nor text before message body.
  21366. (let ((body-start (save-excursion (message-goto-body))))
  21367. (when body-start (setq beg (max body-start beg))))
  21368. (when (save-excursion
  21369. (re-search-forward
  21370. (concat "^" message-cite-prefix-regexp) end t))
  21371. (setq end (match-beginning 0))))
  21372. ;; Fill paragraph, taking line breaks into account.
  21373. (save-excursion
  21374. (goto-char beg)
  21375. (let ((cuts (list beg)))
  21376. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21377. (when (eq 'line-break
  21378. (org-element-type
  21379. (save-excursion (backward-char)
  21380. (org-element-context))))
  21381. (push (point) cuts)))
  21382. (dolist (c (delq end cuts))
  21383. (fill-region-as-paragraph c end justify)
  21384. (setq end c))))
  21385. t)))
  21386. ;; Contents of `comment-block' type elements should be
  21387. ;; filled as plain text, but only if point is within block
  21388. ;; markers.
  21389. (comment-block
  21390. (let* ((case-fold-search t)
  21391. (beg (save-excursion
  21392. (goto-char (org-element-property :begin element))
  21393. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21394. (forward-line)
  21395. (point)))
  21396. (end (save-excursion
  21397. (goto-char (org-element-property :end element))
  21398. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21399. (line-beginning-position))))
  21400. (if (or (< (point) beg) (> (point) end)) t
  21401. (fill-region-as-paragraph
  21402. (save-excursion (end-of-line)
  21403. (re-search-backward "^[ \t]*$" beg 'move)
  21404. (line-beginning-position))
  21405. (save-excursion (beginning-of-line)
  21406. (re-search-forward "^[ \t]*$" end 'move)
  21407. (line-beginning-position))
  21408. justify))))
  21409. ;; Fill comments.
  21410. (comment
  21411. (let ((begin (org-element-property :post-affiliated element))
  21412. (end (org-element-property :end element)))
  21413. (when (and (>= (point) begin) (<= (point) end))
  21414. (let ((begin (save-excursion
  21415. (end-of-line)
  21416. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21417. (progn (forward-line) (point))
  21418. begin)))
  21419. (end (save-excursion
  21420. (end-of-line)
  21421. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21422. (1- (line-beginning-position))
  21423. (skip-chars-backward " \r\t\n")
  21424. (line-end-position)))))
  21425. ;; Do not fill comments when at a blank line.
  21426. (when (> end begin)
  21427. (let ((fill-prefix
  21428. (save-excursion
  21429. (beginning-of-line)
  21430. (looking-at "[ \t]*#")
  21431. (let ((comment-prefix (match-string 0)))
  21432. (goto-char (match-end 0))
  21433. (if (looking-at adaptive-fill-regexp)
  21434. (concat comment-prefix (match-string 0))
  21435. (concat comment-prefix " "))))))
  21436. (save-excursion
  21437. (fill-region-as-paragraph begin end justify))))))
  21438. t))
  21439. ;; Ignore every other element.
  21440. (otherwise t))))))
  21441. (defun org-auto-fill-function ()
  21442. "Auto-fill function."
  21443. ;; Check if auto-filling is meaningful.
  21444. (let ((fc (current-fill-column)))
  21445. (when (and fc (> (current-column) fc))
  21446. (let* ((fill-prefix (org-adaptive-fill-function))
  21447. ;; Enforce empty fill prefix, if required. Otherwise, it
  21448. ;; will be computed again.
  21449. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21450. (when fill-prefix (do-auto-fill))))))
  21451. (defun org-comment-line-break-function (&optional soft)
  21452. "Break line at point and indent, continuing comment if within one.
  21453. The inserted newline is marked hard if variable
  21454. `use-hard-newlines' is true, unless optional argument SOFT is
  21455. non-nil."
  21456. (if soft (insert-and-inherit ?\n) (newline 1))
  21457. (save-excursion (forward-char -1) (delete-horizontal-space))
  21458. (delete-horizontal-space)
  21459. (indent-to-left-margin)
  21460. (insert-before-markers-and-inherit fill-prefix))
  21461. ;;; Fixed Width Areas
  21462. (defun org-toggle-fixed-width ()
  21463. "Toggle fixed-width markup.
  21464. Add or remove fixed-width markup on current line, whenever it
  21465. makes sense. Return an error otherwise.
  21466. If a region is active and if it contains only fixed-width areas
  21467. or blank lines, remove all fixed-width markup in it. If the
  21468. region contains anything else, convert all non-fixed-width lines
  21469. to fixed-width ones.
  21470. Blank lines at the end of the region are ignored unless the
  21471. region only contains such lines."
  21472. (interactive)
  21473. (if (not (org-region-active-p))
  21474. ;; No region:
  21475. ;;
  21476. ;; Remove fixed width marker only in a fixed-with element.
  21477. ;;
  21478. ;; Add fixed width maker in paragraphs, in blank lines after
  21479. ;; elements or at the beginning of a headline or an inlinetask,
  21480. ;; and before any one-line elements (e.g., a clock).
  21481. (progn
  21482. (beginning-of-line)
  21483. (let* ((element (org-element-at-point))
  21484. (type (org-element-type element)))
  21485. (cond
  21486. ((and (eq type 'fixed-width)
  21487. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21488. (replace-match
  21489. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21490. ((and (memq type '(babel-call clock comment diary-sexp headline
  21491. horizontal-rule keyword paragraph
  21492. planning))
  21493. (<= (org-element-property :post-affiliated element) (point)))
  21494. (skip-chars-forward " \t")
  21495. (insert ": "))
  21496. ((and (looking-at-p "[ \t]*$")
  21497. (or (eq type 'inlinetask)
  21498. (save-excursion
  21499. (skip-chars-forward " \r\t\n")
  21500. (<= (org-element-property :end element) (point)))))
  21501. (delete-region (point) (line-end-position))
  21502. (org-indent-line)
  21503. (insert ": "))
  21504. (t (user-error "Cannot insert a fixed-width line here")))))
  21505. ;; Region active.
  21506. (let* ((begin (save-excursion
  21507. (goto-char (region-beginning))
  21508. (line-beginning-position)))
  21509. (end (copy-marker
  21510. (save-excursion
  21511. (goto-char (region-end))
  21512. (unless (eolp) (beginning-of-line))
  21513. (if (save-excursion (re-search-backward "\\S-" begin t))
  21514. (progn (skip-chars-backward " \r\t\n") (point))
  21515. (point)))))
  21516. (all-fixed-width-p
  21517. (catch 'not-all-p
  21518. (save-excursion
  21519. (goto-char begin)
  21520. (skip-chars-forward " \r\t\n")
  21521. (when (eobp) (throw 'not-all-p nil))
  21522. (while (< (point) end)
  21523. (let ((element (org-element-at-point)))
  21524. (if (eq (org-element-type element) 'fixed-width)
  21525. (goto-char (org-element-property :end element))
  21526. (throw 'not-all-p nil))))
  21527. t))))
  21528. (if all-fixed-width-p
  21529. (save-excursion
  21530. (goto-char begin)
  21531. (while (< (point) end)
  21532. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21533. (replace-match
  21534. "" nil nil nil
  21535. (if (= (line-end-position) (match-end 0)) 0 1)))
  21536. (forward-line)))
  21537. (let ((min-ind (point-max)))
  21538. ;; Find minimum indentation across all lines.
  21539. (save-excursion
  21540. (goto-char begin)
  21541. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21542. (setq min-ind 0)
  21543. (catch 'zerop
  21544. (while (< (point) end)
  21545. (unless (looking-at-p "[ \t]*$")
  21546. (let ((ind (org-get-indentation)))
  21547. (setq min-ind (min min-ind ind))
  21548. (when (zerop ind) (throw 'zerop t))))
  21549. (forward-line)))))
  21550. ;; Loop over all lines and add fixed-width markup everywhere
  21551. ;; but in fixed-width lines.
  21552. (save-excursion
  21553. (goto-char begin)
  21554. (while (< (point) end)
  21555. (cond
  21556. ((org-at-heading-p)
  21557. (insert ": ")
  21558. (forward-line)
  21559. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21560. (insert ":")
  21561. (forward-line)))
  21562. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21563. (let* ((element (org-element-at-point))
  21564. (element-end (org-element-property :end element)))
  21565. (if (eq (org-element-type element) 'fixed-width)
  21566. (progn (goto-char element-end)
  21567. (skip-chars-backward " \r\t\n")
  21568. (forward-line))
  21569. (let ((limit (min end element-end)))
  21570. (while (< (point) limit)
  21571. (org-move-to-column min-ind t)
  21572. (insert ": ")
  21573. (forward-line))))))
  21574. (t
  21575. (org-move-to-column min-ind t)
  21576. (insert ": ")
  21577. (forward-line)))))))
  21578. (set-marker end nil))))
  21579. ;;; Comments
  21580. ;; Org comments syntax is quite complex. It requires the entire line
  21581. ;; to be just a comment. Also, even with the right syntax at the
  21582. ;; beginning of line, some some elements (i.e. verse-block or
  21583. ;; example-block) don't accept comments. Usual Emacs comment commands
  21584. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21585. ;; Org still relies on `comment-dwim', but cannot trust
  21586. ;; `comment-only-p'. So, `comment-region-function' and
  21587. ;; `uncomment-region-function' both point
  21588. ;; to`org-comment-or-uncomment-region'. Eventually,
  21589. ;; `org-insert-comment' takes care of insertion of comments at the
  21590. ;; beginning of line.
  21591. ;; `org-setup-comments-handling' install comments related variables
  21592. ;; during `org-mode' initialization.
  21593. (defun org-setup-comments-handling ()
  21594. (interactive)
  21595. (setq-local comment-use-syntax nil)
  21596. (setq-local comment-start "# ")
  21597. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21598. (setq-local comment-insert-comment-function 'org-insert-comment)
  21599. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21600. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21601. (defun org-insert-comment ()
  21602. "Insert an empty comment above current line.
  21603. If the line is empty, insert comment at its beginning. When
  21604. point is within a source block, comment according to the related
  21605. major mode."
  21606. (if (let ((element (org-element-at-point)))
  21607. (and (eq (org-element-type element) 'src-block)
  21608. (< (save-excursion
  21609. (goto-char (org-element-property :post-affiliated element))
  21610. (line-end-position))
  21611. (point))
  21612. (> (save-excursion
  21613. (goto-char (org-element-property :end element))
  21614. (skip-chars-backward " \r\t\n")
  21615. (line-beginning-position))
  21616. (point))))
  21617. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21618. (beginning-of-line)
  21619. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21620. (open-line 1))
  21621. (org-indent-line)
  21622. (insert "# ")))
  21623. (defvar comment-empty-lines) ; From newcomment.el.
  21624. (defun org-comment-or-uncomment-region (beg end &rest _)
  21625. "Comment or uncomment each non-blank line in the region.
  21626. Uncomment each non-blank line between BEG and END if it only
  21627. contains commented lines. Otherwise, comment them. If region is
  21628. strictly within a source block, use appropriate comment syntax."
  21629. (if (let ((element (org-element-at-point)))
  21630. (and (eq (org-element-type element) 'src-block)
  21631. (< (save-excursion
  21632. (goto-char (org-element-property :post-affiliated element))
  21633. (line-end-position))
  21634. beg)
  21635. (>= (save-excursion
  21636. (goto-char (org-element-property :end element))
  21637. (skip-chars-backward " \r\t\n")
  21638. (line-beginning-position))
  21639. end)))
  21640. ;; Translate region boundaries for the Org buffer to the source
  21641. ;; buffer.
  21642. (let ((offset (- end beg)))
  21643. (save-excursion
  21644. (goto-char beg)
  21645. (org-babel-do-in-edit-buffer
  21646. (comment-or-uncomment-region (point) (+ offset (point))))))
  21647. (save-restriction
  21648. ;; Restrict region
  21649. (narrow-to-region (save-excursion (goto-char beg)
  21650. (skip-chars-forward " \r\t\n" end)
  21651. (line-beginning-position))
  21652. (save-excursion (goto-char end)
  21653. (skip-chars-backward " \r\t\n" beg)
  21654. (line-end-position)))
  21655. (let ((uncommentp
  21656. ;; UNCOMMENTP is non-nil when every non blank line between
  21657. ;; BEG and END is a comment.
  21658. (save-excursion
  21659. (goto-char (point-min))
  21660. (while (and (not (eobp))
  21661. (let ((element (org-element-at-point)))
  21662. (and (eq (org-element-type element) 'comment)
  21663. (goto-char (min (point-max)
  21664. (org-element-property
  21665. :end element)))))))
  21666. (eobp))))
  21667. (if uncommentp
  21668. ;; Only blank lines and comments in region: uncomment it.
  21669. (save-excursion
  21670. (goto-char (point-min))
  21671. (while (not (eobp))
  21672. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21673. (replace-match "" nil nil nil 1))
  21674. (forward-line)))
  21675. ;; Comment each line in region.
  21676. (let ((min-indent (point-max)))
  21677. ;; First find the minimum indentation across all lines.
  21678. (save-excursion
  21679. (goto-char (point-min))
  21680. (while (and (not (eobp)) (not (zerop min-indent)))
  21681. (unless (looking-at "[ \t]*$")
  21682. (setq min-indent (min min-indent (current-indentation))))
  21683. (forward-line)))
  21684. ;; Then loop over all lines.
  21685. (save-excursion
  21686. (goto-char (point-min))
  21687. (while (not (eobp))
  21688. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21689. ;; Don't get fooled by invisible text (e.g. link path)
  21690. ;; when moving to column MIN-INDENT.
  21691. (let ((buffer-invisibility-spec nil))
  21692. (org-move-to-column min-indent t))
  21693. (insert comment-start))
  21694. (forward-line)))))))))
  21695. (defun org-comment-dwim (_arg)
  21696. "Call `comment-dwim' within a source edit buffer if needed."
  21697. (interactive "*P")
  21698. (if (org-in-src-block-p)
  21699. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21700. (call-interactively 'comment-dwim)))
  21701. ;;; Timestamps API
  21702. ;; This section contains tools to operate on timestamp objects, as
  21703. ;; returned by, e.g. `org-element-context'.
  21704. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21705. "Encode TIMESTAMP object into Emacs internal time.
  21706. Use end of date range or time range when END is non-nil."
  21707. (apply #'encode-time
  21708. (cons 0
  21709. (mapcar
  21710. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21711. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21712. '(:minute-start :hour-start :day-start :month-start
  21713. :year-start))))))
  21714. (defun org-timestamp-has-time-p (timestamp)
  21715. "Non-nil when TIMESTAMP has a time specified."
  21716. (org-element-property :hour-start timestamp))
  21717. (defun org-timestamp-format (timestamp format &optional end utc)
  21718. "Format a TIMESTAMP object into a string.
  21719. FORMAT is a format specifier to be passed to
  21720. `format-time-string'.
  21721. When optional argument END is non-nil, use end of date-range or
  21722. time-range, if possible.
  21723. When optional argument UTC is non-nil, time will be expressed as
  21724. Universal Time."
  21725. (format-time-string
  21726. format (org-timestamp--to-internal-time timestamp end)
  21727. (and utc t)))
  21728. (defun org-timestamp-split-range (timestamp &optional end)
  21729. "Extract a TIMESTAMP object from a date or time range.
  21730. END, when non-nil, means extract the end of the range.
  21731. Otherwise, extract its start.
  21732. Return a new timestamp object."
  21733. (let ((type (org-element-property :type timestamp)))
  21734. (if (memq type '(active inactive diary)) timestamp
  21735. (let ((split-ts (org-element-copy timestamp)))
  21736. ;; Set new type.
  21737. (org-element-put-property
  21738. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21739. ;; Copy start properties over end properties if END is
  21740. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21741. (let ((p-alist '((:minute-start . :minute-end)
  21742. (:hour-start . :hour-end)
  21743. (:day-start . :day-end)
  21744. (:month-start . :month-end)
  21745. (:year-start . :year-end))))
  21746. (dolist (p-cell p-alist)
  21747. (org-element-put-property
  21748. split-ts
  21749. (funcall (if end #'car #'cdr) p-cell)
  21750. (org-element-property
  21751. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21752. ;; Eventually refresh `:raw-value'.
  21753. (org-element-put-property split-ts :raw-value nil)
  21754. (org-element-put-property
  21755. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21756. (defun org-timestamp-translate (timestamp &optional boundary)
  21757. "Translate TIMESTAMP object to custom format.
  21758. Format string is defined in `org-time-stamp-custom-formats',
  21759. which see.
  21760. When optional argument BOUNDARY is non-nil, it is either the
  21761. symbol `start' or `end'. In this case, only translate the
  21762. starting or ending part of TIMESTAMP if it is a date or time
  21763. range. Otherwise, translate both parts.
  21764. Return timestamp as-is if `org-display-custom-times' is nil or if
  21765. it has a `diary' type."
  21766. (let ((type (org-element-property :type timestamp)))
  21767. (if (or (not org-display-custom-times) (eq type 'diary))
  21768. (org-element-interpret-data timestamp)
  21769. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21770. org-time-stamp-custom-formats)))
  21771. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21772. (concat (org-timestamp-format timestamp fmt)
  21773. "--"
  21774. (org-timestamp-format timestamp fmt t))
  21775. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21776. ;;; Other stuff.
  21777. (defvar reftex-docstruct-symbol)
  21778. (defvar org--rds)
  21779. (defun org-reftex-citation ()
  21780. "Use reftex-citation to insert a citation into the buffer.
  21781. This looks for a line like
  21782. #+BIBLIOGRAPHY: foo plain option:-d
  21783. and derives from it that foo.bib is the bibliography file relevant
  21784. for this document. It then installs the necessary environment for RefTeX
  21785. to work in this buffer and calls `reftex-citation' to insert a citation
  21786. into the buffer.
  21787. Export of such citations to both LaTeX and HTML is handled by the contributed
  21788. package ox-bibtex by Taru Karttunen."
  21789. (interactive)
  21790. (let ((reftex-docstruct-symbol 'org--rds)
  21791. org--rds bib)
  21792. (org-with-wide-buffer
  21793. (let ((case-fold-search t)
  21794. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21795. (if (not (save-excursion
  21796. (or (re-search-forward re nil t)
  21797. (re-search-backward re nil t))))
  21798. (user-error "No bibliography defined in file")
  21799. (setq bib (concat (match-string 1) ".bib")
  21800. org--rds (list (list 'bib bib))))))
  21801. (call-interactively 'reftex-citation)))
  21802. ;;;; Functions extending outline functionality
  21803. (defun org-beginning-of-line (&optional n)
  21804. "Go to the beginning of the current visible line.
  21805. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21806. tags on the first attempt, and only move to after the tags when
  21807. the cursor is already beyond the end of the headline.
  21808. With argument N not nil or 1, move forward N - 1 lines first."
  21809. (interactive "^p")
  21810. (let ((origin (point))
  21811. (special (pcase org-special-ctrl-a/e
  21812. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21813. deactivate-mark)
  21814. ;; First move to a visible line.
  21815. (if (bound-and-true-p visual-line-mode)
  21816. (beginning-of-visual-line n)
  21817. (move-beginning-of-line n)
  21818. ;; `move-beginning-of-line' may leave point after invisible
  21819. ;; characters if line starts with such of these (e.g., with
  21820. ;; a link at column 0). Really move to the beginning of the
  21821. ;; current visible line.
  21822. (beginning-of-line))
  21823. (cond
  21824. ;; No special behavior. Point is already at the beginning of
  21825. ;; a line, logical or visual.
  21826. ((not special))
  21827. ;; `beginning-of-visual-line' left point before logical beginning
  21828. ;; of line: point is at the beginning of a visual line. Bail
  21829. ;; out.
  21830. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21831. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21832. ;; At a headline, special position is before the title, but
  21833. ;; after any TODO keyword or priority cookie.
  21834. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21835. (line-end-position)))
  21836. (bol (point)))
  21837. (if (eq special 'reversed)
  21838. (when (and (= origin bol) (eq last-command this-command))
  21839. (goto-char refpos))
  21840. (when (or (> origin refpos) (= origin bol))
  21841. (goto-char refpos)))))
  21842. ((and (looking-at org-list-full-item-re)
  21843. (memq (org-element-type (save-match-data (org-element-at-point)))
  21844. '(item plain-list)))
  21845. ;; Set special position at first white space character after
  21846. ;; bullet, and check-box, if any.
  21847. (let ((after-bullet
  21848. (let ((box (match-end 3)))
  21849. (cond ((not box) (match-end 1))
  21850. ((eq (char-after box) ?\s) (1+ box))
  21851. (t box)))))
  21852. (if (eq special 'reversed)
  21853. (when (and (= (point) origin) (eq last-command this-command))
  21854. (goto-char after-bullet))
  21855. (when (or (> origin after-bullet) (= (point) origin))
  21856. (goto-char after-bullet)))))
  21857. ;; No special context. Point is already at beginning of line.
  21858. (t nil))))
  21859. (defun org-end-of-line (&optional n)
  21860. "Go to the end of the line, but before ellipsis, if any.
  21861. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21862. tags on the first attempt, and only move to after the tags when
  21863. the cursor is already beyond the end of the headline.
  21864. With argument N not nil or 1, move forward N - 1 lines first."
  21865. (interactive "^p")
  21866. (let ((origin (point))
  21867. (special (pcase org-special-ctrl-a/e
  21868. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21869. deactivate-mark)
  21870. ;; First move to a visible line.
  21871. (if (bound-and-true-p visual-line-mode)
  21872. (beginning-of-visual-line n)
  21873. (move-beginning-of-line n))
  21874. (cond
  21875. ;; At a headline, with tags.
  21876. ((and special
  21877. (save-excursion
  21878. (beginning-of-line)
  21879. (let ((case-fold-search nil))
  21880. (looking-at org-complex-heading-regexp)))
  21881. (match-end 5))
  21882. (let ((tags (save-excursion
  21883. (goto-char (match-beginning 5))
  21884. (skip-chars-backward " \t")
  21885. (point)))
  21886. (visual-end (and (bound-and-true-p visual-line-mode)
  21887. (save-excursion
  21888. (end-of-visual-line)
  21889. (point)))))
  21890. ;; If `end-of-visual-line' brings us before end of line or
  21891. ;; even tags, i.e., the headline spans over multiple visual
  21892. ;; lines, move there.
  21893. (cond ((and visual-end
  21894. (< visual-end tags)
  21895. (<= origin visual-end))
  21896. (goto-char visual-end))
  21897. ((eq special 'reversed)
  21898. (if (and (= origin (line-end-position))
  21899. (eq this-command last-command))
  21900. (goto-char tags)
  21901. (end-of-line)))
  21902. (t
  21903. (if (or (< origin tags) (= origin (line-end-position)))
  21904. (goto-char tags)
  21905. (end-of-line))))))
  21906. ((bound-and-true-p visual-line-mode)
  21907. (let ((bol (line-beginning-position)))
  21908. (end-of-visual-line)
  21909. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21910. ;; end of a line, backtrack and use `end-of-line' instead.
  21911. (when (/= bol (line-beginning-position))
  21912. (goto-char bol)
  21913. (end-of-line))))
  21914. (t (end-of-line)))))
  21915. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21916. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21917. (defun org-backward-sentence (&optional _arg)
  21918. "Go to beginning of sentence, or beginning of table field.
  21919. This will call `backward-sentence' or `org-table-beginning-of-field',
  21920. depending on context."
  21921. (interactive)
  21922. (let* ((element (org-element-at-point))
  21923. (contents-begin (org-element-property :contents-begin element))
  21924. (table (org-element-lineage element '(table) t)))
  21925. (if (and table
  21926. (> (point) contents-begin)
  21927. (<= (point) (org-element-property :contents-end table)))
  21928. (call-interactively #'org-table-beginning-of-field)
  21929. (save-restriction
  21930. (when (and contents-begin
  21931. (< (point-min) contents-begin)
  21932. (> (point) contents-begin))
  21933. (narrow-to-region contents-begin
  21934. (org-element-property :contents-end element)))
  21935. (call-interactively #'backward-sentence)))))
  21936. (defun org-forward-sentence (&optional _arg)
  21937. "Go to end of sentence, or end of table field.
  21938. This will call `forward-sentence' or `org-table-end-of-field',
  21939. depending on context."
  21940. (interactive)
  21941. (let* ((element (org-element-at-point))
  21942. (contents-end (org-element-property :contents-end element))
  21943. (table (org-element-lineage element '(table) t)))
  21944. (if (and table
  21945. (>= (point) (org-element-property :contents-begin table))
  21946. (< (point) contents-end))
  21947. (call-interactively #'org-table-end-of-field)
  21948. (save-restriction
  21949. (when (and contents-end
  21950. (> (point-max) contents-end)
  21951. ;; Skip blank lines between elements.
  21952. (< (org-element-property :end element)
  21953. (save-excursion (goto-char contents-end)
  21954. (skip-chars-forward " \r\t\n"))))
  21955. (narrow-to-region (org-element-property :contents-begin element)
  21956. contents-end))
  21957. (call-interactively #'forward-sentence)))))
  21958. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21959. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21960. (defun org-kill-line (&optional _arg)
  21961. "Kill line, to tags or end of line."
  21962. (interactive)
  21963. (cond
  21964. ((or (not org-special-ctrl-k)
  21965. (bolp)
  21966. (not (org-at-heading-p)))
  21967. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21968. org-ctrl-k-protect-subtree
  21969. (or (eq org-ctrl-k-protect-subtree 'error)
  21970. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21971. (user-error "C-k aborted as it would kill a hidden subtree"))
  21972. (call-interactively
  21973. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21974. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21975. (kill-region (point) (match-beginning 1))
  21976. (org-set-tags nil t))
  21977. (t (kill-region (point) (point-at-eol)))))
  21978. (define-key org-mode-map "\C-k" 'org-kill-line)
  21979. (defun org-yank (&optional arg)
  21980. "Yank. If the kill is a subtree, treat it specially.
  21981. This command will look at the current kill and check if is a single
  21982. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21983. cursor is at the beginning of a line or after the stars of a currently
  21984. empty headline, then the yank is handled specially. How exactly depends
  21985. on the value of the following variables.
  21986. `org-yank-folded-subtrees'
  21987. By default, this variable is non-nil, which results in
  21988. subtree(s) being folded after insertion, except if doing so
  21989. would swallow text after the yanked text.
  21990. `org-yank-adjusted-subtrees'
  21991. When non-nil (the default value is nil), the subtree will be
  21992. promoted or demoted in order to fit into the local outline tree
  21993. structure, which means that the level will be adjusted so that it
  21994. becomes the smaller one of the two *visible* surrounding headings.
  21995. Any prefix to this command will cause `yank' to be called directly with
  21996. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21997. will just
  21998. plainly yank the text as it is.
  21999. \[1] The test checks if the first non-white line is a heading
  22000. and if there are no other headings with fewer stars."
  22001. (interactive "P")
  22002. (org-yank-generic 'yank arg))
  22003. (defun org-yank-generic (command arg)
  22004. "Perform some yank-like command.
  22005. This function implements the behavior described in the `org-yank'
  22006. documentation. However, it has been generalized to work for any
  22007. interactive command with similar behavior."
  22008. ;; pretend to be command COMMAND
  22009. (setq this-command command)
  22010. (if arg
  22011. (call-interactively command)
  22012. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  22013. (and (org-kill-is-subtree-p)
  22014. (or (bolp)
  22015. (and (looking-at "[ \t]*$")
  22016. (string-match
  22017. "\\`\\*+\\'"
  22018. (buffer-substring (point-at-bol) (point)))))))
  22019. swallowp)
  22020. (cond
  22021. ((and subtreep org-yank-folded-subtrees)
  22022. (let ((beg (point))
  22023. end)
  22024. (if (and subtreep org-yank-adjusted-subtrees)
  22025. (org-paste-subtree nil nil 'for-yank)
  22026. (call-interactively command))
  22027. (setq end (point))
  22028. (goto-char beg)
  22029. (when (and (bolp) subtreep
  22030. (not (setq swallowp
  22031. (org-yank-folding-would-swallow-text beg end))))
  22032. (org-with-limited-levels
  22033. (or (looking-at org-outline-regexp)
  22034. (re-search-forward org-outline-regexp-bol end t))
  22035. (while (and (< (point) end) (looking-at org-outline-regexp))
  22036. (outline-hide-subtree)
  22037. (org-cycle-show-empty-lines 'folded)
  22038. (condition-case nil
  22039. (outline-forward-same-level 1)
  22040. (error (goto-char end))))))
  22041. (when swallowp
  22042. (message
  22043. "Inserted text not folded because that would swallow text"))
  22044. (goto-char end)
  22045. (skip-chars-forward " \t\n\r")
  22046. (beginning-of-line 1)
  22047. (push-mark beg 'nomsg)))
  22048. ((and subtreep org-yank-adjusted-subtrees)
  22049. (let ((beg (point-at-bol)))
  22050. (org-paste-subtree nil nil 'for-yank)
  22051. (push-mark beg 'nomsg)))
  22052. (t
  22053. (call-interactively command))))))
  22054. (defun org-yank-folding-would-swallow-text (beg end)
  22055. "Would hide-subtree at BEG swallow any text after END?"
  22056. (let (level)
  22057. (org-with-limited-levels
  22058. (save-excursion
  22059. (goto-char beg)
  22060. (when (or (looking-at org-outline-regexp)
  22061. (re-search-forward org-outline-regexp-bol end t))
  22062. (setq level (org-outline-level)))
  22063. (goto-char end)
  22064. (skip-chars-forward " \t\r\n\v\f")
  22065. (not (or (eobp)
  22066. (and (bolp) (looking-at-p org-outline-regexp)
  22067. (<= (org-outline-level) level))))))))
  22068. (define-key org-mode-map "\C-y" 'org-yank)
  22069. (defun org-truely-invisible-p ()
  22070. "Check if point is at a character currently not visible.
  22071. This version does not only check the character property, but also
  22072. `visible-mode'."
  22073. ;; Early versions of noutline don't have `outline-invisible-p'.
  22074. (unless (bound-and-true-p visible-mode)
  22075. (outline-invisible-p)))
  22076. (defun org-invisible-p2 ()
  22077. "Check if point is at a character currently not visible."
  22078. (save-excursion
  22079. (when (and (eolp) (not (bobp))) (backward-char 1))
  22080. ;; Early versions of noutline don't have `outline-invisible-p'.
  22081. (outline-invisible-p)))
  22082. (defun org-back-to-heading (&optional invisible-ok)
  22083. "Call `outline-back-to-heading', but provide a better error message."
  22084. (condition-case nil
  22085. (outline-back-to-heading invisible-ok)
  22086. (error (error "Before first headline at position %d in buffer %s"
  22087. (point) (current-buffer)))))
  22088. (defun org-before-first-heading-p ()
  22089. "Before first heading?"
  22090. (save-excursion
  22091. (end-of-line)
  22092. (null (re-search-backward org-outline-regexp-bol nil t))))
  22093. (defun org-at-heading-p (&optional ignored)
  22094. (outline-on-heading-p t))
  22095. (defun org-in-commented-heading-p (&optional no-inheritance)
  22096. "Non-nil if point is under a commented heading.
  22097. This function also checks ancestors of the current headline,
  22098. unless optional argument NO-INHERITANCE is non-nil."
  22099. (cond
  22100. ((org-before-first-heading-p) nil)
  22101. ((let ((headline (nth 4 (org-heading-components))))
  22102. (and headline
  22103. (let ((case-fold-search nil))
  22104. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22105. headline)))))
  22106. (no-inheritance nil)
  22107. (t
  22108. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22109. (defun org-at-comment-p nil
  22110. "Is cursor in a commented line?"
  22111. (save-excursion
  22112. (save-match-data
  22113. (beginning-of-line)
  22114. (looking-at "^[ \t]*# "))))
  22115. (defun org-at-drawer-p nil
  22116. "Is cursor at a drawer keyword?"
  22117. (save-excursion
  22118. (move-beginning-of-line 1)
  22119. (looking-at org-drawer-regexp)))
  22120. (defun org-at-block-p nil
  22121. "Is cursor at a block keyword?"
  22122. (save-excursion
  22123. (move-beginning-of-line 1)
  22124. (looking-at org-block-regexp)))
  22125. (defun org-point-at-end-of-empty-headline ()
  22126. "If point is at the end of an empty headline, return t, else nil.
  22127. If the heading only contains a TODO keyword, it is still still considered
  22128. empty."
  22129. (let ((case-fold-search nil))
  22130. (and (looking-at "[ \t]*$")
  22131. org-todo-line-regexp
  22132. (save-excursion
  22133. (beginning-of-line)
  22134. (looking-at org-todo-line-regexp)
  22135. (string= (match-string 3) "")))))
  22136. (defun org-at-heading-or-item-p ()
  22137. (or (org-at-heading-p) (org-at-item-p)))
  22138. (defun org-at-target-p ()
  22139. (or (org-in-regexp org-radio-target-regexp)
  22140. (org-in-regexp org-target-regexp)))
  22141. ;; Compatibility alias with Org versions < 7.8.03
  22142. (defalias 'org-on-target-p 'org-at-target-p)
  22143. (defun org-up-heading-all (arg)
  22144. "Move to the heading line of which the present line is a subheading.
  22145. This function considers both visible and invisible heading lines.
  22146. With argument, move up ARG levels."
  22147. (outline-up-heading arg t))
  22148. (defun org-up-heading-safe ()
  22149. "Move to the heading line of which the present line is a subheading.
  22150. This version will not throw an error. It will return the level of the
  22151. headline found, or nil if no higher level is found.
  22152. Also, this function will be a lot faster than `outline-up-heading',
  22153. because it relies on stars being the outline starters. This can really
  22154. make a significant difference in outlines with very many siblings."
  22155. (when (ignore-errors (org-back-to-heading t))
  22156. (let ((level-up (1- (funcall outline-level))))
  22157. (and (> level-up 0)
  22158. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22159. (funcall outline-level)))))
  22160. (defun org-first-sibling-p ()
  22161. "Is this heading the first child of its parents?"
  22162. (interactive)
  22163. (let ((re org-outline-regexp-bol)
  22164. level l)
  22165. (unless (org-at-heading-p t)
  22166. (user-error "Not at a heading"))
  22167. (setq level (funcall outline-level))
  22168. (save-excursion
  22169. (if (not (re-search-backward re nil t))
  22170. t
  22171. (setq l (funcall outline-level))
  22172. (< l level)))))
  22173. (defun org-goto-sibling (&optional previous)
  22174. "Goto the next sibling, even if it is invisible.
  22175. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22176. when a sibling was found. When none is found, return nil and don't
  22177. move point."
  22178. (let ((fun (if previous 're-search-backward 're-search-forward))
  22179. (pos (point))
  22180. (re org-outline-regexp-bol)
  22181. level l)
  22182. (when (ignore-errors (org-back-to-heading t))
  22183. (setq level (funcall outline-level))
  22184. (catch 'exit
  22185. (or previous (forward-char 1))
  22186. (while (funcall fun re nil t)
  22187. (setq l (funcall outline-level))
  22188. (when (< l level) (goto-char pos) (throw 'exit nil))
  22189. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22190. (goto-char pos)
  22191. nil))))
  22192. (defun org-show-siblings ()
  22193. "Show all siblings of the current headline."
  22194. (save-excursion
  22195. (while (org-goto-sibling) (org-flag-heading nil)))
  22196. (save-excursion
  22197. (while (org-goto-sibling 'previous)
  22198. (org-flag-heading nil))))
  22199. (defun org-goto-first-child ()
  22200. "Goto the first child, even if it is invisible.
  22201. Return t when a child was found. Otherwise don't move point and
  22202. return nil."
  22203. (let (level (pos (point)) (re org-outline-regexp-bol))
  22204. (when (ignore-errors (org-back-to-heading t))
  22205. (setq level (outline-level))
  22206. (forward-char 1)
  22207. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22208. (progn (goto-char (match-beginning 0)) t)
  22209. (goto-char pos) nil))))
  22210. (defun org-show-hidden-entry ()
  22211. "Show an entry where even the heading is hidden."
  22212. (save-excursion
  22213. (org-show-entry)))
  22214. (defun org-flag-heading (flag &optional entry)
  22215. "Flag the current heading. FLAG non-nil means make invisible.
  22216. When ENTRY is non-nil, show the entire entry."
  22217. (save-excursion
  22218. (org-back-to-heading t)
  22219. ;; Check if we should show the entire entry
  22220. (if entry
  22221. (progn
  22222. (org-show-entry)
  22223. (save-excursion
  22224. (and (outline-next-heading)
  22225. (org-flag-heading nil))))
  22226. (outline-flag-region (max (point-min) (1- (point)))
  22227. (save-excursion (outline-end-of-heading) (point))
  22228. flag))))
  22229. (defun org-get-next-sibling ()
  22230. "Move to next heading of the same level, and return point.
  22231. If there is no such heading, return nil.
  22232. This is like outline-next-sibling, but invisible headings are ok."
  22233. (let ((level (funcall outline-level)))
  22234. (outline-next-heading)
  22235. (while (and (not (eobp)) (> (funcall outline-level) level))
  22236. (outline-next-heading))
  22237. (unless (or (eobp) (< (funcall outline-level) level))
  22238. (point))))
  22239. (defun org-get-last-sibling ()
  22240. "Move to previous heading of the same level, and return point.
  22241. If there is no such heading, return nil."
  22242. (let ((opoint (point))
  22243. (level (funcall outline-level)))
  22244. (outline-previous-heading)
  22245. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22246. (while (and (> (funcall outline-level) level)
  22247. (not (bobp)))
  22248. (outline-previous-heading))
  22249. (unless (< (funcall outline-level) level)
  22250. (point)))))
  22251. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22252. "Goto to the end of a subtree."
  22253. ;; This contains an exact copy of the original function, but it uses
  22254. ;; `org-back-to-heading', to make it work also in invisible
  22255. ;; trees. And is uses an invisible-ok argument.
  22256. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22257. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22258. ;; with many children and grandchildren etc, this can be much faster
  22259. ;; than the outline version.
  22260. (org-back-to-heading invisible-ok)
  22261. (let ((first t)
  22262. (level (funcall outline-level)))
  22263. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22264. ;; A true heading (not a plain list item), in Org
  22265. ;; This means we can easily find the end by looking
  22266. ;; only for the right number of stars. Using a regexp to do
  22267. ;; this is so much faster than using a Lisp loop.
  22268. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22269. (forward-char 1)
  22270. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22271. ;; something else, do it the slow way
  22272. (while (and (not (eobp))
  22273. (or first (> (funcall outline-level) level)))
  22274. (setq first nil)
  22275. (outline-next-heading)))
  22276. (unless to-heading
  22277. (when (memq (preceding-char) '(?\n ?\^M))
  22278. ;; Go to end of line before heading
  22279. (forward-char -1)
  22280. (when (memq (preceding-char) '(?\n ?\^M))
  22281. ;; leave blank line before heading
  22282. (forward-char -1)))))
  22283. (point))
  22284. (defun org-end-of-meta-data (&optional full)
  22285. "Skip planning line and properties drawer in current entry.
  22286. When optional argument FULL is non-nil, also skip empty lines,
  22287. clocking lines and regular drawers at the beginning of the
  22288. entry."
  22289. (org-back-to-heading t)
  22290. (forward-line)
  22291. (when (looking-at-p org-planning-line-re) (forward-line))
  22292. (when (looking-at org-property-drawer-re)
  22293. (goto-char (match-end 0))
  22294. (forward-line))
  22295. (when (and full (not (org-at-heading-p)))
  22296. (catch 'exit
  22297. (let ((end (save-excursion (outline-next-heading) (point)))
  22298. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22299. (while (not (eobp))
  22300. (cond ((looking-at-p org-drawer-regexp)
  22301. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22302. (forward-line)
  22303. (throw 'exit t)))
  22304. ((looking-at-p re) (forward-line))
  22305. (t (throw 'exit t))))))))
  22306. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22307. "Move forward to the ARG'th subheading at same level as this one.
  22308. Stop at the first and last subheadings of a superior heading.
  22309. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22310. non-nil it will also look at invisible ones."
  22311. (interactive "p")
  22312. (let ((backward? (and arg (< arg 0))))
  22313. (if (org-before-first-heading-p)
  22314. (if backward? (goto-char (point-min)) (outline-next-heading))
  22315. (org-back-to-heading invisible-ok)
  22316. (unless backward? (end-of-line)) ;do not match current headline
  22317. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22318. (f (if backward? #'re-search-backward #'re-search-forward))
  22319. (count (if arg (abs arg) 1))
  22320. (result (point)))
  22321. (while (and (> count 0)
  22322. (funcall f org-outline-regexp-bol nil 'move))
  22323. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22324. (cond ((< l level) (setq count 0))
  22325. ((and (= l level)
  22326. (or invisible-ok
  22327. (not (outline-invisible-p
  22328. (line-beginning-position)))))
  22329. (cl-decf count)
  22330. (when (= l level) (setq result (point)))))))
  22331. (goto-char result))
  22332. (beginning-of-line))))
  22333. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22334. "Move backward to the ARG'th subheading at same level as this one.
  22335. Stop at the first and last subheadings of a superior heading."
  22336. (interactive "p")
  22337. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22338. (defun org-next-visible-heading (arg)
  22339. "Move to the next visible heading.
  22340. This function wraps `outline-next-visible-heading' with
  22341. `org-with-limited-levels' in order to skip over inline tasks and
  22342. respect customization of `org-odd-levels-only'."
  22343. (interactive "p")
  22344. (org-with-limited-levels
  22345. (outline-next-visible-heading arg)))
  22346. (defun org-previous-visible-heading (arg)
  22347. "Move to the previous visible heading.
  22348. This function wraps `outline-previous-visible-heading' with
  22349. `org-with-limited-levels' in order to skip over inline tasks and
  22350. respect customization of `org-odd-levels-only'."
  22351. (interactive "p")
  22352. (org-with-limited-levels
  22353. (outline-previous-visible-heading arg)))
  22354. (defun org-next-block (arg &optional backward block-regexp)
  22355. "Jump to the next block.
  22356. With a prefix argument ARG, jump forward ARG many blocks.
  22357. When BACKWARD is non-nil, jump to the previous block.
  22358. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22359. Match data is set according to this regexp when the function
  22360. returns.
  22361. Return point at beginning of the opening line of found block.
  22362. Throw an error if no block is found."
  22363. (interactive "p")
  22364. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22365. (case-fold-search t)
  22366. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22367. (count (or arg 1))
  22368. (origin (point))
  22369. last-element)
  22370. (if backward (beginning-of-line) (end-of-line))
  22371. (while (and (> count 0) (funcall search-fn re nil t))
  22372. (let ((element (save-excursion
  22373. (goto-char (match-beginning 0))
  22374. (save-match-data (org-element-at-point)))))
  22375. (when (and (memq (org-element-type element)
  22376. '(center-block comment-block dynamic-block
  22377. example-block export-block quote-block
  22378. special-block src-block verse-block))
  22379. (<= (match-beginning 0)
  22380. (org-element-property :post-affiliated element)))
  22381. (setq last-element element)
  22382. (cl-decf count))))
  22383. (if (= count 0)
  22384. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22385. (save-match-data (org-show-context)))
  22386. (goto-char origin)
  22387. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22388. (defun org-previous-block (arg &optional block-regexp)
  22389. "Jump to the previous block.
  22390. With a prefix argument ARG, jump backward ARG many source blocks.
  22391. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22392. (interactive "p")
  22393. (org-next-block arg t block-regexp))
  22394. (defun org-forward-paragraph ()
  22395. "Move forward to beginning of next paragraph or equivalent.
  22396. The function moves point to the beginning of the next visible
  22397. structural element, which can be a paragraph, a table, a list
  22398. item, etc. It also provides some special moves for convenience:
  22399. - On an affiliated keyword, jump to the beginning of the
  22400. relative element.
  22401. - On an item or a footnote definition, move to the second
  22402. element inside, if any.
  22403. - On a table or a property drawer, jump after it.
  22404. - On a verse or source block, stop after blank lines."
  22405. (interactive)
  22406. (when (eobp) (user-error "Cannot move further down"))
  22407. (let* ((deactivate-mark nil)
  22408. (element (org-element-at-point))
  22409. (type (org-element-type element))
  22410. (post-affiliated (org-element-property :post-affiliated element))
  22411. (contents-begin (org-element-property :contents-begin element))
  22412. (contents-end (org-element-property :contents-end element))
  22413. (end (let ((end (org-element-property :end element)) (parent element))
  22414. (while (and (setq parent (org-element-property :parent parent))
  22415. (= (org-element-property :contents-end parent) end))
  22416. (setq end (org-element-property :end parent)))
  22417. end)))
  22418. (cond ((not element)
  22419. (skip-chars-forward " \r\t\n")
  22420. (or (eobp) (beginning-of-line)))
  22421. ;; On affiliated keywords, move to element's beginning.
  22422. ((< (point) post-affiliated)
  22423. (goto-char post-affiliated))
  22424. ;; At a table row, move to the end of the table. Similarly,
  22425. ;; at a node property, move to the end of the property
  22426. ;; drawer.
  22427. ((memq type '(node-property table-row))
  22428. (goto-char (org-element-property
  22429. :end (org-element-property :parent element))))
  22430. ((memq type '(property-drawer table)) (goto-char end))
  22431. ;; Consider blank lines as separators in verse and source
  22432. ;; blocks to ease editing.
  22433. ((memq type '(src-block verse-block))
  22434. (when (eq type 'src-block)
  22435. (setq contents-end
  22436. (save-excursion (goto-char end)
  22437. (skip-chars-backward " \r\t\n")
  22438. (line-beginning-position))))
  22439. (beginning-of-line)
  22440. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22441. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22442. (goto-char end)
  22443. (skip-chars-forward " \r\t\n")
  22444. (if (= (point) contents-end) (goto-char end)
  22445. (beginning-of-line))))
  22446. ;; With no contents, just skip element.
  22447. ((not contents-begin) (goto-char end))
  22448. ;; If contents are invisible, skip the element altogether.
  22449. ((outline-invisible-p (line-end-position))
  22450. (cl-case type
  22451. (headline
  22452. (org-with-limited-levels (outline-next-visible-heading 1)))
  22453. ;; At a plain list, make sure we move to the next item
  22454. ;; instead of skipping the whole list.
  22455. (plain-list (forward-char)
  22456. (org-forward-paragraph))
  22457. (otherwise (goto-char end))))
  22458. ((>= (point) contents-end) (goto-char end))
  22459. ((>= (point) contents-begin)
  22460. ;; This can only happen on paragraphs and plain lists.
  22461. (cl-case type
  22462. (paragraph (goto-char end))
  22463. ;; At a plain list, try to move to second element in
  22464. ;; first item, if possible.
  22465. (plain-list (end-of-line)
  22466. (org-forward-paragraph))))
  22467. ;; When contents start on the middle of a line (e.g. in
  22468. ;; items and footnote definitions), try to reach first
  22469. ;; element starting after current line.
  22470. ((> (line-end-position) contents-begin)
  22471. (end-of-line)
  22472. (org-forward-paragraph))
  22473. (t (goto-char contents-begin)))))
  22474. (defun org-backward-paragraph ()
  22475. "Move backward to start of previous paragraph or equivalent.
  22476. The function moves point to the beginning of the current
  22477. structural element, which can be a paragraph, a table, a list
  22478. item, etc., or to the beginning of the previous visible one if
  22479. point is already there. It also provides some special moves for
  22480. convenience:
  22481. - On an affiliated keyword, jump to the first one.
  22482. - On a table or a property drawer, move to its beginning.
  22483. - On a verse or source block, stop before blank lines."
  22484. (interactive)
  22485. (when (bobp) (user-error "Cannot move further up"))
  22486. (let* ((deactivate-mark nil)
  22487. (element (org-element-at-point))
  22488. (type (org-element-type element))
  22489. (contents-begin (org-element-property :contents-begin element))
  22490. (contents-end (org-element-property :contents-end element))
  22491. (post-affiliated (org-element-property :post-affiliated element))
  22492. (begin (org-element-property :begin element)))
  22493. (cond
  22494. ((not element) (goto-char (point-min)))
  22495. ((= (point) begin)
  22496. (backward-char)
  22497. (org-backward-paragraph))
  22498. ((<= (point) post-affiliated) (goto-char begin))
  22499. ((memq type '(node-property table-row))
  22500. (goto-char (org-element-property
  22501. :post-affiliated (org-element-property :parent element))))
  22502. ((memq type '(property-drawer table)) (goto-char begin))
  22503. ((memq type '(src-block verse-block))
  22504. (when (eq type 'src-block)
  22505. (setq contents-begin
  22506. (save-excursion (goto-char begin) (forward-line) (point))))
  22507. (if (= (point) contents-begin) (goto-char post-affiliated)
  22508. ;; Inside a verse block, see blank lines as paragraph
  22509. ;; separators.
  22510. (let ((origin (point)))
  22511. (skip-chars-backward " \r\t\n" contents-begin)
  22512. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22513. (skip-chars-forward " \r\t\n" origin)
  22514. (if (= (point) origin) (goto-char contents-begin)
  22515. (beginning-of-line))))))
  22516. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22517. ((eq type 'paragraph)
  22518. (goto-char contents-begin)
  22519. ;; When at first paragraph in an item or a footnote definition,
  22520. ;; move directly to beginning of line.
  22521. (let ((parent-contents
  22522. (org-element-property
  22523. :contents-begin (org-element-property :parent element))))
  22524. (when (and parent-contents (= parent-contents contents-begin))
  22525. (beginning-of-line))))
  22526. ;; At the end of a greater element, move to the beginning of the
  22527. ;; last element within.
  22528. ((>= (point) contents-end)
  22529. (goto-char (1- contents-end))
  22530. (org-backward-paragraph))
  22531. (t (goto-char (or post-affiliated begin))))
  22532. ;; Ensure we never leave point invisible.
  22533. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22534. (defun org-forward-element ()
  22535. "Move forward by one element.
  22536. Move to the next element at the same level, when possible."
  22537. (interactive)
  22538. (cond ((eobp) (user-error "Cannot move further down"))
  22539. ((org-with-limited-levels (org-at-heading-p))
  22540. (let ((origin (point)))
  22541. (goto-char (org-end-of-subtree nil t))
  22542. (unless (org-with-limited-levels (org-at-heading-p))
  22543. (goto-char origin)
  22544. (user-error "Cannot move further down"))))
  22545. (t
  22546. (let* ((elem (org-element-at-point))
  22547. (end (org-element-property :end elem))
  22548. (parent (org-element-property :parent elem)))
  22549. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22550. (goto-char (org-element-property :end parent)))
  22551. ((integer-or-marker-p end) (goto-char end))
  22552. (t (message "No element at point")))))))
  22553. (defun org-backward-element ()
  22554. "Move backward by one element.
  22555. Move to the previous element at the same level, when possible."
  22556. (interactive)
  22557. (cond ((bobp) (user-error "Cannot move further up"))
  22558. ((org-with-limited-levels (org-at-heading-p))
  22559. ;; At a headline, move to the previous one, if any, or stay
  22560. ;; here.
  22561. (let ((origin (point)))
  22562. (org-with-limited-levels (org-backward-heading-same-level 1))
  22563. ;; When current headline has no sibling above, move to its
  22564. ;; parent.
  22565. (when (= (point) origin)
  22566. (or (org-with-limited-levels (org-up-heading-safe))
  22567. (progn (goto-char origin)
  22568. (user-error "Cannot move further up"))))))
  22569. (t
  22570. (let* ((elem (org-element-at-point))
  22571. (beg (org-element-property :begin elem)))
  22572. (cond
  22573. ;; Move to beginning of current element if point isn't
  22574. ;; there already.
  22575. ((null beg) (message "No element at point"))
  22576. ((/= (point) beg) (goto-char beg))
  22577. (t (goto-char beg)
  22578. (skip-chars-backward " \r\t\n")
  22579. (unless (bobp)
  22580. (let ((prev (org-element-at-point)))
  22581. (goto-char (org-element-property :begin prev))
  22582. (while (and (setq prev (org-element-property :parent prev))
  22583. (<= (org-element-property :end prev) beg))
  22584. (goto-char (org-element-property :begin prev)))))))))))
  22585. (defun org-up-element ()
  22586. "Move to upper element."
  22587. (interactive)
  22588. (if (org-with-limited-levels (org-at-heading-p))
  22589. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22590. (let* ((elem (org-element-at-point))
  22591. (parent (org-element-property :parent elem)))
  22592. (if parent (goto-char (org-element-property :begin parent))
  22593. (if (org-with-limited-levels (org-before-first-heading-p))
  22594. (user-error "No surrounding element")
  22595. (org-with-limited-levels (org-back-to-heading)))))))
  22596. (defvar org-element-greater-elements)
  22597. (defun org-down-element ()
  22598. "Move to inner element."
  22599. (interactive)
  22600. (let ((element (org-element-at-point)))
  22601. (cond
  22602. ((memq (org-element-type element) '(plain-list table))
  22603. (goto-char (org-element-property :contents-begin element))
  22604. (forward-char))
  22605. ((memq (org-element-type element) org-element-greater-elements)
  22606. ;; If contents are hidden, first disclose them.
  22607. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22608. (goto-char (or (org-element-property :contents-begin element)
  22609. (user-error "No content for this element"))))
  22610. (t (user-error "No inner element")))))
  22611. (defun org-drag-element-backward ()
  22612. "Move backward element at point."
  22613. (interactive)
  22614. (let ((elem (or (org-element-at-point)
  22615. (user-error "No element at point"))))
  22616. (if (eq (org-element-type elem) 'headline)
  22617. ;; Preserve point when moving a whole tree, even if point was
  22618. ;; on blank lines below the headline.
  22619. (let ((offset (skip-chars-backward " \t\n")))
  22620. (unwind-protect (org-move-subtree-up)
  22621. (forward-char (- offset))))
  22622. (let ((prev-elem
  22623. (save-excursion
  22624. (goto-char (org-element-property :begin elem))
  22625. (skip-chars-backward " \r\t\n")
  22626. (unless (bobp)
  22627. (let* ((beg (org-element-property :begin elem))
  22628. (prev (org-element-at-point))
  22629. (up prev))
  22630. (while (and (setq up (org-element-property :parent up))
  22631. (<= (org-element-property :end up) beg))
  22632. (setq prev up))
  22633. prev)))))
  22634. ;; Error out if no previous element or previous element is
  22635. ;; a parent of the current one.
  22636. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22637. (user-error "Cannot drag element backward")
  22638. (let ((pos (point)))
  22639. (org-element-swap-A-B prev-elem elem)
  22640. (goto-char (+ (org-element-property :begin prev-elem)
  22641. (- pos (org-element-property :begin elem))))))))))
  22642. (defun org-drag-element-forward ()
  22643. "Move forward element at point."
  22644. (interactive)
  22645. (let* ((pos (point))
  22646. (elem (or (org-element-at-point)
  22647. (user-error "No element at point"))))
  22648. (when (= (point-max) (org-element-property :end elem))
  22649. (user-error "Cannot drag element forward"))
  22650. (goto-char (org-element-property :end elem))
  22651. (let ((next-elem (org-element-at-point)))
  22652. (when (or (org-element-nested-p elem next-elem)
  22653. (and (eq (org-element-type next-elem) 'headline)
  22654. (not (eq (org-element-type elem) 'headline))))
  22655. (goto-char pos)
  22656. (user-error "Cannot drag element forward"))
  22657. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22658. ;; body's length (without final blanks) and by the length of
  22659. ;; blanks between ELEM and NEXT-ELEM.
  22660. (let ((size-next (- (save-excursion
  22661. (goto-char (org-element-property :end next-elem))
  22662. (skip-chars-backward " \r\t\n")
  22663. (forward-line)
  22664. ;; Small correction if buffer doesn't end
  22665. ;; with a newline character.
  22666. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22667. (org-element-property :begin next-elem)))
  22668. (size-blank (- (org-element-property :end elem)
  22669. (save-excursion
  22670. (goto-char (org-element-property :end elem))
  22671. (skip-chars-backward " \r\t\n")
  22672. (forward-line)
  22673. (point)))))
  22674. (org-element-swap-A-B elem next-elem)
  22675. (goto-char (+ pos size-next size-blank))))))
  22676. (defun org-drag-line-forward (arg)
  22677. "Drag the line at point ARG lines forward."
  22678. (interactive "p")
  22679. (dotimes (_ (abs arg))
  22680. (let ((c (current-column)))
  22681. (if (< 0 arg)
  22682. (progn
  22683. (beginning-of-line 2)
  22684. (transpose-lines 1)
  22685. (beginning-of-line 0))
  22686. (transpose-lines 1)
  22687. (beginning-of-line -1))
  22688. (org-move-to-column c))))
  22689. (defun org-drag-line-backward (arg)
  22690. "Drag the line at point ARG lines backward."
  22691. (interactive "p")
  22692. (org-drag-line-forward (- arg)))
  22693. (defun org-mark-element ()
  22694. "Put point at beginning of this element, mark at end.
  22695. Interactively, if this command is repeated or (in Transient Mark
  22696. mode) if the mark is active, it marks the next element after the
  22697. ones already marked."
  22698. (interactive)
  22699. (let (deactivate-mark)
  22700. (if (and (called-interactively-p 'any)
  22701. (or (and (eq last-command this-command) (mark t))
  22702. (and transient-mark-mode mark-active)))
  22703. (set-mark
  22704. (save-excursion
  22705. (goto-char (mark))
  22706. (goto-char (org-element-property :end (org-element-at-point)))))
  22707. (let ((element (org-element-at-point)))
  22708. (end-of-line)
  22709. (push-mark (org-element-property :end element) t t)
  22710. (goto-char (org-element-property :begin element))))))
  22711. (defun org-narrow-to-element ()
  22712. "Narrow buffer to current element."
  22713. (interactive)
  22714. (let ((elem (org-element-at-point)))
  22715. (cond
  22716. ((eq (car elem) 'headline)
  22717. (narrow-to-region
  22718. (org-element-property :begin elem)
  22719. (org-element-property :end elem)))
  22720. ((memq (car elem) org-element-greater-elements)
  22721. (narrow-to-region
  22722. (org-element-property :contents-begin elem)
  22723. (org-element-property :contents-end elem)))
  22724. (t
  22725. (narrow-to-region
  22726. (org-element-property :begin elem)
  22727. (org-element-property :end elem))))))
  22728. (defun org-transpose-element ()
  22729. "Transpose current and previous elements, keeping blank lines between.
  22730. Point is moved after both elements."
  22731. (interactive)
  22732. (org-skip-whitespace)
  22733. (let ((end (org-element-property :end (org-element-at-point))))
  22734. (org-drag-element-backward)
  22735. (goto-char end)))
  22736. (defun org-unindent-buffer ()
  22737. "Un-indent the visible part of the buffer.
  22738. Relative indentation (between items, inside blocks, etc.) isn't
  22739. modified."
  22740. (interactive)
  22741. (unless (eq major-mode 'org-mode)
  22742. (user-error "Cannot un-indent a buffer not in Org mode"))
  22743. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22744. (unindent-tree
  22745. (lambda (contents)
  22746. (dolist (element (reverse contents))
  22747. (if (memq (org-element-type element) '(headline section))
  22748. (funcall unindent-tree (org-element-contents element))
  22749. (save-excursion
  22750. (save-restriction
  22751. (narrow-to-region
  22752. (org-element-property :begin element)
  22753. (org-element-property :end element))
  22754. (org-do-remove-indentation))))))))
  22755. (funcall unindent-tree (org-element-contents parse-tree))))
  22756. (defun org-show-children (&optional level)
  22757. "Show all direct subheadings of this heading.
  22758. Prefix arg LEVEL is how many levels below the current level
  22759. should be shown. Default is enough to cause the following
  22760. heading to appear."
  22761. (interactive "p")
  22762. ;; If `orgstruct-mode' is active, use the slower version.
  22763. (if orgstruct-mode (call-interactively #'outline-show-children)
  22764. (save-excursion
  22765. (org-back-to-heading t)
  22766. (let* ((current-level (funcall outline-level))
  22767. (max-level (org-get-valid-level
  22768. current-level
  22769. (if level (prefix-numeric-value level) 1)))
  22770. (end (save-excursion (org-end-of-subtree t t)))
  22771. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22772. (past-first-child nil)
  22773. ;; Make sure to skip inlinetasks.
  22774. (re (format regexp-fmt
  22775. current-level
  22776. (cond
  22777. ((not (featurep 'org-inlinetask)) "")
  22778. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22779. 3))
  22780. (t (1- org-inlinetask-min-level))))))
  22781. ;; Display parent heading.
  22782. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22783. (forward-line)
  22784. ;; Display children. First child may be deeper than expected
  22785. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22786. ;; MAX-LEVEL accordingly.
  22787. (while (re-search-forward re end t)
  22788. (unless past-first-child
  22789. (setq re (format regexp-fmt
  22790. current-level
  22791. (max (funcall outline-level) max-level)))
  22792. (setq past-first-child t))
  22793. (outline-flag-region
  22794. (line-end-position 0) (line-end-position) nil))))))
  22795. (defun org-show-subtree ()
  22796. "Show everything after this heading at deeper levels."
  22797. (interactive)
  22798. (outline-flag-region
  22799. (point)
  22800. (save-excursion
  22801. (org-end-of-subtree t t))
  22802. nil))
  22803. (defun org-show-entry ()
  22804. "Show the body directly following this heading.
  22805. Show the heading too, if it is currently invisible."
  22806. (interactive)
  22807. (save-excursion
  22808. (ignore-errors
  22809. (org-back-to-heading t)
  22810. (outline-flag-region
  22811. (max (point-min) (1- (point)))
  22812. (save-excursion
  22813. (if (re-search-forward
  22814. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22815. (match-beginning 1)
  22816. (point-max)))
  22817. nil)
  22818. (org-cycle-hide-drawers 'children))))
  22819. (defun org-make-options-regexp (kwds &optional extra)
  22820. "Make a regular expression for keyword lines.
  22821. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22822. when non-nil, is a regexp matching keywords names."
  22823. (concat "^[ \t]*#\\+\\("
  22824. (regexp-opt kwds)
  22825. (and extra (concat (and kwds "\\|") extra))
  22826. "\\):[ \t]*\\(.*\\)"))
  22827. ;;;; Integration with and fixes for other packages
  22828. ;;; Imenu support
  22829. (defvar-local org-imenu-markers nil
  22830. "All markers currently used by Imenu.")
  22831. (defun org-imenu-new-marker (&optional pos)
  22832. "Return a new marker for use by Imenu, and remember the marker."
  22833. (let ((m (make-marker)))
  22834. (move-marker m (or pos (point)))
  22835. (push m org-imenu-markers)
  22836. m))
  22837. (defun org-imenu-get-tree ()
  22838. "Produce the index for Imenu."
  22839. (dolist (x org-imenu-markers) (move-marker x nil))
  22840. (setq org-imenu-markers nil)
  22841. (let* ((case-fold-search nil)
  22842. (n org-imenu-depth)
  22843. (re (concat "^" (org-get-limited-outline-regexp)))
  22844. (subs (make-vector (1+ n) nil))
  22845. (last-level 0)
  22846. m level head0 head)
  22847. (org-with-wide-buffer
  22848. (goto-char (point-max))
  22849. (while (re-search-backward re nil t)
  22850. (setq level (org-reduced-level (funcall outline-level)))
  22851. (when (and (<= level n)
  22852. (looking-at org-complex-heading-regexp)
  22853. (setq head0 (match-string-no-properties 4)))
  22854. (setq head (org-link-display-format head0)
  22855. m (org-imenu-new-marker))
  22856. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22857. (if (>= level last-level)
  22858. (push (cons head m) (aref subs level))
  22859. (push (cons head (aref subs (1+ level))) (aref subs level))
  22860. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22861. (setq last-level level))))
  22862. (aref subs 1)))
  22863. (eval-after-load "imenu"
  22864. '(progn
  22865. (add-hook 'imenu-after-jump-hook
  22866. (lambda ()
  22867. (when (derived-mode-p 'org-mode)
  22868. (org-show-context 'org-goto))))))
  22869. (defun org-link-display-format (s)
  22870. "Replace links in string S with their description.
  22871. If there is no description, use the link target."
  22872. (save-match-data
  22873. (replace-regexp-in-string
  22874. org-bracket-link-analytic-regexp
  22875. (lambda (m)
  22876. (if (match-end 5) (match-string 5 m)
  22877. (concat (match-string 1 m) (match-string 3 m))))
  22878. s nil t)))
  22879. (defun org-toggle-link-display ()
  22880. "Toggle the literal or descriptive display of links."
  22881. (interactive)
  22882. (if org-descriptive-links
  22883. (progn (org-remove-from-invisibility-spec '(org-link))
  22884. (org-restart-font-lock)
  22885. (setq org-descriptive-links nil))
  22886. (progn (add-to-invisibility-spec '(org-link))
  22887. (org-restart-font-lock)
  22888. (setq org-descriptive-links t))))
  22889. ;; Speedbar support
  22890. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22891. "Overlay marking the agenda restriction line in speedbar.")
  22892. (overlay-put org-speedbar-restriction-lock-overlay
  22893. 'face 'org-agenda-restriction-lock)
  22894. (overlay-put org-speedbar-restriction-lock-overlay
  22895. 'help-echo "Agendas are currently limited to this item.")
  22896. (delete-overlay org-speedbar-restriction-lock-overlay)
  22897. (defun org-speedbar-set-agenda-restriction ()
  22898. "Restrict future agenda commands to the location at point in speedbar.
  22899. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22900. (interactive)
  22901. (require 'org-agenda)
  22902. (let (p m tp np dir txt)
  22903. (cond
  22904. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22905. 'org-imenu t))
  22906. (setq m (get-text-property p 'org-imenu-marker))
  22907. (with-current-buffer (marker-buffer m)
  22908. (goto-char m)
  22909. (org-agenda-set-restriction-lock 'subtree)))
  22910. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22911. 'speedbar-function 'speedbar-find-file))
  22912. (setq tp (previous-single-property-change
  22913. (1+ p) 'speedbar-function)
  22914. np (next-single-property-change
  22915. tp 'speedbar-function)
  22916. dir (speedbar-line-directory)
  22917. txt (buffer-substring-no-properties (or tp (point-min))
  22918. (or np (point-max))))
  22919. (with-current-buffer (find-file-noselect
  22920. (let ((default-directory dir))
  22921. (expand-file-name txt)))
  22922. (unless (derived-mode-p 'org-mode)
  22923. (user-error "Cannot restrict to non-Org mode file"))
  22924. (org-agenda-set-restriction-lock 'file)))
  22925. (t (user-error "Don't know how to restrict Org mode agenda")))
  22926. (move-overlay org-speedbar-restriction-lock-overlay
  22927. (point-at-bol) (point-at-eol))
  22928. (setq current-prefix-arg nil)
  22929. (org-agenda-maybe-redo)))
  22930. (defvar speedbar-file-key-map)
  22931. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22932. (eval-after-load "speedbar"
  22933. '(progn
  22934. (speedbar-add-supported-extension ".org")
  22935. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22936. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22937. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22938. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22939. (add-hook 'speedbar-visiting-tag-hook
  22940. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22941. ;;; Fixes and Hacks for problems with other packages
  22942. (defun org--flyspell-object-check-p (element)
  22943. "Non-nil when Flyspell can check object at point.
  22944. ELEMENT is the element at point."
  22945. (let ((object (save-excursion
  22946. (when (looking-at-p "\\>") (backward-char))
  22947. (org-element-context element))))
  22948. (cl-case (org-element-type object)
  22949. ;; Prevent checks in links due to keybinding conflict with
  22950. ;; Flyspell.
  22951. ((code entity export-snippet inline-babel-call
  22952. inline-src-block line-break latex-fragment link macro
  22953. statistics-cookie target timestamp verbatim)
  22954. nil)
  22955. (footnote-reference
  22956. ;; Only in inline footnotes, within the definition.
  22957. (and (eq (org-element-property :type object) 'inline)
  22958. (< (save-excursion
  22959. (goto-char (org-element-property :begin object))
  22960. (search-forward ":" nil t 2))
  22961. (point))))
  22962. (otherwise t))))
  22963. (defun org-mode-flyspell-verify ()
  22964. "Function used for `flyspell-generic-check-word-predicate'."
  22965. (if (org-at-heading-p)
  22966. ;; At a headline or an inlinetask, check title only. This is
  22967. ;; faster than relying on `org-element-at-point'.
  22968. (and (save-excursion (beginning-of-line)
  22969. (and (let ((case-fold-search t))
  22970. (not (looking-at-p "\\*+ END[ \t]*$")))
  22971. (let ((case-fold-search nil))
  22972. (looking-at org-complex-heading-regexp))))
  22973. (match-beginning 4)
  22974. (>= (point) (match-beginning 4))
  22975. (or (not (match-beginning 5))
  22976. (< (point) (match-beginning 5))))
  22977. (let* ((element (org-element-at-point))
  22978. (post-affiliated (org-element-property :post-affiliated element)))
  22979. (cond
  22980. ;; Ignore checks in all affiliated keywords but captions.
  22981. ((< (point) post-affiliated)
  22982. (and (save-excursion
  22983. (beginning-of-line)
  22984. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22985. (> (point) (match-end 0))
  22986. (org--flyspell-object-check-p element)))
  22987. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22988. ((let ((log (org-log-into-drawer)))
  22989. (and log
  22990. (let ((drawer (org-element-lineage element '(drawer))))
  22991. (and drawer
  22992. (eq (compare-strings
  22993. log nil nil
  22994. (org-element-property :drawer-name drawer) nil nil t)
  22995. t)))))
  22996. nil)
  22997. (t
  22998. (cl-case (org-element-type element)
  22999. ((comment quote-section) t)
  23000. (comment-block
  23001. ;; Allow checks between block markers, not on them.
  23002. (and (> (line-beginning-position) post-affiliated)
  23003. (save-excursion
  23004. (end-of-line)
  23005. (skip-chars-forward " \r\t\n")
  23006. (< (point) (org-element-property :end element)))))
  23007. ;; Arbitrary list of keywords where checks are meaningful.
  23008. ;; Make sure point is on the value part of the element.
  23009. (keyword
  23010. (and (member (org-element-property :key element)
  23011. '("DESCRIPTION" "TITLE"))
  23012. (save-excursion
  23013. (search-backward ":" (line-beginning-position) t))))
  23014. ;; Check is globally allowed in paragraphs verse blocks and
  23015. ;; table rows (after affiliated keywords) but some objects
  23016. ;; must not be affected.
  23017. ((paragraph table-row verse-block)
  23018. (let ((cbeg (org-element-property :contents-begin element))
  23019. (cend (org-element-property :contents-end element)))
  23020. (and cbeg (>= (point) cbeg) (< (point) cend)
  23021. (org--flyspell-object-check-p element))))))))))
  23022. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  23023. (defun org-remove-flyspell-overlays-in (beg end)
  23024. "Remove flyspell overlays in region."
  23025. (and (bound-and-true-p flyspell-mode)
  23026. (fboundp 'flyspell-delete-region-overlays)
  23027. (flyspell-delete-region-overlays beg end)))
  23028. (defvar flyspell-delayed-commands)
  23029. (eval-after-load "flyspell"
  23030. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23031. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23032. (eval-after-load "bookmark"
  23033. '(if (boundp 'bookmark-after-jump-hook)
  23034. ;; We can use the hook
  23035. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23036. ;; Hook not available, use advice
  23037. (defadvice bookmark-jump (after org-make-visible activate)
  23038. "Make the position visible."
  23039. (org-bookmark-jump-unhide))))
  23040. ;; Make sure saveplace shows the location if it was hidden
  23041. (eval-after-load "saveplace"
  23042. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23043. "Make the position visible."
  23044. (org-bookmark-jump-unhide)))
  23045. ;; Make sure ecb shows the location if it was hidden
  23046. (eval-after-load "ecb"
  23047. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23048. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23049. (when (derived-mode-p 'org-mode)
  23050. (org-show-context))))
  23051. (defun org-bookmark-jump-unhide ()
  23052. "Unhide the current position, to show the bookmark location."
  23053. (and (derived-mode-p 'org-mode)
  23054. (or (outline-invisible-p)
  23055. (save-excursion (goto-char (max (point-min) (1- (point))))
  23056. (outline-invisible-p)))
  23057. (org-show-context 'bookmark-jump)))
  23058. (defun org-mark-jump-unhide ()
  23059. "Make the point visible with `org-show-context' after jumping to the mark."
  23060. (when (and (derived-mode-p 'org-mode)
  23061. (outline-invisible-p))
  23062. (org-show-context 'mark-goto)))
  23063. (eval-after-load "simple"
  23064. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23065. "Make the point visible with `org-show-context'."
  23066. (org-mark-jump-unhide)))
  23067. (eval-after-load "simple"
  23068. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23069. "Make the point visible with `org-show-context'."
  23070. (org-mark-jump-unhide)))
  23071. (eval-after-load "simple"
  23072. '(defadvice pop-global-mark (after org-make-visible activate)
  23073. "Make the point visible with `org-show-context'."
  23074. (org-mark-jump-unhide)))
  23075. ;; Make session.el ignore our circular variable
  23076. (defvar session-globals-exclude)
  23077. (eval-after-load "session"
  23078. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23079. ;;;; Finish up
  23080. (provide 'org)
  23081. (run-hooks 'org-load-hook)
  23082. ;;; org.el ends here