org.el 949 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda"
  105. (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  108. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  109. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  110. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  111. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  112. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  113. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  114. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  115. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  116. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  117. (declare-function org-clock-update-time-maybe "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  128. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  129. (declare-function org-element-property "org-element" (property element))
  130. (declare-function org-element-put-property "org-element" (element property value))
  131. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  132. (declare-function org-element-type "org-element" (element))
  133. (declare-function org-element-update-syntax "org-element" ())
  134. (declare-function org-id-find-id-file "org-id" (id))
  135. (declare-function org-id-get-create "org-id" (&optional force))
  136. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  137. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  138. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  139. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  140. (declare-function org-table-align "org-table" ())
  141. (declare-function org-table-begin "org-table" (&optional table-type))
  142. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  143. (declare-function org-table-blank-field "org-table" ())
  144. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  145. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  146. (declare-function org-table-cut-region "org-table" (beg end))
  147. (declare-function org-table-edit-field "org-table" (arg))
  148. (declare-function org-table-end "org-table" (&optional table-type))
  149. (declare-function org-table-end-of-field "org-table" (&optional n))
  150. (declare-function org-table-insert-row "org-table" (&optional arg))
  151. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  152. (declare-function org-table-maybe-eval-formula "org-table" ())
  153. (declare-function org-table-maybe-recalculate-line "org-table" ())
  154. (declare-function org-table-next-row "org-table" ())
  155. (declare-function org-table-paste-rectangle "org-table" ())
  156. (declare-function org-table-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. (defsubst org-uniquify (list)
  161. "Non-destructively remove duplicate elements from LIST."
  162. (let ((res (copy-sequence list))) (delete-dups res)))
  163. (defsubst org-get-at-bol (property)
  164. "Get text property PROPERTY at the beginning of line."
  165. (get-text-property (point-at-bol) property))
  166. (defsubst org-trim (s &optional keep-lead)
  167. "Remove whitespace at the beginning and the end of string S.
  168. When optional argument KEEP-LEAD is non-nil, removing blank lines
  169. at the beginning of the string does not affect leading indentation."
  170. (replace-regexp-in-string
  171. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  172. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  173. ;; load languages based on value of `org-babel-load-languages'
  174. (defvar org-babel-load-languages)
  175. ;;;###autoload
  176. (defun org-babel-do-load-languages (sym value)
  177. "Load the languages defined in `org-babel-load-languages'."
  178. (set-default sym value)
  179. (dolist (pair org-babel-load-languages)
  180. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  181. (if active
  182. (require (intern (concat "ob-" lang)))
  183. (funcall 'fmakunbound
  184. (intern (concat "org-babel-execute:" lang)))
  185. (funcall 'fmakunbound
  186. (intern (concat "org-babel-expand-body:" lang)))))))
  187. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  188. ;;;###autoload
  189. (defun org-babel-load-file (file &optional compile)
  190. "Load Emacs Lisp source code blocks in the Org FILE.
  191. This function exports the source code using `org-babel-tangle'
  192. and then loads the resulting file using `load-file'. With prefix
  193. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  194. file to byte-code before it is loaded."
  195. (interactive "fFile to load: \nP")
  196. (let* ((age (lambda (file)
  197. (float-time
  198. (time-subtract (current-time)
  199. (nth 5 (or (file-attributes (file-truename file))
  200. (file-attributes file)))))))
  201. (base-name (file-name-sans-extension file))
  202. (exported-file (concat base-name ".el")))
  203. ;; tangle if the Org file is newer than the elisp file
  204. (unless (and (file-exists-p exported-file)
  205. (> (funcall age file) (funcall age exported-file)))
  206. ;; Tangle-file traversal returns reversed list of tangled files
  207. ;; and we want to evaluate the first target.
  208. (setq exported-file
  209. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  210. (message "%s %s"
  211. (if compile
  212. (progn (byte-compile-file exported-file 'load)
  213. "Compiled and loaded")
  214. (progn (load-file exported-file) "Loaded"))
  215. exported-file)))
  216. (defcustom org-babel-load-languages '((emacs-lisp . t))
  217. "Languages which can be evaluated in Org buffers.
  218. This list can be used to load support for any of the languages
  219. below, note that each language will depend on a different set of
  220. system executables and/or Emacs modes. When a language is
  221. \"loaded\", then code blocks in that language can be evaluated
  222. with `org-babel-execute-src-block' bound by default to C-c
  223. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  224. be set to remove code block evaluation from the C-c C-c
  225. keybinding. By default only Emacs Lisp (which has no
  226. requirements) is loaded."
  227. :group 'org-babel
  228. :set 'org-babel-do-load-languages
  229. :version "24.1"
  230. :type '(alist :tag "Babel Languages"
  231. :key-type
  232. (choice
  233. (const :tag "Awk" awk)
  234. (const :tag "C" C)
  235. (const :tag "R" R)
  236. (const :tag "Asymptote" asymptote)
  237. (const :tag "Calc" calc)
  238. (const :tag "Clojure" clojure)
  239. (const :tag "CSS" css)
  240. (const :tag "Ditaa" ditaa)
  241. (const :tag "Dot" dot)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "IO" io)
  248. (const :tag "J" J)
  249. (const :tag "Java" java)
  250. (const :tag "Javascript" js)
  251. (const :tag "LaTeX" latex)
  252. (const :tag "Ledger" ledger)
  253. (const :tag "Lilypond" lilypond)
  254. (const :tag "Lisp" lisp)
  255. (const :tag "Makefile" makefile)
  256. (const :tag "Maxima" maxima)
  257. (const :tag "Matlab" matlab)
  258. (const :tag "Mscgen" mscgen)
  259. (const :tag "Ocaml" ocaml)
  260. (const :tag "Octave" octave)
  261. (const :tag "Org" org)
  262. (const :tag "Perl" perl)
  263. (const :tag "Pico Lisp" picolisp)
  264. (const :tag "PlantUML" plantuml)
  265. (const :tag "Python" python)
  266. (const :tag "Ruby" ruby)
  267. (const :tag "Sass" sass)
  268. (const :tag "Scala" scala)
  269. (const :tag "Scheme" scheme)
  270. (const :tag "Screen" screen)
  271. (const :tag "Shell Script" shell)
  272. (const :tag "Shen" shen)
  273. (const :tag "Sql" sql)
  274. (const :tag "Sqlite" sqlite)
  275. (const :tag "Stan" stan)
  276. (const :tag "ebnf2ps" ebnf2ps))
  277. :value-type (boolean :tag "Activate" :value t)))
  278. ;;;; Customization variables
  279. (defcustom org-clone-delete-id nil
  280. "Remove ID property of clones of a subtree.
  281. When non-nil, clones of a subtree don't inherit the ID property.
  282. Otherwise they inherit the ID property with a new unique
  283. identifier."
  284. :type 'boolean
  285. :version "24.1"
  286. :group 'org-id)
  287. ;;; Version
  288. (org-check-version)
  289. ;;;###autoload
  290. (defun org-version (&optional here full message)
  291. "Show the Org version.
  292. Interactively, or when MESSAGE is non-nil, show it in echo area.
  293. With prefix argument, or when HERE is non-nil, insert it at point.
  294. In non-interactive uses, a reduced version string is output unless
  295. FULL is given."
  296. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  297. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  298. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  299. (load-suffixes (list ".el"))
  300. (org-install-dir
  301. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  302. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  303. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  304. (let* ((load-suffixes save-load-suffixes)
  305. (release (org-release))
  306. (git-version (org-git-version))
  307. (version (format "Org-mode version %s (%s @ %s)"
  308. release
  309. git-version
  310. (if org-install-dir
  311. (if (string= org-dir org-install-dir)
  312. org-install-dir
  313. (concat "mixed installation! "
  314. org-install-dir
  315. " and "
  316. org-dir))
  317. "org-loaddefs.el can not be found!")))
  318. (version1 (if full version release)))
  319. (when here (insert version1))
  320. (when message (message "%s" version1))
  321. version1)))
  322. (defconst org-version (org-version))
  323. ;;; Syntax Constants
  324. ;;;; Block
  325. (defconst org-block-regexp
  326. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  327. "Regular expression for hiding blocks.")
  328. (defconst org-dblock-start-re
  329. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  330. "Matches the start line of a dynamic block, with parameters.")
  331. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  332. "Matches the end of a dynamic block.")
  333. ;;;; Clock and Planning
  334. (defconst org-clock-string "CLOCK:"
  335. "String used as prefix for timestamps clocking work hours on an item.")
  336. (defvar org-closed-string "CLOSED:"
  337. "String used as the prefix for timestamps logging closing a TODO entry.")
  338. (defvar org-deadline-string "DEADLINE:"
  339. "String to mark deadline entries.
  340. A deadline is this string, followed by a time stamp. Should be a word,
  341. terminated by a colon. You can insert a schedule keyword and
  342. a timestamp with \\[org-deadline].")
  343. (defvar org-scheduled-string "SCHEDULED:"
  344. "String to mark scheduled TODO entries.
  345. A schedule is this string, followed by a time stamp. Should be a word,
  346. terminated by a colon. You can insert a schedule keyword and
  347. a timestamp with \\[org-schedule].")
  348. (defconst org-ds-keyword-length
  349. (+ 2
  350. (apply #'max
  351. (mapcar #'length
  352. (list org-deadline-string org-scheduled-string
  353. org-clock-string org-closed-string))))
  354. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  355. (defconst org-planning-line-re
  356. (concat "^[ \t]*"
  357. (regexp-opt
  358. (list org-closed-string org-deadline-string org-scheduled-string)
  359. t))
  360. "Matches a line with planning info.
  361. Matched keyword is in group 1.")
  362. (defconst org-clock-line-re
  363. (concat "^[ \t]*" org-clock-string)
  364. "Matches a line with clock info.")
  365. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  366. "Matches the DEADLINE keyword.")
  367. (defconst org-deadline-time-regexp
  368. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  369. "Matches the DEADLINE keyword together with a time stamp.")
  370. (defconst org-deadline-time-hour-regexp
  371. (concat "\\<" org-deadline-string
  372. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  373. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  374. (defconst org-deadline-line-regexp
  375. (concat "\\<\\(" org-deadline-string "\\).*")
  376. "Matches the DEADLINE keyword and the rest of the line.")
  377. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  378. "Matches the SCHEDULED keyword.")
  379. (defconst org-scheduled-time-regexp
  380. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  381. "Matches the SCHEDULED keyword together with a time stamp.")
  382. (defconst org-scheduled-time-hour-regexp
  383. (concat "\\<" org-scheduled-string
  384. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  385. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  386. (defconst org-closed-time-regexp
  387. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  388. "Matches the CLOSED keyword together with a time stamp.")
  389. (defconst org-keyword-time-regexp
  390. (concat "\\<"
  391. (regexp-opt
  392. (list org-scheduled-string org-deadline-string org-closed-string
  393. org-clock-string)
  394. t)
  395. " *[[<]\\([^]>]+\\)[]>]")
  396. "Matches any of the 4 keywords, together with the time stamp.")
  397. (defconst org-keyword-time-not-clock-regexp
  398. (concat
  399. "\\<"
  400. (regexp-opt
  401. (list org-scheduled-string org-deadline-string org-closed-string) t)
  402. " *[[<]\\([^]>]+\\)[]>]")
  403. "Matches any of the 3 keywords, together with the time stamp.")
  404. (defconst org-maybe-keyword-time-regexp
  405. (concat "\\(\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string
  408. org-clock-string)
  409. t)
  410. "\\)?"
  411. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  412. "\\|"
  413. "<%%([^\r\n>]*>\\)")
  414. "Matches a timestamp, possibly preceded by a keyword.")
  415. (defconst org-all-time-keywords
  416. (mapcar (lambda (w) (substring w 0 -1))
  417. (list org-scheduled-string org-deadline-string
  418. org-clock-string org-closed-string))
  419. "List of time keywords.")
  420. ;;;; Drawer
  421. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  422. "Matches first or last line of a hidden block.
  423. Group 1 contains drawer's name or \"END\".")
  424. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  425. "Regular expression matching the first line of a property drawer.")
  426. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  427. "Regular expression matching the last line of a property drawer.")
  428. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  429. "Regular expression matching the first line of a clock drawer.")
  430. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  431. "Regular expression matching the last line of a clock drawer.")
  432. (defconst org-property-drawer-re
  433. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  434. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  435. "[ \t]*:END:[ \t]*$")
  436. "Matches an entire property drawer.")
  437. (defconst org-clock-drawer-re
  438. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  439. org-clock-drawer-end-re "\\)\n?")
  440. "Matches an entire clock drawer.")
  441. ;;;; Headline
  442. (defconst org-heading-keyword-regexp-format
  443. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  444. "Printf format for a regexp matching a headline with some keyword.
  445. This regexp will match the headline of any node which has the
  446. exact keyword that is put into the format. The keyword isn't in
  447. any group by default, but the stars and the body are.")
  448. (defconst org-heading-keyword-maybe-regexp-format
  449. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  450. "Printf format for a regexp matching a headline, possibly with some keyword.
  451. This regexp can match any headline with the specified keyword, or
  452. without a keyword. The keyword isn't in any group by default,
  453. but the stars and the body are.")
  454. (defconst org-archive-tag "ARCHIVE"
  455. "The tag that marks a subtree as archived.
  456. An archived subtree does not open during visibility cycling, and does
  457. not contribute to the agenda listings.")
  458. (defconst org-comment-string "COMMENT"
  459. "Entries starting with this keyword will never be exported.
  460. An entry can be toggled between COMMENT and normal with
  461. \\[org-toggle-comment].")
  462. ;;;; LaTeX Environments and Fragments
  463. (defconst org-latex-regexps
  464. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  465. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  466. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  467. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  468. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  469. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  470. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  471. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  472. "Regular expressions for matching embedded LaTeX.")
  473. ;;;; Node Property
  474. (defconst org-effort-property "Effort"
  475. "The property that is being used to keep track of effort estimates.
  476. Effort estimates given in this property need to have the format H:MM.")
  477. ;;;; Table
  478. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  479. "Detect an org-type or table-type table.")
  480. (defconst org-table-line-regexp "^[ \t]*|"
  481. "Detect an org-type table line.")
  482. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  483. "Detect an org-type table line.")
  484. (defconst org-table-hline-regexp "^[ \t]*|-"
  485. "Detect an org-type table hline.")
  486. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  487. "Detect a table-type table hline.")
  488. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  489. "Detect the first line outside a table when searching from within it.
  490. This works for both table types.")
  491. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  492. "Detect a #+TBLFM line.")
  493. ;;;; Timestamp
  494. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  495. "Regular expression for fast time stamp matching.")
  496. (defconst org-ts-regexp-inactive
  497. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  498. "Regular expression for fast inactive time stamp matching.")
  499. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  500. "Regular expression for fast time stamp matching.")
  501. (defconst org-ts-regexp0
  502. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  503. "Regular expression matching time strings for analysis.
  504. This one does not require the space after the date, so it can be used
  505. on a string that terminates immediately after the date.")
  506. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.")
  508. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  509. "Regular expression matching time stamps, with groups.")
  510. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  511. "Regular expression matching time stamps (also [..]), with groups.")
  512. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  513. "Regular expression matching a time stamp range.")
  514. (defconst org-tr-regexp-both
  515. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  518. org-ts-regexp "\\)?")
  519. "Regular expression matching a time stamp or time stamp range.")
  520. (defconst org-tsr-regexp-both
  521. (concat org-ts-regexp-both "\\(--?-?"
  522. org-ts-regexp-both "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.
  524. The time stamps may be either active or inactive.")
  525. (defconst org-repeat-re
  526. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  527. "Regular expression for specifying repeated events.
  528. After a match, group 1 contains the repeat expression.")
  529. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  530. "Formats for `format-time-string' which are used for time stamps.")
  531. ;;; The custom variables
  532. (defgroup org nil
  533. "Outline-based notes management and organizer."
  534. :tag "Org"
  535. :group 'outlines
  536. :group 'calendar)
  537. (defcustom org-mode-hook nil
  538. "Mode hook for Org-mode, run after the mode was turned on."
  539. :group 'org
  540. :type 'hook)
  541. (defcustom org-load-hook nil
  542. "Hook that is run after org.el has been loaded."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-log-buffer-setup-hook nil
  546. "Hook that is run after an Org log buffer is created."
  547. :group 'org
  548. :version "24.1"
  549. :type 'hook)
  550. (defvar org-modules) ; defined below
  551. (defvar org-modules-loaded nil
  552. "Have the modules been loaded already?")
  553. (defun org-load-modules-maybe (&optional force)
  554. "Load all extensions listed in `org-modules'."
  555. (when (or force (not org-modules-loaded))
  556. (dolist (ext org-modules)
  557. (condition-case nil (require ext)
  558. (error (message "Problems while trying to load feature `%s'" ext))))
  559. (setq org-modules-loaded t)))
  560. (defun org-set-modules (var value)
  561. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  562. (set var value)
  563. (when (featurep 'org)
  564. (org-load-modules-maybe 'force)
  565. (org-element-cache-reset 'all)))
  566. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  567. "Modules that should always be loaded together with org.el.
  568. If a description starts with <C>, the file is not part of Emacs
  569. and loading it will require that you have downloaded and properly
  570. installed the Org mode distribution.
  571. You can also use this system to load external packages (i.e. neither Org
  572. core modules, nor modules from the CONTRIB directory). Just add symbols
  573. to the end of the list. If the package is called org-xyz.el, then you need
  574. to add the symbol `xyz', and the package must have a call to:
  575. (provide \\='org-xyz)
  576. For export specific modules, see also `org-export-backends'."
  577. :group 'org
  578. :set 'org-set-modules
  579. :version "24.4"
  580. :package-version '(Org . "8.0")
  581. :type
  582. '(set :greedy t
  583. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  584. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  585. (const :tag " crypt: Encryption of subtrees" org-crypt)
  586. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  587. (const :tag " docview: Links to doc-view buffers" org-docview)
  588. (const :tag " eww: Store link to url of eww" org-eww)
  589. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  590. (const :tag " habit: Track your consistency with habits" org-habit)
  591. (const :tag " id: Global IDs for identifying entries" org-id)
  592. (const :tag " info: Links to Info nodes" org-info)
  593. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  594. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  595. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  596. (const :tag " mouse: Additional mouse support" org-mouse)
  597. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  598. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  599. (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
  600. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  601. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  602. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  603. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  604. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  605. (const :tag "C collector: Collect properties into tables" org-collector)
  606. (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  607. (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
  608. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  609. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  610. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  611. (const :tag "C eval: Include command output as text" org-eval)
  612. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  613. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  614. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  615. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  616. (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
  617. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  618. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  619. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  620. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  621. (const :tag "C man: Support for links to manpages in Org-mode" org-man)
  622. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  623. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  624. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  625. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  626. (const :tag "C registry: A registry for Org links" org-registry)
  627. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  628. (const :tag "C secretary: Team management with org-mode" org-secretary)
  629. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  630. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  631. (const :tag "C track: Keep up with Org mode development" org-track)
  632. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  633. (const :tag "C vm: Links to VM folders/messages" org-vm)
  634. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  635. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  636. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  637. (defvar org-export-registered-backends) ; From ox.el.
  638. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  639. (declare-function org-export-backend-name "ox" (backend) t)
  640. (defcustom org-export-backends '(ascii html icalendar latex odt)
  641. "List of export back-ends that should be always available.
  642. If a description starts with <C>, the file is not part of Emacs
  643. and loading it will require that you have downloaded and properly
  644. installed the Org mode distribution.
  645. Unlike to `org-modules', libraries in this list will not be
  646. loaded along with Org, but only once the export framework is
  647. needed.
  648. This variable needs to be set before org.el is loaded. If you
  649. need to make a change while Emacs is running, use the customize
  650. interface or run the following code, where VAL stands for the new
  651. value of the variable, after updating it:
  652. (progn
  653. (setq org-export-registered-backends
  654. (cl-remove-if-not
  655. (lambda (backend)
  656. (let ((name (org-export-backend-name backend)))
  657. (or (memq name val)
  658. (catch \\='parentp
  659. (dolist (b val)
  660. (and (org-export-derived-backend-p b name)
  661. (throw \\='parentp t)))))))
  662. org-export-registered-backends))
  663. (let ((new-list (mapcar #\\='org-export-backend-name
  664. org-export-registered-backends)))
  665. (dolist (backend val)
  666. (cond
  667. ((not (load (format \"ox-%s\" backend) t t))
  668. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  669. backend))
  670. ((not (memq backend new-list)) (push backend new-list))))
  671. (set-default \\='org-export-backends new-list)))
  672. Adding a back-end to this list will also pull the back-end it
  673. depends on, if any."
  674. :group 'org
  675. :group 'org-export
  676. :version "25.1"
  677. :package-version '(Org . "9.0")
  678. :initialize 'custom-initialize-set
  679. :set (lambda (var val)
  680. (if (not (featurep 'ox)) (set-default var val)
  681. ;; Any back-end not required anymore (not present in VAL and not
  682. ;; a parent of any back-end in the new value) is removed from the
  683. ;; list of registered back-ends.
  684. (setq org-export-registered-backends
  685. (cl-remove-if-not
  686. (lambda (backend)
  687. (let ((name (org-export-backend-name backend)))
  688. (or (memq name val)
  689. (catch 'parentp
  690. (dolist (b val)
  691. (and (org-export-derived-backend-p b name)
  692. (throw 'parentp t)))))))
  693. org-export-registered-backends))
  694. ;; Now build NEW-LIST of both new back-ends and required
  695. ;; parents.
  696. (let ((new-list (mapcar #'org-export-backend-name
  697. org-export-registered-backends)))
  698. (dolist (backend val)
  699. (cond
  700. ((not (load (format "ox-%s" backend) t t))
  701. (message "Problems while trying to load export back-end `%s'"
  702. backend))
  703. ((not (memq backend new-list)) (push backend new-list))))
  704. ;; Set VAR to that list with fixed dependencies.
  705. (set-default var new-list))))
  706. :type '(set :greedy t
  707. (const :tag " ascii Export buffer to ASCII format" ascii)
  708. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  709. (const :tag " html Export buffer to HTML format" html)
  710. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  711. (const :tag " latex Export buffer to LaTeX format" latex)
  712. (const :tag " man Export buffer to MAN format" man)
  713. (const :tag " md Export buffer to Markdown format" md)
  714. (const :tag " odt Export buffer to ODT format" odt)
  715. (const :tag " org Export buffer to Org format" org)
  716. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  717. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  718. (const :tag "C deck Export buffer to deck.js presentations" deck)
  719. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  720. (const :tag "C groff Export buffer to Groff format" groff)
  721. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  722. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  723. (const :tag "C s5 Export buffer to s5 presentations" s5)
  724. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  725. (eval-after-load 'ox
  726. '(dolist (backend org-export-backends)
  727. (condition-case nil (require (intern (format "ox-%s" backend)))
  728. (error (message "Problems while trying to load export back-end `%s'"
  729. backend)))))
  730. (defcustom org-support-shift-select nil
  731. "Non-nil means make shift-cursor commands select text when possible.
  732. \\<org-mode-map>\
  733. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  734. start selecting a region, or enlarge regions started in this way.
  735. In Org-mode, in special contexts, these same keys are used for
  736. other purposes, important enough to compete with shift selection.
  737. Org tries to balance these needs by supporting `shift-select-mode'
  738. outside these special contexts, under control of this variable.
  739. The default of this variable is nil, to avoid confusing behavior. Shifted
  740. cursor keys will then execute Org commands in the following contexts:
  741. - on a headline, changing TODO state (left/right) and priority (up/down)
  742. - on a time stamp, changing the time
  743. - in a plain list item, changing the bullet type
  744. - in a property definition line, switching between allowed values
  745. - in the BEGIN line of a clock table (changing the time block).
  746. Outside these contexts, the commands will throw an error.
  747. When this variable is t and the cursor is not in a special
  748. context, Org mode will support shift-selection for making and
  749. enlarging regions. To make this more effective, the bullet
  750. cycling will no longer happen anywhere in an item line, but only
  751. if the cursor is exactly on the bullet.
  752. If you set this variable to the symbol `always', then the keys
  753. will not be special in headlines, property lines, and item lines,
  754. to make shift selection work there as well. If this is what you
  755. want, you can use the following alternative commands:
  756. `\\[org-todo]' and `\\[org-priority]' \
  757. to change TODO state and priority,
  758. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  759. can be used to switch TODO sets,
  760. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  761. and properties can be edited by hand or in column view.
  762. However, when the cursor is on a timestamp, shift-cursor commands
  763. will still edit the time stamp - this is just too good to give up."
  764. :group 'org
  765. :type '(choice
  766. (const :tag "Never" nil)
  767. (const :tag "When outside special context" t)
  768. (const :tag "Everywhere except timestamps" always)))
  769. (defcustom org-loop-over-headlines-in-active-region nil
  770. "Shall some commands act upon headlines in the active region?
  771. When set to t, some commands will be performed in all headlines
  772. within the active region.
  773. When set to `start-level', some commands will be performed in all
  774. headlines within the active region, provided that these headlines
  775. are of the same level than the first one.
  776. When set to a string, those commands will be performed on the
  777. matching headlines within the active region. Such string must be
  778. a tags/property/todo match as it is used in the agenda tags view.
  779. The list of commands is: `org-schedule', `org-deadline',
  780. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  781. `org-archive-to-archive-sibling'. The archiving commands skip
  782. already archived entries."
  783. :type '(choice (const :tag "Don't loop" nil)
  784. (const :tag "All headlines in active region" t)
  785. (const :tag "In active region, headlines at the same level than the first one" start-level)
  786. (string :tag "Tags/Property/Todo matcher"))
  787. :version "24.1"
  788. :group 'org-todo
  789. :group 'org-archive)
  790. (defgroup org-startup nil
  791. "Options concerning startup of Org-mode."
  792. :tag "Org Startup"
  793. :group 'org)
  794. (defcustom org-startup-folded t
  795. "Non-nil means entering Org mode will switch to OVERVIEW.
  796. This can also be configured on a per-file basis by adding one of
  797. the following lines anywhere in the buffer:
  798. #+STARTUP: fold (or `overview', this is equivalent)
  799. #+STARTUP: nofold (or `showall', this is equivalent)
  800. #+STARTUP: content
  801. #+STARTUP: showeverything
  802. By default, this option is ignored when Org opens agenda files
  803. for the first time. If you want the agenda to honor the startup
  804. option, set `org-agenda-inhibit-startup' to nil."
  805. :group 'org-startup
  806. :type '(choice
  807. (const :tag "nofold: show all" nil)
  808. (const :tag "fold: overview" t)
  809. (const :tag "content: all headlines" content)
  810. (const :tag "show everything, even drawers" showeverything)))
  811. (defcustom org-startup-truncated t
  812. "Non-nil means entering Org mode will set `truncate-lines'.
  813. This is useful since some lines containing links can be very long and
  814. uninteresting. Also tables look terrible when wrapped.
  815. The variable `org-startup-truncated' allows to configure
  816. truncation for Org mode different to the other modes that use the
  817. variable `truncate-lines' and as a shortcut instead of putting
  818. the variable `truncate-lines' into the `org-mode-hook'. If one
  819. wants to configure truncation for Org mode not statically but
  820. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  821. the variable `truncate-lines' has to be used because in such a
  822. case it is too late to set the variable `org-startup-truncated'."
  823. :group 'org-startup
  824. :type 'boolean)
  825. (defcustom org-startup-indented nil
  826. "Non-nil means turn on `org-indent-mode' on startup.
  827. This can also be configured on a per-file basis by adding one of
  828. the following lines anywhere in the buffer:
  829. #+STARTUP: indent
  830. #+STARTUP: noindent"
  831. :group 'org-structure
  832. :type '(choice
  833. (const :tag "Not" nil)
  834. (const :tag "Globally (slow on startup in large files)" t)))
  835. (defcustom org-use-sub-superscripts t
  836. "Non-nil means interpret \"_\" and \"^\" for display.
  837. If you want to control how Org exports those characters, see
  838. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  839. used to be an alias for `org-export-with-sub-superscripts' in
  840. Org <8.0, it is not anymore.
  841. When this option is turned on, you can use TeX-like syntax for
  842. sub- and superscripts within the buffer. Several characters after
  843. \"_\" or \"^\" will be considered as a single item - so grouping
  844. with {} is normally not needed. For example, the following things
  845. will be parsed as single sub- or superscripts:
  846. 10^24 or 10^tau several digits will be considered 1 item.
  847. 10^-12 or 10^-tau a leading sign with digits or a word
  848. x^2-y^3 will be read as x^2 - y^3, because items are
  849. terminated by almost any nonword/nondigit char.
  850. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  851. Still, ambiguity is possible. So when in doubt, use {} to enclose
  852. the sub/superscript. If you set this variable to the symbol `{}',
  853. the braces are *required* in order to trigger interpretations as
  854. sub/superscript. This can be helpful in documents that need \"_\"
  855. frequently in plain text."
  856. :group 'org-startup
  857. :version "24.4"
  858. :package-version '(Org . "8.0")
  859. :type '(choice
  860. (const :tag "Always interpret" t)
  861. (const :tag "Only with braces" {})
  862. (const :tag "Never interpret" nil)))
  863. (defcustom org-startup-with-beamer-mode nil
  864. "Non-nil means turn on `org-beamer-mode' on startup.
  865. This can also be configured on a per-file basis by adding one of
  866. the following lines anywhere in the buffer:
  867. #+STARTUP: beamer"
  868. :group 'org-startup
  869. :version "24.1"
  870. :type 'boolean)
  871. (defcustom org-startup-align-all-tables nil
  872. "Non-nil means align all tables when visiting a file.
  873. This is useful when the column width in tables is forced with <N> cookies
  874. in table fields. Such tables will look correct only after the first re-align.
  875. This can also be configured on a per-file basis by adding one of
  876. the following lines anywhere in the buffer:
  877. #+STARTUP: align
  878. #+STARTUP: noalign"
  879. :group 'org-startup
  880. :type 'boolean)
  881. (defcustom org-startup-with-inline-images nil
  882. "Non-nil means show inline images when loading a new Org file.
  883. This can also be configured on a per-file basis by adding one of
  884. the following lines anywhere in the buffer:
  885. #+STARTUP: inlineimages
  886. #+STARTUP: noinlineimages"
  887. :group 'org-startup
  888. :version "24.1"
  889. :type 'boolean)
  890. (defcustom org-startup-with-latex-preview nil
  891. "Non-nil means preview LaTeX fragments when loading a new Org file.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: latexpreview
  895. #+STARTUP: nolatexpreview"
  896. :group 'org-startup
  897. :version "24.4"
  898. :package-version '(Org . "8.0")
  899. :type 'boolean)
  900. (defcustom org-insert-mode-line-in-empty-file nil
  901. "Non-nil means insert the first line setting Org mode in empty files.
  902. When the function `org-mode' is called interactively in an empty file, this
  903. normally means that the file name does not automatically trigger Org mode.
  904. To ensure that the file will always be in Org mode in the future, a
  905. line enforcing Org mode will be inserted into the buffer, if this option
  906. has been set."
  907. :group 'org-startup
  908. :type 'boolean)
  909. (defcustom org-replace-disputed-keys nil
  910. "Non-nil means use alternative key bindings for some keys.
  911. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  912. These keys are also used by other packages like shift-selection-mode'
  913. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  914. If you want to use Org mode together with one of these other modes,
  915. or more generally if you would like to move some Org mode commands to
  916. other keys, set this variable and configure the keys with the variable
  917. `org-disputed-keys'.
  918. This option is only relevant at load-time of Org-mode, and must be set
  919. *before* org.el is loaded. Changing it requires a restart of Emacs to
  920. become effective."
  921. :group 'org-startup
  922. :type 'boolean)
  923. (defcustom org-use-extra-keys nil
  924. "Non-nil means use extra key sequence definitions for certain commands.
  925. This happens automatically if `window-system' is nil. This
  926. variable lets you do the same manually. You must set it before
  927. loading Org."
  928. :group 'org-startup
  929. :type 'boolean)
  930. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  931. (defcustom org-disputed-keys
  932. '(([(shift up)] . [(meta p)])
  933. ([(shift down)] . [(meta n)])
  934. ([(shift left)] . [(meta -)])
  935. ([(shift right)] . [(meta +)])
  936. ([(control shift right)] . [(meta shift +)])
  937. ([(control shift left)] . [(meta shift -)]))
  938. "Keys for which Org mode and other modes compete.
  939. This is an alist, cars are the default keys, second element specifies
  940. the alternative to use when `org-replace-disputed-keys' is t.
  941. Keys can be specified in any syntax supported by `define-key'.
  942. The value of this option takes effect only at Org-mode's startup,
  943. therefore you'll have to restart Emacs to apply it after changing."
  944. :group 'org-startup
  945. :type 'alist)
  946. (defun org-key (key)
  947. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  948. Or return the original if not disputed."
  949. (when org-replace-disputed-keys
  950. (let* ((nkey (key-description key))
  951. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  952. org-disputed-keys)))
  953. (setq key (if x (cdr x) key))))
  954. key)
  955. (defun org-defkey (keymap key def)
  956. "Define a key, possibly translated, as returned by `org-key'."
  957. (define-key keymap (org-key key) def))
  958. (defcustom org-ellipsis nil
  959. "The ellipsis to use in the Org mode outline.
  960. When nil, just use the standard three dots.
  961. When a string, use that string instead.
  962. When a face, use the standard 3 dots, but with the specified face.
  963. The change affects only Org mode (which will then use its own display table).
  964. Changing this requires executing \\[org-mode] in a buffer to become
  965. effective."
  966. :group 'org-startup
  967. :type '(choice (const :tag "Default" nil)
  968. (face :tag "Face" :value org-warning)
  969. (string :tag "String" :value "...#")))
  970. (defvar org-display-table nil
  971. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  972. (defgroup org-keywords nil
  973. "Keywords in Org-mode."
  974. :tag "Org Keywords"
  975. :group 'org)
  976. (defcustom org-closed-keep-when-no-todo nil
  977. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  978. :group 'org-todo
  979. :group 'org-keywords
  980. :version "24.4"
  981. :package-version '(Org . "8.0")
  982. :type 'boolean)
  983. (defgroup org-structure nil
  984. "Options concerning the general structure of Org files."
  985. :tag "Org Structure"
  986. :group 'org)
  987. (defgroup org-reveal-location nil
  988. "Options about how to make context of a location visible."
  989. :tag "Org Reveal Location"
  990. :group 'org-structure)
  991. (defcustom org-show-context-detail '((agenda . local)
  992. (bookmark-jump . lineage)
  993. (isearch . lineage)
  994. (default . ancestors))
  995. "Alist between context and visibility span when revealing a location.
  996. \\<org-mode-map>Some actions may move point into invisible
  997. locations. As a consequence, Org always expose a neighborhood
  998. around point. How much is shown depends on the initial action,
  999. or context. Valid contexts are
  1000. agenda when exposing an entry from the agenda
  1001. org-goto when using the command `org-goto' (\\[org-goto])
  1002. occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
  1003. tags-tree when constructing a sparse tree based on tags matches
  1004. link-search when exposing search matches associated with a link
  1005. mark-goto when exposing the jump goal of a mark
  1006. bookmark-jump when exposing a bookmark location
  1007. isearch when exiting from an incremental search
  1008. default default for all contexts not set explicitly
  1009. Allowed visibility spans are
  1010. minimal show current headline; if point is not on headline,
  1011. also show entry
  1012. local show current headline, entry and next headline
  1013. ancestors show current headline and its direct ancestors; if
  1014. point is not on headline, also show entry
  1015. lineage show current headline, its direct ancestors and all
  1016. their children; if point is not on headline, also show
  1017. entry and first child
  1018. tree show current headline, its direct ancestors and all
  1019. their children; if point is not on headline, also show
  1020. entry and all children
  1021. canonical show current headline, its direct ancestors along with
  1022. their entries and children; if point is not located on
  1023. the headline, also show current entry and all children
  1024. As special cases, a nil or t value means show all contexts in
  1025. `minimal' or `canonical' view, respectively.
  1026. Some views can make displayed information very compact, but also
  1027. make it harder to edit the location of the match. In such
  1028. a case, use the command `org-reveal' (\\[org-reveal]) to show
  1029. more context."
  1030. :group 'org-reveal-location
  1031. :version "25.2"
  1032. :package-version '(Org . "9.0")
  1033. :type '(choice
  1034. (const :tag "Canonical" t)
  1035. (const :tag "Minimal" nil)
  1036. (repeat :greedy t :tag "Individual contexts"
  1037. (cons
  1038. (choice :tag "Context"
  1039. (const agenda)
  1040. (const org-goto)
  1041. (const occur-tree)
  1042. (const tags-tree)
  1043. (const link-search)
  1044. (const mark-goto)
  1045. (const bookmark-jump)
  1046. (const isearch)
  1047. (const default))
  1048. (choice :tag "Detail level"
  1049. (const minimal)
  1050. (const local)
  1051. (const ancestors)
  1052. (const lineage)
  1053. (const tree)
  1054. (const canonical))))))
  1055. (defcustom org-indirect-buffer-display 'other-window
  1056. "How should indirect tree buffers be displayed?
  1057. This applies to indirect buffers created with the commands
  1058. \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
  1059. Valid values are:
  1060. current-window Display in the current window
  1061. other-window Just display in another window.
  1062. dedicated-frame Create one new frame, and re-use it each time.
  1063. new-frame Make a new frame each time. Note that in this case
  1064. previously-made indirect buffers are kept, and you need to
  1065. kill these buffers yourself."
  1066. :group 'org-structure
  1067. :group 'org-agenda-windows
  1068. :type '(choice
  1069. (const :tag "In current window" current-window)
  1070. (const :tag "In current frame, other window" other-window)
  1071. (const :tag "Each time a new frame" new-frame)
  1072. (const :tag "One dedicated frame" dedicated-frame)))
  1073. (defcustom org-use-speed-commands nil
  1074. "Non-nil means activate single letter commands at beginning of a headline.
  1075. This may also be a function to test for appropriate locations where speed
  1076. commands should be active.
  1077. For example, to activate speed commands when the point is on any
  1078. star at the beginning of the headline, you can do this:
  1079. (setq org-use-speed-commands
  1080. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1081. :group 'org-structure
  1082. :type '(choice
  1083. (const :tag "Never" nil)
  1084. (const :tag "At beginning of headline stars" t)
  1085. (function)))
  1086. (defcustom org-speed-commands-user nil
  1087. "Alist of additional speed commands.
  1088. This list will be checked before `org-speed-commands-default'
  1089. when the variable `org-use-speed-commands' is non-nil
  1090. and when the cursor is at the beginning of a headline.
  1091. The car if each entry is a string with a single letter, which must
  1092. be assigned to `self-insert-command' in the global map.
  1093. The cdr is either a command to be called interactively, a function
  1094. to be called, or a form to be evaluated.
  1095. An entry that is just a list with a single string will be interpreted
  1096. as a descriptive headline that will be added when listing the speed
  1097. commands in the Help buffer using the `?' speed command."
  1098. :group 'org-structure
  1099. :type '(repeat :value ("k" . ignore)
  1100. (choice :value ("k" . ignore)
  1101. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1102. (cons :tag "Letter and Command"
  1103. (string :tag "Command letter")
  1104. (choice
  1105. (function)
  1106. (sexp))))))
  1107. (defcustom org-bookmark-names-plist
  1108. '(:last-capture "org-capture-last-stored"
  1109. :last-refile "org-refile-last-stored"
  1110. :last-capture-marker "org-capture-last-stored-marker")
  1111. "Names for bookmarks automatically set by some Org commands.
  1112. This can provide strings as names for a number of bookmarks Org sets
  1113. automatically. The following keys are currently implemented:
  1114. :last-capture
  1115. :last-capture-marker
  1116. :last-refile
  1117. When a key does not show up in the property list, the corresponding bookmark
  1118. is not set."
  1119. :group 'org-structure
  1120. :type 'plist)
  1121. (defgroup org-cycle nil
  1122. "Options concerning visibility cycling in Org-mode."
  1123. :tag "Org Cycle"
  1124. :group 'org-structure)
  1125. (defcustom org-cycle-skip-children-state-if-no-children t
  1126. "Non-nil means skip CHILDREN state in entries that don't have any."
  1127. :group 'org-cycle
  1128. :type 'boolean)
  1129. (defcustom org-cycle-max-level nil
  1130. "Maximum level which should still be subject to visibility cycling.
  1131. Levels higher than this will, for cycling, be treated as text, not a headline.
  1132. When `org-odd-levels-only' is set, a value of N in this variable actually
  1133. means 2N-1 stars as the limiting headline.
  1134. When nil, cycle all levels.
  1135. Note that the limiting level of cycling is also influenced by
  1136. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1137. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1138. than its value."
  1139. :group 'org-cycle
  1140. :type '(choice
  1141. (const :tag "No limit" nil)
  1142. (integer :tag "Maximum level")))
  1143. (defcustom org-hide-block-startup nil
  1144. "Non-nil means entering Org mode will fold all blocks.
  1145. This can also be set in on a per-file basis with
  1146. #+STARTUP: hideblocks
  1147. #+STARTUP: showblocks"
  1148. :group 'org-startup
  1149. :group 'org-cycle
  1150. :type 'boolean)
  1151. (defcustom org-cycle-global-at-bob nil
  1152. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1153. This makes it possible to do global cycling without having to use S-TAB or
  1154. \\[universal-argument] TAB. For this special case to work, the first line
  1155. of the buffer must not be a headline -- it may be empty or some other text.
  1156. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1157. sure the cursor stays at the beginning of the buffer. When this option is
  1158. nil, don't do anything special at the beginning of the buffer."
  1159. :group 'org-cycle
  1160. :type 'boolean)
  1161. (defcustom org-cycle-level-after-item/entry-creation t
  1162. "Non-nil means cycle entry level or item indentation in new empty entries.
  1163. When the cursor is at the end of an empty headline, i.e., with only stars
  1164. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1165. and then all possible ancestor states, before returning to the original state.
  1166. This makes data entry extremely fast: M-RET to create a new headline,
  1167. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1168. When the cursor is at the end of an empty plain list item, one TAB will
  1169. make it a subitem, two or more tabs will back up to make this an item
  1170. higher up in the item hierarchy."
  1171. :group 'org-cycle
  1172. :type 'boolean)
  1173. (defcustom org-cycle-emulate-tab t
  1174. "Where should `org-cycle' emulate TAB.
  1175. nil Never
  1176. white Only in completely white lines
  1177. whitestart Only at the beginning of lines, before the first non-white char
  1178. t Everywhere except in headlines
  1179. exc-hl-bol Everywhere except at the start of a headline
  1180. If TAB is used in a place where it does not emulate TAB, the current subtree
  1181. visibility is cycled."
  1182. :group 'org-cycle
  1183. :type '(choice (const :tag "Never" nil)
  1184. (const :tag "Only in completely white lines" white)
  1185. (const :tag "Before first char in a line" whitestart)
  1186. (const :tag "Everywhere except in headlines" t)
  1187. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1188. (defcustom org-cycle-separator-lines 2
  1189. "Number of empty lines needed to keep an empty line between collapsed trees.
  1190. If you leave an empty line between the end of a subtree and the following
  1191. headline, this empty line is hidden when the subtree is folded.
  1192. Org mode will leave (exactly) one empty line visible if the number of
  1193. empty lines is equal or larger to the number given in this variable.
  1194. So the default 2 means at least 2 empty lines after the end of a subtree
  1195. are needed to produce free space between a collapsed subtree and the
  1196. following headline.
  1197. If the number is negative, and the number of empty lines is at least -N,
  1198. all empty lines are shown.
  1199. Special case: when 0, never leave empty lines in collapsed view."
  1200. :group 'org-cycle
  1201. :type 'integer)
  1202. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1203. (defcustom org-pre-cycle-hook nil
  1204. "Hook that is run before visibility cycling is happening.
  1205. The function(s) in this hook must accept a single argument which indicates
  1206. the new state that will be set right after running this hook. The
  1207. argument is a symbol. Before a global state change, it can have the values
  1208. `overview', `content', or `all'. Before a local state change, it can have
  1209. the values `folded', `children', or `subtree'."
  1210. :group 'org-cycle
  1211. :type 'hook)
  1212. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1213. org-cycle-hide-drawers
  1214. org-cycle-show-empty-lines
  1215. org-optimize-window-after-visibility-change)
  1216. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1217. The function(s) in this hook must accept a single argument which indicates
  1218. the new state that was set by the most recent `org-cycle' command. The
  1219. argument is a symbol. After a global state change, it can have the values
  1220. `overview', `contents', or `all'. After a local state change, it can have
  1221. the values `folded', `children', or `subtree'."
  1222. :group 'org-cycle
  1223. :type 'hook
  1224. :version "25.1"
  1225. :package-version '(Org . "8.3"))
  1226. (defgroup org-edit-structure nil
  1227. "Options concerning structure editing in Org-mode."
  1228. :tag "Org Edit Structure"
  1229. :group 'org-structure)
  1230. (defcustom org-odd-levels-only nil
  1231. "Non-nil means skip even levels and only use odd levels for the outline.
  1232. This has the effect that two stars are being added/taken away in
  1233. promotion/demotion commands. It also influences how levels are
  1234. handled by the exporters.
  1235. Changing it requires restart of `font-lock-mode' to become effective
  1236. for fontification also in regions already fontified.
  1237. You may also set this on a per-file basis by adding one of the following
  1238. lines to the buffer:
  1239. #+STARTUP: odd
  1240. #+STARTUP: oddeven"
  1241. :group 'org-edit-structure
  1242. :group 'org-appearance
  1243. :type 'boolean)
  1244. (defcustom org-adapt-indentation t
  1245. "Non-nil means adapt indentation to outline node level.
  1246. When this variable is set, Org assumes that you write outlines by
  1247. indenting text in each node to align with the headline (after the
  1248. stars). The following issues are influenced by this variable:
  1249. - The indentation is increased by one space in a demotion
  1250. command, and decreased by one in a promotion command. However,
  1251. in the latter case, if shifting some line in the entry body
  1252. would alter document structure (e.g., insert a new headline),
  1253. indentation is not changed at all.
  1254. - Property drawers and planning information is inserted indented
  1255. when this variable is set. When nil, they will not be indented.
  1256. - TAB indents a line relative to current level. The lines below
  1257. a headline will be indented when this variable is set.
  1258. Note that this is all about true indentation, by adding and
  1259. removing space characters. See also `org-indent.el' which does
  1260. level-dependent indentation in a virtual way, i.e. at display
  1261. time in Emacs."
  1262. :group 'org-edit-structure
  1263. :type 'boolean)
  1264. (defcustom org-special-ctrl-a/e nil
  1265. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1266. When t, `C-a' will bring back the cursor to the beginning of the
  1267. headline text, i.e. after the stars and after a possible TODO
  1268. keyword. In an item, this will be the position after bullet and
  1269. check-box, if any. When the cursor is already at that position,
  1270. another `C-a' will bring it to the beginning of the line.
  1271. `C-e' will jump to the end of the headline, ignoring the presence
  1272. of tags in the headline. A second `C-e' will then jump to the
  1273. true end of the line, after any tags. This also means that, when
  1274. this variable is non-nil, `C-e' also will never jump beyond the
  1275. end of the heading of a folded section, i.e. not after the
  1276. ellipses.
  1277. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1278. normally, going to the true line boundary first. Only a directly
  1279. following, identical keypress will bring the cursor to the
  1280. special positions.
  1281. This may also be a cons cell where the behavior for `C-a' and
  1282. `C-e' is set separately."
  1283. :group 'org-edit-structure
  1284. :type '(choice
  1285. (const :tag "off" nil)
  1286. (const :tag "on: after stars/bullet and before tags first" t)
  1287. (const :tag "reversed: true line boundary first" reversed)
  1288. (cons :tag "Set C-a and C-e separately"
  1289. (choice :tag "Special C-a"
  1290. (const :tag "off" nil)
  1291. (const :tag "on: after stars/bullet first" t)
  1292. (const :tag "reversed: before stars/bullet first" reversed))
  1293. (choice :tag "Special C-e"
  1294. (const :tag "off" nil)
  1295. (const :tag "on: before tags first" t)
  1296. (const :tag "reversed: after tags first" reversed)))))
  1297. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1298. (defcustom org-special-ctrl-k nil
  1299. "Non-nil means `C-k' will behave specially in headlines.
  1300. When nil, `C-k' will call the default `kill-line' command.
  1301. When t, the following will happen while the cursor is in the headline:
  1302. - When the cursor is at the beginning of a headline, kill the entire
  1303. line and possible the folded subtree below the line.
  1304. - When in the middle of the headline text, kill the headline up to the tags.
  1305. - When after the headline text, kill the tags."
  1306. :group 'org-edit-structure
  1307. :type 'boolean)
  1308. (defcustom org-ctrl-k-protect-subtree nil
  1309. "Non-nil means, do not delete a hidden subtree with C-k.
  1310. When set to the symbol `error', simply throw an error when C-k is
  1311. used to kill (part-of) a headline that has hidden text behind it.
  1312. Any other non-nil value will result in a query to the user, if it is
  1313. OK to kill that hidden subtree. When nil, kill without remorse."
  1314. :group 'org-edit-structure
  1315. :version "24.1"
  1316. :type '(choice
  1317. (const :tag "Do not protect hidden subtrees" nil)
  1318. (const :tag "Protect hidden subtrees with a security query" t)
  1319. (const :tag "Never kill a hidden subtree with C-k" error)))
  1320. (defcustom org-special-ctrl-o t
  1321. "Non-nil means, make `C-o' insert a row in tables."
  1322. :group 'org-edit-structure
  1323. :type 'boolean)
  1324. (defcustom org-catch-invisible-edits nil
  1325. "Check if in invisible region before inserting or deleting a character.
  1326. Valid values are:
  1327. nil Do not check, so just do invisible edits.
  1328. error Throw an error and do nothing.
  1329. show Make point visible, and do the requested edit.
  1330. show-and-error Make point visible, then throw an error and abort the edit.
  1331. smart Make point visible, and do insertion/deletion if it is
  1332. adjacent to visible text and the change feels predictable.
  1333. Never delete a previously invisible character or add in the
  1334. middle or right after an invisible region. Basically, this
  1335. allows insertion and backward-delete right before ellipses.
  1336. FIXME: maybe in this case we should not even show?"
  1337. :group 'org-edit-structure
  1338. :version "24.1"
  1339. :type '(choice
  1340. (const :tag "Do not check" nil)
  1341. (const :tag "Throw error when trying to edit" error)
  1342. (const :tag "Unhide, but do not do the edit" show-and-error)
  1343. (const :tag "Show invisible part and do the edit" show)
  1344. (const :tag "Be smart and do the right thing" smart)))
  1345. (defcustom org-yank-folded-subtrees t
  1346. "Non-nil means when yanking subtrees, fold them.
  1347. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1348. it starts with a heading and all other headings in it are either children
  1349. or siblings, then fold all the subtrees. However, do this only if no
  1350. text after the yank would be swallowed into a folded tree by this action."
  1351. :group 'org-edit-structure
  1352. :type 'boolean)
  1353. (defcustom org-yank-adjusted-subtrees nil
  1354. "Non-nil means when yanking subtrees, adjust the level.
  1355. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1356. this function for details."
  1357. :group 'org-edit-structure
  1358. :type 'boolean)
  1359. (defcustom org-M-RET-may-split-line '((default . t))
  1360. "Non-nil means M-RET will split the line at the cursor position.
  1361. When nil, it will go to the end of the line before making a
  1362. new line.
  1363. You may also set this option in a different way for different
  1364. contexts. Valid contexts are:
  1365. headline when creating a new headline
  1366. item when creating a new item
  1367. table in a table field
  1368. default the value to be used for all contexts not explicitly
  1369. customized"
  1370. :group 'org-structure
  1371. :group 'org-table
  1372. :type '(choice
  1373. (const :tag "Always" t)
  1374. (const :tag "Never" nil)
  1375. (repeat :greedy t :tag "Individual contexts"
  1376. (cons
  1377. (choice :tag "Context"
  1378. (const headline)
  1379. (const item)
  1380. (const table)
  1381. (const default))
  1382. (boolean)))))
  1383. (defcustom org-insert-heading-respect-content nil
  1384. "Non-nil means insert new headings after the current subtree.
  1385. When nil, the new heading is created directly after the current line.
  1386. The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
  1387. this variable on for the duration of the command."
  1388. :group 'org-structure
  1389. :type 'boolean)
  1390. (defcustom org-blank-before-new-entry '((heading . auto)
  1391. (plain-list-item . auto))
  1392. "Should `org-insert-heading' leave a blank line before new heading/item?
  1393. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1394. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1395. which case Org will look at the surrounding headings/items and try to
  1396. make an intelligent decision whether to insert a blank line or not."
  1397. :group 'org-edit-structure
  1398. :type '(list
  1399. (cons (const heading)
  1400. (choice (const :tag "Never" nil)
  1401. (const :tag "Always" t)
  1402. (const :tag "Auto" auto)))
  1403. (cons (const plain-list-item)
  1404. (choice (const :tag "Never" nil)
  1405. (const :tag "Always" t)
  1406. (const :tag "Auto" auto)))))
  1407. (defcustom org-insert-heading-hook nil
  1408. "Hook being run after inserting a new heading."
  1409. :group 'org-edit-structure
  1410. :type 'hook)
  1411. (defcustom org-enable-fixed-width-editor t
  1412. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1413. This currently only means they are never auto-wrapped.
  1414. When nil, such lines will be treated like ordinary lines."
  1415. :group 'org-edit-structure
  1416. :type 'boolean)
  1417. (defcustom org-goto-auto-isearch t
  1418. "Non-nil means typing characters in `org-goto' starts incremental search.
  1419. When nil, you can use these keybindings to navigate the buffer:
  1420. q Quit the org-goto interface
  1421. n Go to the next visible heading
  1422. p Go to the previous visible heading
  1423. f Go one heading forward on same level
  1424. b Go one heading backward on same level
  1425. u Go one heading up"
  1426. :group 'org-edit-structure
  1427. :type 'boolean)
  1428. (defgroup org-sparse-trees nil
  1429. "Options concerning sparse trees in Org-mode."
  1430. :tag "Org Sparse Trees"
  1431. :group 'org-structure)
  1432. (defcustom org-highlight-sparse-tree-matches t
  1433. "Non-nil means highlight all matches that define a sparse tree.
  1434. The highlights will automatically disappear the next time the buffer is
  1435. changed by an edit command."
  1436. :group 'org-sparse-trees
  1437. :type 'boolean)
  1438. (defcustom org-remove-highlights-with-change t
  1439. "Non-nil means any change to the buffer will remove temporary highlights.
  1440. \\<org-mode-map>\
  1441. Such highlights are created by `org-occur' and `org-clock-display'.
  1442. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1443. to get rid of the highlights.
  1444. The highlights created by `org-toggle-latex-fragment' always need
  1445. `\\[org-toggle-latex-fragment]' to be removed."
  1446. :group 'org-sparse-trees
  1447. :group 'org-time
  1448. :type 'boolean)
  1449. (defcustom org-occur-case-fold-search t
  1450. "Non-nil means `org-occur' should be case-insensitive.
  1451. If set to `smart' the search will be case-insensitive only if it
  1452. doesn't specify any upper case character."
  1453. :group 'org-sparse-trees
  1454. :version "25.1"
  1455. :type '(choice
  1456. (const :tag "Case-sensitive" nil)
  1457. (const :tag "Case-insensitive" t)
  1458. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1459. (defcustom org-occur-hook '(org-first-headline-recenter)
  1460. "Hook that is run after `org-occur' has constructed a sparse tree.
  1461. This can be used to recenter the window to show as much of the structure
  1462. as possible."
  1463. :group 'org-sparse-trees
  1464. :type 'hook)
  1465. (defgroup org-imenu-and-speedbar nil
  1466. "Options concerning imenu and speedbar in Org-mode."
  1467. :tag "Org Imenu and Speedbar"
  1468. :group 'org-structure)
  1469. (defcustom org-imenu-depth 2
  1470. "The maximum level for Imenu access to Org headlines.
  1471. This also applied for speedbar access."
  1472. :group 'org-imenu-and-speedbar
  1473. :type 'integer)
  1474. (defgroup org-table nil
  1475. "Options concerning tables in Org-mode."
  1476. :tag "Org Table"
  1477. :group 'org)
  1478. (defcustom org-enable-table-editor 'optimized
  1479. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1480. When nil, such lines will be treated like ordinary lines.
  1481. When equal to the symbol `optimized', the table editor will be optimized to
  1482. do the following:
  1483. - Automatic overwrite mode in front of whitespace in table fields.
  1484. This makes the structure of the table stay in tact as long as the edited
  1485. field does not exceed the column width.
  1486. - Minimize the number of realigns. Normally, the table is aligned each time
  1487. TAB or RET are pressed to move to another field. With optimization this
  1488. happens only if changes to a field might have changed the column width.
  1489. Optimization requires replacing the functions `self-insert-command',
  1490. `delete-char', and `backward-delete-char' in Org buffers, with a
  1491. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1492. good at guessing when a re-align will be necessary, but you can always
  1493. force one with \\[org-ctrl-c-ctrl-c].
  1494. If you would like to use the optimized version in Org-mode, but the
  1495. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1496. This variable can be used to turn on and off the table editor during a session,
  1497. but in order to toggle optimization, a restart is required.
  1498. See also the variable `org-table-auto-blank-field'."
  1499. :group 'org-table
  1500. :type '(choice
  1501. (const :tag "off" nil)
  1502. (const :tag "on" t)
  1503. (const :tag "on, optimized" optimized)))
  1504. (defcustom org-self-insert-cluster-for-undo nil
  1505. "Non-nil means cluster self-insert commands for undo when possible.
  1506. If this is set, then, like in the Emacs command loop, 20 consecutive
  1507. characters will be undone together.
  1508. This is configurable, because there is some impact on typing performance."
  1509. :group 'org-table
  1510. :type 'boolean)
  1511. (defcustom org-table-tab-recognizes-table.el t
  1512. "Non-nil means TAB will automatically notice a table.el table.
  1513. When it sees such a table, it moves point into it and - if necessary -
  1514. calls `table-recognize-table'."
  1515. :group 'org-table-editing
  1516. :type 'boolean)
  1517. (defgroup org-link nil
  1518. "Options concerning links in Org-mode."
  1519. :tag "Org Link"
  1520. :group 'org)
  1521. (defvar-local org-link-abbrev-alist-local nil
  1522. "Buffer-local version of `org-link-abbrev-alist', which see.
  1523. The value of this is taken from the #+LINK lines.")
  1524. (defcustom org-link-parameters
  1525. '(("doi" :follow org--open-doi-link)
  1526. ("elisp" :follow org--open-elisp-link)
  1527. ("file" :complete org-file-complete-link)
  1528. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1529. ("help" :follow org--open-help-link)
  1530. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1531. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1532. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1533. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1534. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1535. ("shell" :follow org--open-shell-link))
  1536. "An alist of properties that defines all the links in Org mode.
  1537. The key in each association is a string of the link type.
  1538. Subsequent optional elements make up a p-list of link properties.
  1539. :follow - A function that takes the link path as an argument.
  1540. :export - A function that takes the link path, description and
  1541. export-backend as arguments.
  1542. :store - A function responsible for storing the link. See the
  1543. function `org-store-link-functions'.
  1544. :complete - A function that inserts a link with completion. The
  1545. function takes one optional prefix arg.
  1546. :face - A face for the link, or a function that returns a face.
  1547. The function takes one argument which is the link path. The
  1548. default face is `org-link'.
  1549. :mouse-face - The mouse-face. The default is `highlight'.
  1550. :display - `full' will not fold the link in descriptive
  1551. display. Default is `org-link'.
  1552. :help-echo - A string or function that takes (window object position)
  1553. as arguments and returns a string.
  1554. :keymap - A keymap that is active on the link. The default is
  1555. `org-mouse-map'.
  1556. :htmlize-link - A function for the htmlize-link. Defaults
  1557. to (list :uri \"type:path\")
  1558. :activate-func - A function to run at the end of font-lock
  1559. activation. The function must accept (link-start link-end path bracketp)
  1560. as arguments."
  1561. :group 'org-link
  1562. :type '(alist :tag "Link display parameters"
  1563. :value-type plist))
  1564. (defun org-link-get-parameter (type key)
  1565. "Get TYPE link property for KEY.
  1566. TYPE is a string and KEY is a plist keyword."
  1567. (plist-get
  1568. (cdr (assoc type org-link-parameters))
  1569. key))
  1570. (defun org-link-set-parameters (type &rest parameters)
  1571. "Set link TYPE properties to PARAMETERS.
  1572. PARAMETERS should be :key val pairs."
  1573. (let ((data (assoc type org-link-parameters)))
  1574. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1575. (push (cons type parameters) org-link-parameters)
  1576. (org-make-link-regexps)
  1577. (org-element-update-syntax))))
  1578. (defun org-link-types ()
  1579. "Return a list of known link types."
  1580. (mapcar #'car org-link-parameters))
  1581. (defcustom org-link-abbrev-alist nil
  1582. "Alist of link abbreviations.
  1583. The car of each element is a string, to be replaced at the start of a link.
  1584. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1585. links in Org buffers can have an optional tag after a double colon, e.g.,
  1586. [[linkkey:tag][description]]
  1587. The `linkkey' must be a single word, starting with a letter, followed
  1588. by letters, numbers, `-' or `_'.
  1589. If REPLACE is a string, the tag will simply be appended to create the link.
  1590. If the string contains \"%s\", the tag will be inserted there. If the string
  1591. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1592. at that point (see the function `url-hexify-string'). If the string contains
  1593. the specifier \"%(my-function)\", then the custom function `my-function' will
  1594. be invoked: this function takes the tag as its only argument and must return
  1595. a string.
  1596. REPLACE may also be a function that will be called with the tag as the
  1597. only argument to create the link, which should be returned as a string.
  1598. See the manual for examples."
  1599. :group 'org-link
  1600. :type '(repeat
  1601. (cons
  1602. (string :tag "Protocol")
  1603. (choice
  1604. (string :tag "Format")
  1605. (function)))))
  1606. (defcustom org-descriptive-links t
  1607. "Non-nil means Org will display descriptive links.
  1608. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1609. \"Org Website\", hiding the link itself and just displaying its
  1610. description. When set to nil, Org will display the full links
  1611. literally.
  1612. You can interactively set the value of this variable by calling
  1613. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1614. :group 'org-link
  1615. :type 'boolean)
  1616. (defcustom org-link-file-path-type 'adaptive
  1617. "How the path name in file links should be stored.
  1618. Valid values are:
  1619. relative Relative to the current directory, i.e. the directory of the file
  1620. into which the link is being inserted.
  1621. absolute Absolute path, if possible with ~ for home directory.
  1622. noabbrev Absolute path, no abbreviation of home directory.
  1623. adaptive Use relative path for files in the current directory and sub-
  1624. directories of it. For other files, use an absolute path."
  1625. :group 'org-link
  1626. :type '(choice
  1627. (const relative)
  1628. (const absolute)
  1629. (const noabbrev)
  1630. (const adaptive)))
  1631. (defvaralias 'org-activate-links 'org-highlight-links)
  1632. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1633. "Types of links that should be highlighted in Org files.
  1634. This is a list of symbols, each one of them leading to the
  1635. highlighting of a certain link type.
  1636. You can still open links that are not highlighted.
  1637. In principle, it does not hurt to turn on highlighting for all
  1638. link types. There may be a small gain when turning off unused
  1639. link types. The types are:
  1640. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1641. angle Links in angular brackets that may contain whitespace like
  1642. <bbdb:Carsten Dominik>.
  1643. plain Plain links in normal text, no whitespace, like http://google.com.
  1644. radio Text that is matched by a radio target, see manual for details.
  1645. tag Tag settings in a headline (link to tag search).
  1646. date Time stamps (link to calendar).
  1647. footnote Footnote labels.
  1648. If you set this variable during an Emacs session, use `org-mode-restart'
  1649. in the Org buffer so that the change takes effect."
  1650. :group 'org-link
  1651. :group 'org-appearance
  1652. :type '(set :greedy t
  1653. (const :tag "Double bracket links" bracket)
  1654. (const :tag "Angular bracket links" angle)
  1655. (const :tag "Plain text links" plain)
  1656. (const :tag "Radio target matches" radio)
  1657. (const :tag "Tags" tag)
  1658. (const :tag "Timestamps" date)
  1659. (const :tag "Footnotes" footnote)))
  1660. (defcustom org-make-link-description-function nil
  1661. "Function to use for generating link descriptions from links.
  1662. When nil, the link location will be used. This function must take
  1663. two parameters: the first one is the link, the second one is the
  1664. description generated by `org-insert-link'. The function should
  1665. return the description to use."
  1666. :group 'org-link
  1667. :type '(choice (const nil) (function)))
  1668. (defgroup org-link-store nil
  1669. "Options concerning storing links in Org-mode."
  1670. :tag "Org Store Link"
  1671. :group 'org-link)
  1672. (defcustom org-url-hexify-p t
  1673. "When non-nil, hexify URL when creating a link."
  1674. :type 'boolean
  1675. :version "24.3"
  1676. :group 'org-link-store)
  1677. (defcustom org-email-link-description-format "Email %c: %.30s"
  1678. "Format of the description part of a link to an email or usenet message.
  1679. The following %-escapes will be replaced by corresponding information:
  1680. %F full \"From\" field
  1681. %f name, taken from \"From\" field, address if no name
  1682. %T full \"To\" field
  1683. %t first name in \"To\" field, address if no name
  1684. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1685. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1686. %s subject
  1687. %d date
  1688. %m message-id.
  1689. You may use normal field width specification between the % and the letter.
  1690. This is for example useful to limit the length of the subject.
  1691. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1692. :group 'org-link-store
  1693. :type 'string)
  1694. (defcustom org-from-is-user-regexp
  1695. (let (r1 r2)
  1696. (when (and user-mail-address (not (string= user-mail-address "")))
  1697. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1698. (when (and user-full-name (not (string= user-full-name "")))
  1699. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1700. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1701. "Regexp matched against the \"From:\" header of an email or usenet message.
  1702. It should match if the message is from the user him/herself."
  1703. :group 'org-link-store
  1704. :type 'regexp)
  1705. (defcustom org-context-in-file-links t
  1706. "Non-nil means file links from `org-store-link' contain context.
  1707. A search string will be added to the file name with :: as separator and
  1708. used to find the context when the link is activated by the command
  1709. `org-open-at-point'. When this option is t, the entire active region
  1710. will be placed in the search string of the file link. If set to a
  1711. positive integer, only the first n lines of context will be stored.
  1712. Using a prefix arg to the command \\[org-store-link] (`org-store-link')
  1713. negates this setting for the duration of the command."
  1714. :group 'org-link-store
  1715. :type '(choice boolean integer))
  1716. (defcustom org-keep-stored-link-after-insertion nil
  1717. "Non-nil means keep link in list for entire session.
  1718. The command `org-store-link' adds a link pointing to the current
  1719. location to an internal list. These links accumulate during a session.
  1720. The command `org-insert-link' can be used to insert links into any
  1721. Org file (offering completion for all stored links). When this option
  1722. is nil, every link which has been inserted once using \\[org-insert-link]
  1723. will be removed from the list, to make completing the unused links
  1724. more efficient."
  1725. :group 'org-link-store
  1726. :type 'boolean)
  1727. (defgroup org-link-follow nil
  1728. "Options concerning following links in Org-mode."
  1729. :tag "Org Follow Link"
  1730. :group 'org-link)
  1731. (defcustom org-link-translation-function nil
  1732. "Function to translate links with different syntax to Org syntax.
  1733. This can be used to translate links created for example by the Planner
  1734. or emacs-wiki packages to Org syntax.
  1735. The function must accept two parameters, a TYPE containing the link
  1736. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1737. which is everything after the link protocol. It should return a cons
  1738. with possibly modified values of type and path.
  1739. Org contains a function for this, so if you set this variable to
  1740. `org-translate-link-from-planner', you should be able follow many
  1741. links created by planner."
  1742. :group 'org-link-follow
  1743. :type '(choice (const nil) (function)))
  1744. (defcustom org-follow-link-hook nil
  1745. "Hook that is run after a link has been followed."
  1746. :group 'org-link-follow
  1747. :type 'hook)
  1748. (defcustom org-tab-follows-link nil
  1749. "Non-nil means on links TAB will follow the link.
  1750. Needs to be set before org.el is loaded.
  1751. This really should not be used, it does not make sense, and the
  1752. implementation is bad."
  1753. :group 'org-link-follow
  1754. :type 'boolean)
  1755. (defcustom org-return-follows-link nil
  1756. "Non-nil means on links RET will follow the link.
  1757. In tables, the special behavior of RET has precedence."
  1758. :group 'org-link-follow
  1759. :type 'boolean)
  1760. (defcustom org-mouse-1-follows-link
  1761. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1762. "Non-nil means mouse-1 on a link will follow the link.
  1763. A longer mouse click will still set point. Needs to be set
  1764. before org.el is loaded."
  1765. :group 'org-link-follow
  1766. :version "24.4"
  1767. :package-version '(Org . "8.3")
  1768. :type '(choice
  1769. (const :tag "A double click follows the link" double)
  1770. (const :tag "Unconditionally follow the link with mouse-1" t)
  1771. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1772. (defcustom org-mark-ring-length 4
  1773. "Number of different positions to be recorded in the ring.
  1774. Changing this requires a restart of Emacs to work correctly."
  1775. :group 'org-link-follow
  1776. :type 'integer)
  1777. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1778. "Non-nil means internal links in Org files must exactly match a headline.
  1779. When nil, the link search tries to match a phrase with all words
  1780. in the search text."
  1781. :group 'org-link-follow
  1782. :version "24.1"
  1783. :type '(choice
  1784. (const :tag "Use fuzzy text search" nil)
  1785. (const :tag "Match only exact headline" t)
  1786. (const :tag "Match exact headline or query to create it"
  1787. query-to-create)))
  1788. (defcustom org-link-frame-setup
  1789. '((vm . vm-visit-folder-other-frame)
  1790. (vm-imap . vm-visit-imap-folder-other-frame)
  1791. (gnus . org-gnus-no-new-news)
  1792. (file . find-file-other-window)
  1793. (wl . wl-other-frame))
  1794. "Setup the frame configuration for following links.
  1795. When following a link with Emacs, it may often be useful to display
  1796. this link in another window or frame. This variable can be used to
  1797. set this up for the different types of links.
  1798. For VM, use any of
  1799. `vm-visit-folder'
  1800. `vm-visit-folder-other-window'
  1801. `vm-visit-folder-other-frame'
  1802. For Gnus, use any of
  1803. `gnus'
  1804. `gnus-other-frame'
  1805. `org-gnus-no-new-news'
  1806. For FILE, use any of
  1807. `find-file'
  1808. `find-file-other-window'
  1809. `find-file-other-frame'
  1810. For Wanderlust use any of
  1811. `wl'
  1812. `wl-other-frame'
  1813. For the calendar, use the variable `calendar-setup'.
  1814. For BBDB, it is currently only possible to display the matches in
  1815. another window."
  1816. :group 'org-link-follow
  1817. :type '(list
  1818. (cons (const vm)
  1819. (choice
  1820. (const vm-visit-folder)
  1821. (const vm-visit-folder-other-window)
  1822. (const vm-visit-folder-other-frame)))
  1823. (cons (const vm-imap)
  1824. (choice
  1825. (const vm-visit-imap-folder)
  1826. (const vm-visit-imap-folder-other-window)
  1827. (const vm-visit-imap-folder-other-frame)))
  1828. (cons (const gnus)
  1829. (choice
  1830. (const gnus)
  1831. (const gnus-other-frame)
  1832. (const org-gnus-no-new-news)))
  1833. (cons (const file)
  1834. (choice
  1835. (const find-file)
  1836. (const find-file-other-window)
  1837. (const find-file-other-frame)))
  1838. (cons (const wl)
  1839. (choice
  1840. (const wl)
  1841. (const wl-other-frame)))))
  1842. (defcustom org-display-internal-link-with-indirect-buffer nil
  1843. "Non-nil means use indirect buffer to display infile links.
  1844. Activating internal links (from one location in a file to another location
  1845. in the same file) normally just jumps to the location. When the link is
  1846. activated with a \\[universal-argument] prefix (or with mouse-3), the link \
  1847. is displayed in
  1848. another window. When this option is set, the other window actually displays
  1849. an indirect buffer clone of the current buffer, to avoid any visibility
  1850. changes to the current buffer."
  1851. :group 'org-link-follow
  1852. :type 'boolean)
  1853. (defcustom org-open-non-existing-files nil
  1854. "Non-nil means `org-open-file' will open non-existing files.
  1855. When nil, an error will be generated.
  1856. This variable applies only to external applications because they
  1857. might choke on non-existing files. If the link is to a file that
  1858. will be opened in Emacs, the variable is ignored."
  1859. :group 'org-link-follow
  1860. :type 'boolean)
  1861. (defcustom org-open-directory-means-index-dot-org nil
  1862. "Non-nil means a link to a directory really means to index.org.
  1863. When nil, following a directory link will run dired or open a finder/explorer
  1864. window on that directory."
  1865. :group 'org-link-follow
  1866. :type 'boolean)
  1867. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1868. "Non-nil means ask for confirmation before executing shell links.
  1869. Shell links can be dangerous: just think about a link
  1870. [[shell:rm -rf ~/*][Google Search]]
  1871. This link would show up in your Org document as \"Google Search\",
  1872. but really it would remove your entire home directory.
  1873. Therefore we advise against setting this variable to nil.
  1874. Just change it to `y-or-n-p' if you want to confirm with a
  1875. single keystroke rather than having to type \"yes\"."
  1876. :group 'org-link-follow
  1877. :type '(choice
  1878. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1879. (const :tag "with y-or-n (faster)" y-or-n-p)
  1880. (const :tag "no confirmation (dangerous)" nil)))
  1881. (put 'org-confirm-shell-link-function
  1882. 'safe-local-variable
  1883. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1884. (defcustom org-confirm-shell-link-not-regexp ""
  1885. "A regexp to skip confirmation for shell links."
  1886. :group 'org-link-follow
  1887. :version "24.1"
  1888. :type 'regexp)
  1889. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1890. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1891. Elisp links can be dangerous: just think about a link
  1892. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1893. This link would show up in your Org document as \"Google Search\",
  1894. but really it would remove your entire home directory.
  1895. Therefore we advise against setting this variable to nil.
  1896. Just change it to `y-or-n-p' if you want to confirm with a
  1897. single keystroke rather than having to type \"yes\"."
  1898. :group 'org-link-follow
  1899. :type '(choice
  1900. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1901. (const :tag "with y-or-n (faster)" y-or-n-p)
  1902. (const :tag "no confirmation (dangerous)" nil)))
  1903. (put 'org-confirm-shell-link-function
  1904. 'safe-local-variable
  1905. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1906. (defcustom org-confirm-elisp-link-not-regexp ""
  1907. "A regexp to skip confirmation for Elisp links."
  1908. :group 'org-link-follow
  1909. :version "24.1"
  1910. :type 'regexp)
  1911. (defconst org-file-apps-defaults-gnu
  1912. '((remote . emacs)
  1913. (system . mailcap)
  1914. (t . mailcap))
  1915. "Default file applications on a UNIX or GNU/Linux system.
  1916. See `org-file-apps'.")
  1917. (defconst org-file-apps-defaults-macosx
  1918. '((remote . emacs)
  1919. (system . "open %s")
  1920. ("ps.gz" . "gv %s")
  1921. ("eps.gz" . "gv %s")
  1922. ("dvi" . "xdvi %s")
  1923. ("fig" . "xfig %s")
  1924. (t . "open %s"))
  1925. "Default file applications on a MacOS X system.
  1926. The system \"open\" is known as a default, but we use X11 applications
  1927. for some files for which the OS does not have a good default.
  1928. See `org-file-apps'.")
  1929. (defconst org-file-apps-defaults-windowsnt
  1930. (list '(remote . emacs)
  1931. (cons 'system (lambda (file _path)
  1932. (with-no-warnings (w32-shell-execute "open" file))))
  1933. (cons t (lambda (file _path)
  1934. (with-no-warnings (w32-shell-execute "open" file)))))
  1935. "Default file applications on a Windows NT system.
  1936. The system \"open\" is used for most files.
  1937. See `org-file-apps'.")
  1938. (defcustom org-file-apps
  1939. '((auto-mode . emacs)
  1940. ("\\.mm\\'" . default)
  1941. ("\\.x?html?\\'" . default)
  1942. ("\\.pdf\\'" . default))
  1943. "External applications for opening `file:path' items in a document.
  1944. \\<org-mode-map>\
  1945. Org mode uses system defaults for different file types, but
  1946. you can use this variable to set the application for a given file
  1947. extension. The entries in this list are cons cells where the car identifies
  1948. files and the cdr the corresponding command.
  1949. Possible values for the file identifier are:
  1950. \"string\" A string as a file identifier can be interpreted in different
  1951. ways, depending on its contents:
  1952. - Alphanumeric characters only:
  1953. Match links with this file extension.
  1954. Example: (\"pdf\" . \"evince %s\")
  1955. to open PDFs with evince.
  1956. - Regular expression: Match links where the
  1957. filename matches the regexp. If you want to
  1958. use groups here, use shy groups.
  1959. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1960. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1961. to open *.html and *.xhtml with firefox.
  1962. - Regular expression which contains (non-shy) groups:
  1963. Match links where the whole link, including \"::\", and
  1964. anything after that, matches the regexp.
  1965. In a custom command string, %1, %2, etc. are replaced with
  1966. the parts of the link that were matched by the groups.
  1967. For backwards compatibility, if a command string is given
  1968. that does not use any of the group matches, this case is
  1969. handled identically to the second one (i.e. match against
  1970. file name only).
  1971. In a custom function, you can access the group matches with
  1972. \(match-string n link).
  1973. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1974. \"evince -p %1 %s\")
  1975. to open [[file:document.pdf::5]] with evince at page 5.
  1976. `directory' Matches a directory
  1977. `remote' Matches a remote file, accessible through tramp or efs.
  1978. Remote files most likely should be visited through Emacs
  1979. because external applications cannot handle such paths.
  1980. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1981. so all files Emacs knows how to handle. Using this with
  1982. command `emacs' will open most files in Emacs. Beware that this
  1983. will also open html files inside Emacs, unless you add
  1984. \(\"html\" . default) to the list as well.
  1985. `system' The system command to open files, like `open' on Windows
  1986. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1987. that will be selected if you call \\[org-open-at-point] with a double
  1988. \\[universal-argument] \\[universal-argument] prefix.
  1989. t Default for files not matched by any of the other options.
  1990. Possible values for the command are:
  1991. `emacs' The file will be visited by the current Emacs process.
  1992. `default' Use the default application for this file type, which is the
  1993. association for t in the list, most likely in the system-specific
  1994. part. This can be used to overrule an unwanted setting in the
  1995. system-specific variable.
  1996. `system' Use the system command for opening files, like \"open\".
  1997. This command is specified by the entry whose car is `system'.
  1998. Most likely, the system-specific version of this variable
  1999. does define this command, but you can overrule/replace it
  2000. here.
  2001. `mailcap' Use command specified in the mailcaps.
  2002. string A command to be executed by a shell; %s will be replaced
  2003. by the path to the file.
  2004. function A Lisp function, which will be called with two arguments:
  2005. the file path and the original link string, without the
  2006. \"file:\" prefix.
  2007. For more examples, see the system specific constants
  2008. `org-file-apps-defaults-macosx'
  2009. `org-file-apps-defaults-windowsnt'
  2010. `org-file-apps-defaults-gnu'."
  2011. :group 'org-link-follow
  2012. :type '(repeat
  2013. (cons (choice :value ""
  2014. (string :tag "Extension")
  2015. (const :tag "System command to open files" system)
  2016. (const :tag "Default for unrecognized files" t)
  2017. (const :tag "Remote file" remote)
  2018. (const :tag "Links to a directory" directory)
  2019. (const :tag "Any files that have Emacs modes"
  2020. auto-mode))
  2021. (choice :value ""
  2022. (const :tag "Visit with Emacs" emacs)
  2023. (const :tag "Use default" default)
  2024. (const :tag "Use the system command" system)
  2025. (string :tag "Command")
  2026. (function :tag "Function")))))
  2027. (defcustom org-doi-server-url "http://dx.doi.org/"
  2028. "The URL of the DOI server."
  2029. :type 'string
  2030. :version "24.3"
  2031. :group 'org-link-follow)
  2032. (defgroup org-refile nil
  2033. "Options concerning refiling entries in Org-mode."
  2034. :tag "Org Refile"
  2035. :group 'org)
  2036. (defcustom org-directory "~/org"
  2037. "Directory with Org files.
  2038. This is just a default location to look for Org files. There is no need
  2039. at all to put your files into this directory. It is used in the
  2040. following situations:
  2041. 1. When a capture template specifies a target file that is not an
  2042. absolute path. The path will then be interpreted relative to
  2043. `org-directory'
  2044. 2. When the value of variable `org-agenda-files' is a single file, any
  2045. relative paths in this file will be taken as relative to
  2046. `org-directory'."
  2047. :group 'org-refile
  2048. :group 'org-capture
  2049. :type 'directory)
  2050. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2051. "Default target for storing notes.
  2052. Used as a fall back file for org-capture.el, for templates that
  2053. do not specify a target file."
  2054. :group 'org-refile
  2055. :group 'org-capture
  2056. :type 'file)
  2057. (defcustom org-goto-interface 'outline
  2058. "The default interface to be used for `org-goto'.
  2059. Allowed values are:
  2060. outline The interface shows an outline of the relevant file
  2061. and the correct heading is found by moving through
  2062. the outline or by searching with incremental search.
  2063. outline-path-completion Headlines in the current buffer are offered via
  2064. completion. This is the interface also used by
  2065. the refile command."
  2066. :group 'org-refile
  2067. :type '(choice
  2068. (const :tag "Outline" outline)
  2069. (const :tag "Outline-path-completion" outline-path-completion)))
  2070. (defcustom org-goto-max-level 5
  2071. "Maximum target level when running `org-goto' with refile interface."
  2072. :group 'org-refile
  2073. :type 'integer)
  2074. (defcustom org-reverse-note-order nil
  2075. "Non-nil means store new notes at the beginning of a file or entry.
  2076. When nil, new notes will be filed to the end of a file or entry.
  2077. This can also be a list with cons cells of regular expressions that
  2078. are matched against file names, and values."
  2079. :group 'org-capture
  2080. :group 'org-refile
  2081. :type '(choice
  2082. (const :tag "Reverse always" t)
  2083. (const :tag "Reverse never" nil)
  2084. (repeat :tag "By file name regexp"
  2085. (cons regexp boolean))))
  2086. (defcustom org-log-refile nil
  2087. "Information to record when a task is refiled.
  2088. Possible values are:
  2089. nil Don't add anything
  2090. time Add a time stamp to the task
  2091. note Prompt for a note and add it with template `org-log-note-headings'
  2092. This option can also be set with on a per-file-basis with
  2093. #+STARTUP: nologrefile
  2094. #+STARTUP: logrefile
  2095. #+STARTUP: lognoterefile
  2096. You can have local logging settings for a subtree by setting the LOGGING
  2097. property to one or more of these keywords.
  2098. When bulk-refiling from the agenda, the value `note' is forbidden and
  2099. will temporarily be changed to `time'."
  2100. :group 'org-refile
  2101. :group 'org-progress
  2102. :version "24.1"
  2103. :type '(choice
  2104. (const :tag "No logging" nil)
  2105. (const :tag "Record timestamp" time)
  2106. (const :tag "Record timestamp with note." note)))
  2107. (defcustom org-refile-targets nil
  2108. "Targets for refiling entries with \\[org-refile].
  2109. This is a list of cons cells. Each cell contains:
  2110. - a specification of the files to be considered, either a list of files,
  2111. or a symbol whose function or variable value will be used to retrieve
  2112. a file name or a list of file names. If you use `org-agenda-files' for
  2113. that, all agenda files will be scanned for targets. Nil means consider
  2114. headings in the current buffer.
  2115. - A specification of how to find candidate refile targets. This may be
  2116. any of:
  2117. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2118. This tag has to be present in all target headlines, inheritance will
  2119. not be considered.
  2120. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2121. todo keyword.
  2122. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2123. headlines that are refiling targets.
  2124. - a cons cell (:level . N). Any headline of level N is considered a target.
  2125. Note that, when `org-odd-levels-only' is set, level corresponds to
  2126. order in hierarchy, not to the number of stars.
  2127. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2128. Note that, when `org-odd-levels-only' is set, level corresponds to
  2129. order in hierarchy, not to the number of stars.
  2130. Each element of this list generates a set of possible targets.
  2131. The union of these sets is presented (with completion) to
  2132. the user by `org-refile'.
  2133. You can set the variable `org-refile-target-verify-function' to a function
  2134. to verify each headline found by the simple criteria above.
  2135. When this variable is nil, all top-level headlines in the current buffer
  2136. are used, equivalent to the value `((nil . (:level . 1))'."
  2137. :group 'org-refile
  2138. :type '(repeat
  2139. (cons
  2140. (choice :value org-agenda-files
  2141. (const :tag "All agenda files" org-agenda-files)
  2142. (const :tag "Current buffer" nil)
  2143. (function) (variable) (file))
  2144. (choice :tag "Identify target headline by"
  2145. (cons :tag "Specific tag" (const :value :tag) (string))
  2146. (cons :tag "TODO keyword" (const :value :todo) (string))
  2147. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2148. (cons :tag "Level number" (const :value :level) (integer))
  2149. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2150. (defcustom org-refile-target-verify-function nil
  2151. "Function to verify if the headline at point should be a refile target.
  2152. The function will be called without arguments, with point at the
  2153. beginning of the headline. It should return t and leave point
  2154. where it is if the headline is a valid target for refiling.
  2155. If the target should not be selected, the function must return nil.
  2156. In addition to this, it may move point to a place from where the search
  2157. should be continued. For example, the function may decide that the entire
  2158. subtree of the current entry should be excluded and move point to the end
  2159. of the subtree."
  2160. :group 'org-refile
  2161. :type '(choice
  2162. (const nil)
  2163. (function)))
  2164. (defcustom org-refile-use-cache nil
  2165. "Non-nil means cache refile targets to speed up the process.
  2166. \\<org-mode-map>\
  2167. The cache for a particular file will be updated automatically when
  2168. the buffer has been killed, or when any of the marker used for flagging
  2169. refile targets no longer points at a live buffer.
  2170. If you have added new entries to a buffer that might themselves be targets,
  2171. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2172. if you find that easier, \
  2173. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2174. \\[org-refile]'."
  2175. :group 'org-refile
  2176. :version "24.1"
  2177. :type 'boolean)
  2178. (defcustom org-refile-use-outline-path nil
  2179. "Non-nil means provide refile targets as paths.
  2180. So a level 3 headline will be available as level1/level2/level3.
  2181. When the value is `file', also include the file name (without directory)
  2182. into the path. In this case, you can also stop the completion after
  2183. the file name, to get entries inserted as top level in the file.
  2184. When `full-file-path', include the full file path."
  2185. :group 'org-refile
  2186. :type '(choice
  2187. (const :tag "Not" nil)
  2188. (const :tag "Yes" t)
  2189. (const :tag "Start with file name" file)
  2190. (const :tag "Start with full file path" full-file-path)))
  2191. (defcustom org-outline-path-complete-in-steps t
  2192. "Non-nil means complete the outline path in hierarchical steps.
  2193. When Org uses the refile interface to select an outline path (see
  2194. `org-refile-use-outline-path'), the completion of the path can be
  2195. done in a single go, or it can be done in steps down the headline
  2196. hierarchy. Going in steps is probably the best if you do not use
  2197. a special completion package like `ido' or `icicles'. However,
  2198. when using these packages, going in one step can be very fast,
  2199. while still showing the whole path to the entry."
  2200. :group 'org-refile
  2201. :type 'boolean)
  2202. (defcustom org-refile-allow-creating-parent-nodes nil
  2203. "Non-nil means allow the creation of new nodes as refile targets.
  2204. New nodes are then created by adding \"/new node name\" to the completion
  2205. of an existing node. When the value of this variable is `confirm',
  2206. new node creation must be confirmed by the user (recommended).
  2207. When nil, the completion must match an existing entry.
  2208. Note that, if the new heading is not seen by the criteria
  2209. listed in `org-refile-targets', multiple instances of the same
  2210. heading would be created by trying again to file under the new
  2211. heading."
  2212. :group 'org-refile
  2213. :type '(choice
  2214. (const :tag "Never" nil)
  2215. (const :tag "Always" t)
  2216. (const :tag "Prompt for confirmation" confirm)))
  2217. (defcustom org-refile-active-region-within-subtree nil
  2218. "Non-nil means also refile active region within a subtree.
  2219. By default `org-refile' doesn't allow refiling regions if they
  2220. don't contain a set of subtrees, but it might be convenient to
  2221. do so sometimes: in that case, the first line of the region is
  2222. converted to a headline before refiling."
  2223. :group 'org-refile
  2224. :version "24.1"
  2225. :type 'boolean)
  2226. (defgroup org-todo nil
  2227. "Options concerning TODO items in Org-mode."
  2228. :tag "Org TODO"
  2229. :group 'org)
  2230. (defgroup org-progress nil
  2231. "Options concerning Progress logging in Org-mode."
  2232. :tag "Org Progress"
  2233. :group 'org-time)
  2234. (defvar org-todo-interpretation-widgets
  2235. '((:tag "Sequence (cycling hits every state)" sequence)
  2236. (:tag "Type (cycling directly to DONE)" type))
  2237. "The available interpretation symbols for customizing `org-todo-keywords'.
  2238. Interested libraries should add to this list.")
  2239. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2240. "List of TODO entry keyword sequences and their interpretation.
  2241. \\<org-mode-map>This is a list of sequences.
  2242. Each sequence starts with a symbol, either `sequence' or `type',
  2243. indicating if the keywords should be interpreted as a sequence of
  2244. action steps, or as different types of TODO items. The first
  2245. keywords are states requiring action - these states will select a headline
  2246. for inclusion into the global TODO list Org produces. If one of the
  2247. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2248. signify that no further action is necessary. If \"|\" is not found,
  2249. the last keyword is treated as the only DONE state of the sequence.
  2250. The command \\[org-todo] cycles an entry through these states, and one
  2251. additional state where no keyword is present. For details about this
  2252. cycling, see the manual.
  2253. TODO keywords and interpretation can also be set on a per-file basis with
  2254. the special #+SEQ_TODO and #+TYP_TODO lines.
  2255. Each keyword can optionally specify a character for fast state selection
  2256. \(in combination with the variable `org-use-fast-todo-selection')
  2257. and specifiers for state change logging, using the same syntax that
  2258. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2259. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2260. indicates to record a time stamp each time this state is selected.
  2261. Each keyword may also specify if a timestamp or a note should be
  2262. recorded when entering or leaving the state, by adding additional
  2263. characters in the parenthesis after the keyword. This looks like this:
  2264. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2265. record only the time of the state change. With X and Y being either
  2266. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2267. Y when leaving the state if and only if the *target* state does not
  2268. define X. You may omit any of the fast-selection key or X or /Y,
  2269. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2270. For backward compatibility, this variable may also be just a list
  2271. of keywords. In this case the interpretation (sequence or type) will be
  2272. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2273. :group 'org-todo
  2274. :group 'org-keywords
  2275. :type '(choice
  2276. (repeat :tag "Old syntax, just keywords"
  2277. (string :tag "Keyword"))
  2278. (repeat :tag "New syntax"
  2279. (cons
  2280. (choice
  2281. :tag "Interpretation"
  2282. ;;Quick and dirty way to see
  2283. ;;`org-todo-interpretations'. This takes the
  2284. ;;place of item arguments
  2285. :convert-widget
  2286. (lambda (widget)
  2287. (widget-put widget
  2288. :args (mapcar
  2289. (lambda (x)
  2290. (widget-convert
  2291. (cons 'const x)))
  2292. org-todo-interpretation-widgets))
  2293. widget))
  2294. (repeat
  2295. (string :tag "Keyword"))))))
  2296. (defvar-local org-todo-keywords-1 nil
  2297. "All TODO and DONE keywords active in a buffer.")
  2298. (defvar org-todo-keywords-for-agenda nil)
  2299. (defvar org-done-keywords-for-agenda nil)
  2300. (defvar org-todo-keyword-alist-for-agenda nil)
  2301. (defvar org-tag-alist-for-agenda nil
  2302. "Alist of all tags from all agenda files.")
  2303. (defvar org-tag-groups-alist-for-agenda nil
  2304. "Alist of all groups tags from all current agenda files.")
  2305. (defvar-local org-tag-groups-alist nil)
  2306. (defvar org-agenda-contributing-files nil)
  2307. (defvar-local org-current-tag-alist nil
  2308. "Alist of all tag groups in current buffer.
  2309. This variable takes into consideration `org-tag-alist',
  2310. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2311. (defvar-local org-not-done-keywords nil)
  2312. (defvar-local org-done-keywords nil)
  2313. (defvar-local org-todo-heads nil)
  2314. (defvar-local org-todo-sets nil)
  2315. (defvar-local org-todo-log-states nil)
  2316. (defvar-local org-todo-kwd-alist nil)
  2317. (defvar-local org-todo-key-alist nil)
  2318. (defvar-local org-todo-key-trigger nil)
  2319. (defcustom org-todo-interpretation 'sequence
  2320. "Controls how TODO keywords are interpreted.
  2321. This variable is in principle obsolete and is only used for
  2322. backward compatibility, if the interpretation of todo keywords is
  2323. not given already in `org-todo-keywords'. See that variable for
  2324. more information."
  2325. :group 'org-todo
  2326. :group 'org-keywords
  2327. :type '(choice (const sequence)
  2328. (const type)))
  2329. (defcustom org-use-fast-todo-selection t
  2330. "\\<org-mode-map>\
  2331. Non-nil means use the fast todo selection scheme with \\[org-todo].
  2332. This variable describes if and under what circumstances the cycling
  2333. mechanism for TODO keywords will be replaced by a single-key, direct
  2334. selection scheme.
  2335. When nil, fast selection is never used.
  2336. When the symbol `prefix', it will be used when `org-todo' is called
  2337. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2338. in an Org buffer, and
  2339. `\\[universal-argument] t' in an agenda buffer.
  2340. When t, fast selection is used by default. In this case, the prefix
  2341. argument forces cycling instead.
  2342. In all cases, the special interface is only used if access keys have
  2343. actually been assigned by the user, i.e. if keywords in the configuration
  2344. are followed by a letter in parenthesis, like TODO(t)."
  2345. :group 'org-todo
  2346. :type '(choice
  2347. (const :tag "Never" nil)
  2348. (const :tag "By default" t)
  2349. (const :tag "Only with C-u C-c C-t" prefix)))
  2350. (defcustom org-provide-todo-statistics t
  2351. "Non-nil means update todo statistics after insert and toggle.
  2352. ALL-HEADLINES means update todo statistics by including headlines
  2353. with no TODO keyword as well, counting them as not done.
  2354. A list of TODO keywords means the same, but skip keywords that are
  2355. not in this list.
  2356. When set to a list of two lists, the first list contains keywords
  2357. to consider as TODO keywords, the second list contains keywords
  2358. to consider as DONE keywords.
  2359. When this is set, todo statistics is updated in the parent of the
  2360. current entry each time a todo state is changed."
  2361. :group 'org-todo
  2362. :type '(choice
  2363. (const :tag "Yes, only for TODO entries" t)
  2364. (const :tag "Yes, including all entries" all-headlines)
  2365. (repeat :tag "Yes, for TODOs in this list"
  2366. (string :tag "TODO keyword"))
  2367. (list :tag "Yes, for TODOs and DONEs in these lists"
  2368. (repeat (string :tag "TODO keyword"))
  2369. (repeat (string :tag "DONE keyword")))
  2370. (other :tag "No TODO statistics" nil)))
  2371. (defcustom org-hierarchical-todo-statistics t
  2372. "Non-nil means TODO statistics covers just direct children.
  2373. When nil, all entries in the subtree are considered.
  2374. This has only an effect if `org-provide-todo-statistics' is set.
  2375. To set this to nil for only a single subtree, use a COOKIE_DATA
  2376. property and include the word \"recursive\" into the value."
  2377. :group 'org-todo
  2378. :type 'boolean)
  2379. (defcustom org-after-todo-state-change-hook nil
  2380. "Hook which is run after the state of a TODO item was changed.
  2381. The new state (a string with a TODO keyword, or nil) is available in the
  2382. Lisp variable `org-state'."
  2383. :group 'org-todo
  2384. :type 'hook)
  2385. (defvar org-blocker-hook nil
  2386. "Hook for functions that are allowed to block a state change.
  2387. Functions in this hook should not modify the buffer.
  2388. Each function gets as its single argument a property list,
  2389. see `org-trigger-hook' for more information about this list.
  2390. If any of the functions in this hook returns nil, the state change
  2391. is blocked.")
  2392. (defvar org-trigger-hook nil
  2393. "Hook for functions that are triggered by a state change.
  2394. Each function gets as its single argument a property list with at
  2395. least the following elements:
  2396. (:type type-of-change :position pos-at-entry-start
  2397. :from old-state :to new-state)
  2398. Depending on the type, more properties may be present.
  2399. This mechanism is currently implemented for:
  2400. TODO state changes
  2401. ------------------
  2402. :type todo-state-change
  2403. :from previous state (keyword as a string), or nil, or a symbol
  2404. `todo' or `done', to indicate the general type of state.
  2405. :to new state, like in :from")
  2406. (defcustom org-enforce-todo-dependencies nil
  2407. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2408. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2409. be blocked if any prior sibling is not yet done.
  2410. Finally, if the parent is blocked because of ordered siblings of its own,
  2411. the child will also be blocked."
  2412. :set (lambda (var val)
  2413. (set var val)
  2414. (if val
  2415. (add-hook 'org-blocker-hook
  2416. 'org-block-todo-from-children-or-siblings-or-parent)
  2417. (remove-hook 'org-blocker-hook
  2418. 'org-block-todo-from-children-or-siblings-or-parent)))
  2419. :group 'org-todo
  2420. :type 'boolean)
  2421. (defcustom org-enforce-todo-checkbox-dependencies nil
  2422. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2423. When this is nil, checkboxes have no influence on switching TODO states.
  2424. When non-nil, you first need to check off all check boxes before the TODO
  2425. entry can be switched to DONE.
  2426. This variable needs to be set before org.el is loaded, and you need to
  2427. restart Emacs after a change to make the change effective. The only way
  2428. to change is while Emacs is running is through the customize interface."
  2429. :set (lambda (var val)
  2430. (set var val)
  2431. (if val
  2432. (add-hook 'org-blocker-hook
  2433. 'org-block-todo-from-checkboxes)
  2434. (remove-hook 'org-blocker-hook
  2435. 'org-block-todo-from-checkboxes)))
  2436. :group 'org-todo
  2437. :type 'boolean)
  2438. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2439. "Non-nil means inserting a TODO heading is treated as state change.
  2440. So when the command \\[org-insert-todo-heading] is used, state change
  2441. logging will apply if appropriate. When nil, the new TODO item will
  2442. be inserted directly, and no logging will take place."
  2443. :group 'org-todo
  2444. :type 'boolean)
  2445. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2446. "Non-nil means switching TODO states with S-cursor counts as state change.
  2447. This is the default behavior. However, setting this to nil allows a
  2448. convenient way to select a TODO state and bypass any logging associated
  2449. with that."
  2450. :group 'org-todo
  2451. :type 'boolean)
  2452. (defcustom org-todo-state-tags-triggers nil
  2453. "Tag changes that should be triggered by TODO state changes.
  2454. This is a list. Each entry is
  2455. (state-change (tag . flag) .......)
  2456. State-change can be a string with a state, and empty string to indicate the
  2457. state that has no TODO keyword, or it can be one of the symbols `todo'
  2458. or `done', meaning any not-done or done state, respectively."
  2459. :group 'org-todo
  2460. :group 'org-tags
  2461. :type '(repeat
  2462. (cons (choice :tag "When changing to"
  2463. (const :tag "Not-done state" todo)
  2464. (const :tag "Done state" done)
  2465. (string :tag "State"))
  2466. (repeat
  2467. (cons :tag "Tag action"
  2468. (string :tag "Tag")
  2469. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2470. (defcustom org-log-done nil
  2471. "Information to record when a task moves to the DONE state.
  2472. Possible values are:
  2473. nil Don't add anything, just change the keyword
  2474. time Add a time stamp to the task
  2475. note Prompt for a note and add it with template `org-log-note-headings'
  2476. This option can also be set with on a per-file-basis with
  2477. #+STARTUP: nologdone
  2478. #+STARTUP: logdone
  2479. #+STARTUP: lognotedone
  2480. You can have local logging settings for a subtree by setting the LOGGING
  2481. property to one or more of these keywords."
  2482. :group 'org-todo
  2483. :group 'org-progress
  2484. :type '(choice
  2485. (const :tag "No logging" nil)
  2486. (const :tag "Record CLOSED timestamp" time)
  2487. (const :tag "Record CLOSED timestamp with note." note)))
  2488. ;; Normalize old uses of org-log-done.
  2489. (cond
  2490. ((eq org-log-done t) (setq org-log-done 'time))
  2491. ((and (listp org-log-done) (memq 'done org-log-done))
  2492. (setq org-log-done 'note)))
  2493. (defcustom org-log-reschedule nil
  2494. "Information to record when the scheduling date of a tasks is modified.
  2495. Possible values are:
  2496. nil Don't add anything, just change the date
  2497. time Add a time stamp to the task
  2498. note Prompt for a note and add it with template `org-log-note-headings'
  2499. This option can also be set with on a per-file-basis with
  2500. #+STARTUP: nologreschedule
  2501. #+STARTUP: logreschedule
  2502. #+STARTUP: lognotereschedule"
  2503. :group 'org-todo
  2504. :group 'org-progress
  2505. :type '(choice
  2506. (const :tag "No logging" nil)
  2507. (const :tag "Record timestamp" time)
  2508. (const :tag "Record timestamp with note." note)))
  2509. (defcustom org-log-redeadline nil
  2510. "Information to record when the deadline date of a tasks is modified.
  2511. Possible values are:
  2512. nil Don't add anything, just change the date
  2513. time Add a time stamp to the task
  2514. note Prompt for a note and add it with template `org-log-note-headings'
  2515. This option can also be set with on a per-file-basis with
  2516. #+STARTUP: nologredeadline
  2517. #+STARTUP: logredeadline
  2518. #+STARTUP: lognoteredeadline
  2519. You can have local logging settings for a subtree by setting the LOGGING
  2520. property to one or more of these keywords."
  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-note-clock-out nil
  2528. "Non-nil means record a note when clocking out of an item.
  2529. This can also be configured on a per-file basis by adding one of
  2530. the following lines anywhere in the buffer:
  2531. #+STARTUP: lognoteclock-out
  2532. #+STARTUP: nolognoteclock-out"
  2533. :group 'org-todo
  2534. :group 'org-progress
  2535. :type 'boolean)
  2536. (defcustom org-log-done-with-time t
  2537. "Non-nil means the CLOSED time stamp will contain date and time.
  2538. When nil, only the date will be recorded."
  2539. :group 'org-progress
  2540. :type 'boolean)
  2541. (defcustom org-log-note-headings
  2542. '((done . "CLOSING NOTE %t")
  2543. (state . "State %-12s from %-12S %t")
  2544. (note . "Note taken on %t")
  2545. (reschedule . "Rescheduled from %S on %t")
  2546. (delschedule . "Not scheduled, was %S on %t")
  2547. (redeadline . "New deadline from %S on %t")
  2548. (deldeadline . "Removed deadline, was %S on %t")
  2549. (refile . "Refiled on %t")
  2550. (clock-out . ""))
  2551. "Headings for notes added to entries.
  2552. The value is an alist, with the car being a symbol indicating the
  2553. note context, and the cdr is the heading to be used. The heading
  2554. may also be the empty string. The following placeholders can be
  2555. used:
  2556. %t a time stamp.
  2557. %T an active time stamp instead the default inactive one
  2558. %d a short-format time stamp.
  2559. %D an active short-format time stamp.
  2560. %s the new TODO state or time stamp (inactive), in double quotes.
  2561. %S the old TODO state or time stamp (inactive), in double quotes.
  2562. %u the user name.
  2563. %U full user name.
  2564. In fact, it is not a good idea to change the `state' entry,
  2565. because Agenda Log mode depends on the format of these entries."
  2566. :group 'org-todo
  2567. :group 'org-progress
  2568. :type '(list :greedy t
  2569. (cons (const :tag "Heading when closing an item" done) string)
  2570. (cons (const :tag
  2571. "Heading when changing todo state (todo sequence only)"
  2572. state) string)
  2573. (cons (const :tag "Heading when just taking a note" note) string)
  2574. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2575. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2576. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2577. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2578. (cons (const :tag "Heading when refiling" refile) string)
  2579. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2580. (unless (assq 'note org-log-note-headings)
  2581. (push '(note . "%t") org-log-note-headings))
  2582. (defcustom org-log-into-drawer nil
  2583. "Non-nil means insert state change notes and time stamps into a drawer.
  2584. When nil, state changes notes will be inserted after the headline and
  2585. any scheduling and clock lines, but not inside a drawer.
  2586. The value of this variable should be the name of the drawer to use.
  2587. LOGBOOK is proposed as the default drawer for this purpose, you can
  2588. also set this to a string to define the drawer of your choice.
  2589. A value of t is also allowed, representing \"LOGBOOK\".
  2590. A value of t or nil can also be set with on a per-file-basis with
  2591. #+STARTUP: logdrawer
  2592. #+STARTUP: nologdrawer
  2593. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2594. will be ignored.
  2595. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2596. a subtree.
  2597. Do not check directly this variable in a Lisp program. Call
  2598. function `org-log-into-drawer' instead."
  2599. :group 'org-todo
  2600. :group 'org-progress
  2601. :type '(choice
  2602. (const :tag "Not into a drawer" nil)
  2603. (const :tag "LOGBOOK" t)
  2604. (string :tag "Other")))
  2605. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2606. (defun org-log-into-drawer ()
  2607. "Name of the log drawer, as a string, or nil.
  2608. This is the value of `org-log-into-drawer'. However, if the
  2609. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2610. be used instead of the default value."
  2611. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2612. (cond ((equal p "nil") nil)
  2613. ((equal p "t") "LOGBOOK")
  2614. ((stringp p) p)
  2615. (p "LOGBOOK")
  2616. ((stringp org-log-into-drawer) org-log-into-drawer)
  2617. (org-log-into-drawer "LOGBOOK"))))
  2618. (defcustom org-log-state-notes-insert-after-drawers nil
  2619. "Non-nil means insert state change notes after any drawers in entry.
  2620. Only the drawers that *immediately* follow the headline and the
  2621. deadline/scheduled line are skipped.
  2622. When nil, insert notes right after the heading and perhaps the line
  2623. with deadline/scheduling if present.
  2624. This variable will have no effect if `org-log-into-drawer' is
  2625. set."
  2626. :group 'org-todo
  2627. :group 'org-progress
  2628. :type 'boolean)
  2629. (defcustom org-log-states-order-reversed t
  2630. "Non-nil means the latest state note will be directly after heading.
  2631. When nil, the state change notes will be ordered according to time.
  2632. This option can also be set with on a per-file-basis with
  2633. #+STARTUP: logstatesreversed
  2634. #+STARTUP: nologstatesreversed"
  2635. :group 'org-todo
  2636. :group 'org-progress
  2637. :type 'boolean)
  2638. (defcustom org-todo-repeat-to-state nil
  2639. "The TODO state to which a repeater should return the repeating task.
  2640. By default this is the first task in a TODO sequence, or the previous state
  2641. in a TODO_TYP set. But you can specify another task here.
  2642. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2643. :group 'org-todo
  2644. :version "24.1"
  2645. :type '(choice (const :tag "Head of sequence" nil)
  2646. (string :tag "Specific state")))
  2647. (defcustom org-log-repeat 'time
  2648. "Non-nil means record moving through the DONE state when triggering repeat.
  2649. An auto-repeating task is immediately switched back to TODO when
  2650. marked DONE. If you are not logging state changes (by adding \"@\"
  2651. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2652. record a closing note, there will be no record of the task moving
  2653. through DONE. This variable forces taking a note anyway.
  2654. nil Don't force a record
  2655. time Record a time stamp
  2656. note Prompt for a note and add it with template `org-log-note-headings'
  2657. This option can also be set with on a per-file-basis with
  2658. #+STARTUP: nologrepeat
  2659. #+STARTUP: logrepeat
  2660. #+STARTUP: lognoterepeat
  2661. You can have local logging settings for a subtree by setting the LOGGING
  2662. property to one or more of these keywords."
  2663. :group 'org-todo
  2664. :group 'org-progress
  2665. :type '(choice
  2666. (const :tag "Don't force a record" nil)
  2667. (const :tag "Force recording the DONE state" time)
  2668. (const :tag "Force recording a note with the DONE state" note)))
  2669. (defgroup org-priorities nil
  2670. "Priorities in Org-mode."
  2671. :tag "Org Priorities"
  2672. :group 'org-todo)
  2673. (defcustom org-enable-priority-commands t
  2674. "Non-nil means priority commands are active.
  2675. When nil, these commands will be disabled, so that you never accidentally
  2676. set a priority."
  2677. :group 'org-priorities
  2678. :type 'boolean)
  2679. (defcustom org-highest-priority ?A
  2680. "The highest priority of TODO items. A character like ?A, ?B etc.
  2681. Must have a smaller ASCII number than `org-lowest-priority'."
  2682. :group 'org-priorities
  2683. :type 'character)
  2684. (defcustom org-lowest-priority ?C
  2685. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2686. Must have a larger ASCII number than `org-highest-priority'."
  2687. :group 'org-priorities
  2688. :type 'character)
  2689. (defcustom org-default-priority ?B
  2690. "The default priority of TODO items.
  2691. This is the priority an item gets if no explicit priority is given.
  2692. When starting to cycle on an empty priority the first step in the cycle
  2693. depends on `org-priority-start-cycle-with-default'. The resulting first
  2694. step priority must not exceed the range from `org-highest-priority' to
  2695. `org-lowest-priority' which means that `org-default-priority' has to be
  2696. in this range exclusive or inclusive the range boundaries. Else the
  2697. first step refuses to set the default and the second will fall back
  2698. to (depending on the command used) the highest or lowest priority."
  2699. :group 'org-priorities
  2700. :type 'character)
  2701. (defcustom org-priority-start-cycle-with-default t
  2702. "Non-nil means start with default priority when starting to cycle.
  2703. When this is nil, the first step in the cycle will be (depending on the
  2704. command used) one higher or lower than the default priority.
  2705. See also `org-default-priority'."
  2706. :group 'org-priorities
  2707. :type 'boolean)
  2708. (defcustom org-get-priority-function nil
  2709. "Function to extract the priority from a string.
  2710. The string is normally the headline. If this is nil Org computes the
  2711. priority from the priority cookie like [#A] in the headline. It returns
  2712. an integer, increasing by 1000 for each priority level.
  2713. The user can set a different function here, which should take a string
  2714. as an argument and return the numeric priority."
  2715. :group 'org-priorities
  2716. :version "24.1"
  2717. :type '(choice
  2718. (const nil)
  2719. (function)))
  2720. (defgroup org-time nil
  2721. "Options concerning time stamps and deadlines in Org-mode."
  2722. :tag "Org Time"
  2723. :group 'org)
  2724. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2725. "Number of minutes to round time stamps to.
  2726. \\<org-mode-map>\
  2727. These are two values, the first applies when first creating a time stamp.
  2728. The second applies when changing it with the commands `S-up' and `S-down'.
  2729. When changing the time stamp, this means that it will change in steps
  2730. of N minutes, as given by the second value.
  2731. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2732. numbers should be factors of 60, so for example 5, 10, 15.
  2733. When this is larger than 1, you can still force an exact time stamp by using
  2734. a double prefix argument to a time stamp command like \
  2735. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2736. and by using a prefix arg to `S-up/down' to specify the exact number
  2737. of minutes to shift."
  2738. :group 'org-time
  2739. :get (lambda (var) ; Make sure both elements are there
  2740. (if (integerp (default-value var))
  2741. (list (default-value var) 5)
  2742. (default-value var)))
  2743. :type '(list
  2744. (integer :tag "when inserting times")
  2745. (integer :tag "when modifying times")))
  2746. ;; Normalize old customizations of this variable.
  2747. (when (integerp org-time-stamp-rounding-minutes)
  2748. (setq org-time-stamp-rounding-minutes
  2749. (list org-time-stamp-rounding-minutes
  2750. org-time-stamp-rounding-minutes)))
  2751. (defcustom org-display-custom-times nil
  2752. "Non-nil means overlay custom formats over all time stamps.
  2753. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2754. To turn this on on a per-file basis, insert anywhere in the file:
  2755. #+STARTUP: customtime"
  2756. :group 'org-time
  2757. :set 'set-default
  2758. :type 'sexp)
  2759. (make-variable-buffer-local 'org-display-custom-times)
  2760. (defcustom org-time-stamp-custom-formats
  2761. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2762. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2763. These are overlaid over the default ISO format if the variable
  2764. `org-display-custom-times' is set. Time like %H:%M should be at the
  2765. end of the second format. The custom formats are also honored by export
  2766. commands, if custom time display is turned on at the time of export."
  2767. :group 'org-time
  2768. :type 'sexp)
  2769. (defun org-time-stamp-format (&optional long inactive)
  2770. "Get the right format for a time string."
  2771. (let ((f (if long (cdr org-time-stamp-formats)
  2772. (car org-time-stamp-formats))))
  2773. (if inactive
  2774. (concat "[" (substring f 1 -1) "]")
  2775. f)))
  2776. (defcustom org-time-clocksum-format
  2777. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2778. "The format string used when creating CLOCKSUM lines.
  2779. This is also used when Org mode generates a time duration.
  2780. The value can be a single format string containing two
  2781. %-sequences, which will be filled with the number of hours and
  2782. minutes in that order.
  2783. Alternatively, the value can be a plist associating any of the
  2784. keys :years, :months, :weeks, :days, :hours or :minutes with
  2785. format strings. The time duration is formatted using only the
  2786. time components that are needed and concatenating the results.
  2787. If a time unit in absent, it falls back to the next smallest
  2788. unit.
  2789. The keys :require-years, :require-months, :require-days,
  2790. :require-weeks, :require-hours, :require-minutes are also
  2791. meaningful. A non-nil value for these keys indicates that the
  2792. corresponding time component should always be included, even if
  2793. its value is 0.
  2794. For example,
  2795. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2796. :require-minutes t)
  2797. means durations longer than a day will be expressed in days,
  2798. hours and minutes, and durations less than a day will always be
  2799. expressed in hours and minutes (even for durations less than an
  2800. hour).
  2801. The value
  2802. (:days \"%dd\" :minutes \"%dm\")
  2803. means durations longer than a day will be expressed in days and
  2804. minutes, and durations less than a day will be expressed entirely
  2805. in minutes (even for durations longer than an hour)."
  2806. :group 'org-time
  2807. :group 'org-clock
  2808. :version "24.4"
  2809. :package-version '(Org . "8.0")
  2810. :type '(choice (string :tag "Format string")
  2811. (set :tag "Plist"
  2812. (group :inline t (const :tag "Years" :years)
  2813. (string :tag "Format string"))
  2814. (group :inline t
  2815. (const :tag "Always show years" :require-years)
  2816. (const t))
  2817. (group :inline t (const :tag "Months" :months)
  2818. (string :tag "Format string"))
  2819. (group :inline t
  2820. (const :tag "Always show months" :require-months)
  2821. (const t))
  2822. (group :inline t (const :tag "Weeks" :weeks)
  2823. (string :tag "Format string"))
  2824. (group :inline t
  2825. (const :tag "Always show weeks" :require-weeks)
  2826. (const t))
  2827. (group :inline t (const :tag "Days" :days)
  2828. (string :tag "Format string"))
  2829. (group :inline t
  2830. (const :tag "Always show days" :require-days)
  2831. (const t))
  2832. (group :inline t (const :tag "Hours" :hours)
  2833. (string :tag "Format string"))
  2834. (group :inline t
  2835. (const :tag "Always show hours" :require-hours)
  2836. (const t))
  2837. (group :inline t (const :tag "Minutes" :minutes)
  2838. (string :tag "Format string"))
  2839. (group :inline t
  2840. (const :tag "Always show minutes" :require-minutes)
  2841. (const t)))))
  2842. (defcustom org-time-clocksum-use-fractional nil
  2843. "When non-nil, \\[org-clock-display] uses fractional times.
  2844. See `org-time-clocksum-format' for more on time clock formats."
  2845. :group 'org-time
  2846. :group 'org-clock
  2847. :version "24.3"
  2848. :type 'boolean)
  2849. (defcustom org-time-clocksum-use-effort-durations nil
  2850. "When non-nil, \\[org-clock-display] uses effort durations.
  2851. E.g. by default, one day is considered to be a 8 hours effort,
  2852. so a task that has been clocked for 16 hours will be displayed
  2853. as during 2 days in the clock display or in the clocktable.
  2854. See `org-effort-durations' on how to set effort durations
  2855. and `org-time-clocksum-format' for more on time clock formats."
  2856. :group 'org-time
  2857. :group 'org-clock
  2858. :version "24.4"
  2859. :package-version '(Org . "8.0")
  2860. :type 'boolean)
  2861. (defcustom org-time-clocksum-fractional-format "%.2f"
  2862. "The format string used when creating CLOCKSUM lines,
  2863. or when Org mode generates a time duration, if
  2864. `org-time-clocksum-use-fractional' is enabled.
  2865. The value can be a single format string containing one
  2866. %-sequence, which will be filled with the number of hours as
  2867. a float.
  2868. Alternatively, the value can be a plist associating any of the
  2869. keys :years, :months, :weeks, :days, :hours or :minutes with
  2870. a format string. The time duration is formatted using the
  2871. largest time unit which gives a non-zero integer part. If all
  2872. specified formats have zero integer part, the smallest time unit
  2873. is used."
  2874. :group 'org-time
  2875. :type '(choice (string :tag "Format string")
  2876. (set (group :inline t (const :tag "Years" :years)
  2877. (string :tag "Format string"))
  2878. (group :inline t (const :tag "Months" :months)
  2879. (string :tag "Format string"))
  2880. (group :inline t (const :tag "Weeks" :weeks)
  2881. (string :tag "Format string"))
  2882. (group :inline t (const :tag "Days" :days)
  2883. (string :tag "Format string"))
  2884. (group :inline t (const :tag "Hours" :hours)
  2885. (string :tag "Format string"))
  2886. (group :inline t (const :tag "Minutes" :minutes)
  2887. (string :tag "Format string")))))
  2888. (defcustom org-deadline-warning-days 14
  2889. "Number of days before expiration during which a deadline becomes active.
  2890. This variable governs the display in sparse trees and in the agenda.
  2891. When 0 or negative, it means use this number (the absolute value of it)
  2892. even if a deadline has a different individual lead time specified.
  2893. Custom commands can set this variable in the options section."
  2894. :group 'org-time
  2895. :group 'org-agenda-daily/weekly
  2896. :type 'integer)
  2897. (defcustom org-scheduled-delay-days 0
  2898. "Number of days before a scheduled item becomes active.
  2899. This variable governs the display in sparse trees and in the agenda.
  2900. The default value (i.e. 0) means: don't delay scheduled item.
  2901. When negative, it means use this number (the absolute value of it)
  2902. even if a scheduled item has a different individual delay time
  2903. specified.
  2904. Custom commands can set this variable in the options section."
  2905. :group 'org-time
  2906. :group 'org-agenda-daily/weekly
  2907. :version "24.4"
  2908. :package-version '(Org . "8.0")
  2909. :type 'integer)
  2910. (defcustom org-read-date-prefer-future t
  2911. "Non-nil means assume future for incomplete date input from user.
  2912. This affects the following situations:
  2913. 1. The user gives a month but not a year.
  2914. For example, if it is April and you enter \"feb 2\", this will be read
  2915. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2916. 2. The user gives a day, but no month.
  2917. For example, if today is the 15th, and you enter \"3\", Org will read
  2918. this as the third of *next* month. However, if you enter \"17\",
  2919. it will be considered as *this* month.
  2920. If you set this variable to the symbol `time', then also the following
  2921. will work:
  2922. 3. If the user gives a time.
  2923. If the time is before now, it will be interpreted as tomorrow.
  2924. Currently none of this works for ISO week specifications.
  2925. When this option is nil, the current day, month and year will always be
  2926. used as defaults.
  2927. See also `org-agenda-jump-prefer-future'."
  2928. :group 'org-time
  2929. :type '(choice
  2930. (const :tag "Never" nil)
  2931. (const :tag "Check month and day" t)
  2932. (const :tag "Check month, day, and time" time)))
  2933. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2934. "Should the agenda jump command prefer the future for incomplete dates?
  2935. The default is to do the same as configured in `org-read-date-prefer-future'.
  2936. But you can also set a deviating value here.
  2937. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2938. :group 'org-agenda
  2939. :group 'org-time
  2940. :version "24.1"
  2941. :type '(choice
  2942. (const :tag "Use org-read-date-prefer-future"
  2943. org-read-date-prefer-future)
  2944. (const :tag "Never" nil)
  2945. (const :tag "Always" t)))
  2946. (defcustom org-read-date-force-compatible-dates t
  2947. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2948. Depending on the system Emacs is running on, certain dates cannot
  2949. be represented with the type used internally to represent time.
  2950. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2951. correctly. Some systems allow for earlier dates, some for later,
  2952. some for both. One way to find out it to insert any date into an
  2953. Org buffer, putting the cursor on the year and hitting S-up and
  2954. S-down to test the range.
  2955. When this variable is set to t, the date/time prompt will not let
  2956. you specify dates outside the 1970-2037 range, so it is certain that
  2957. these dates will work in whatever version of Emacs you are
  2958. running, and also that you can move a file from one Emacs implementation
  2959. to another. WHenever Org is forcing the year for you, it will display
  2960. a message and beep.
  2961. When this variable is nil, Org will check if the date is
  2962. representable in the specific Emacs implementation you are using.
  2963. If not, it will force a year, usually the current year, and beep
  2964. to remind you. Currently this setting is not recommended because
  2965. the likelihood that you will open your Org files in an Emacs that
  2966. has limited date range is not negligible.
  2967. A workaround for this problem is to use diary sexp dates for time
  2968. stamps outside of this range."
  2969. :group 'org-time
  2970. :version "24.1"
  2971. :type 'boolean)
  2972. (defcustom org-read-date-display-live t
  2973. "Non-nil means display current interpretation of date prompt live.
  2974. This display will be in an overlay, in the minibuffer."
  2975. :group 'org-time
  2976. :type 'boolean)
  2977. (defcustom org-read-date-popup-calendar t
  2978. "Non-nil means pop up a calendar when prompting for a date.
  2979. In the calendar, the date can be selected with mouse-1. However, the
  2980. minibuffer will also be active, and you can simply enter the date as well.
  2981. When nil, only the minibuffer will be available."
  2982. :group 'org-time
  2983. :type 'boolean)
  2984. (defvaralias 'org-popup-calendar-for-date-prompt
  2985. 'org-read-date-popup-calendar)
  2986. (defcustom org-extend-today-until 0
  2987. "The hour when your day really ends. Must be an integer.
  2988. This has influence for the following applications:
  2989. - When switching the agenda to \"today\". It it is still earlier than
  2990. the time given here, the day recognized as TODAY is actually yesterday.
  2991. - When a date is read from the user and it is still before the time given
  2992. here, the current date and time will be assumed to be yesterday, 23:59.
  2993. Also, timestamps inserted in capture templates follow this rule.
  2994. IMPORTANT: This is a feature whose implementation is and likely will
  2995. remain incomplete. Really, it is only here because past midnight seems to
  2996. be the favorite working time of John Wiegley :-)"
  2997. :group 'org-time
  2998. :type 'integer)
  2999. (defcustom org-use-effective-time nil
  3000. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3001. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3002. \"effective time\" of any timestamps between midnight and 8am will be
  3003. 23:59 of the previous day."
  3004. :group 'org-time
  3005. :version "24.1"
  3006. :type 'boolean)
  3007. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3008. "When non-nil, use the last clock out time for `org-todo'.
  3009. Note that this option has precedence over the combined use of
  3010. `org-use-effective-time' and `org-extend-today-until'."
  3011. :group 'org-time
  3012. :version "24.4"
  3013. :package-version '(Org . "8.0")
  3014. :type 'boolean)
  3015. (defcustom org-edit-timestamp-down-means-later nil
  3016. "Non-nil means S-down will increase the time in a time stamp.
  3017. When nil, S-up will increase."
  3018. :group 'org-time
  3019. :type 'boolean)
  3020. (defcustom org-calendar-follow-timestamp-change t
  3021. "Non-nil means make the calendar window follow timestamp changes.
  3022. When a timestamp is modified and the calendar window is visible, it will be
  3023. moved to the new date."
  3024. :group 'org-time
  3025. :type 'boolean)
  3026. (defgroup org-tags nil
  3027. "Options concerning tags in Org-mode."
  3028. :tag "Org Tags"
  3029. :group 'org)
  3030. (defcustom org-tag-alist nil
  3031. "Default tags available in Org files.
  3032. The value of this variable is an alist. Associations either:
  3033. (TAG)
  3034. (TAG . SELECT)
  3035. (SPECIAL)
  3036. where TAG is a tag as a string, SELECT is a character, used to
  3037. select that tag through the fast tag selection interface, and
  3038. SPECIAL is one of the following keywords: `:startgroup',
  3039. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3040. `:newline'. These keywords are used to define a hierarchy of
  3041. tags. See manual for details.
  3042. When this variable is nil, Org mode bases tag input on what is
  3043. already in the buffer. The value can be overridden locally by
  3044. using a TAGS keyword, e.g.,
  3045. #+TAGS: tag1 tag2
  3046. See also `org-tag-persistent-alist' to sidestep this behavior."
  3047. :group 'org-tags
  3048. :type '(repeat
  3049. (choice
  3050. (cons (string :tag "Tag name")
  3051. (character :tag "Access char"))
  3052. (const :tag "Start radio group" (:startgroup))
  3053. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3054. (const :tag "Group tags delimiter" (:grouptags))
  3055. (const :tag "End radio group" (:endgroup))
  3056. (const :tag "End tag group, non distinct" (:endgrouptag))
  3057. (const :tag "New line" (:newline)))))
  3058. (defcustom org-tag-persistent-alist nil
  3059. "Tags always available in Org files.
  3060. The value of this variable is an alist. Associations either:
  3061. (TAG)
  3062. (TAG . SELECT)
  3063. (SPECIAL)
  3064. where TAG is a tag as a string, SELECT is a character, used to
  3065. select that tag through the fast tag selection interface, and
  3066. SPECIAL is one of the following keywords: `:startgroup',
  3067. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3068. `:newline'. These keywords are used to define a hierarchy of
  3069. tags. See manual for details.
  3070. Unlike to `org-tag-alist', tags defined in this variable do not
  3071. depend on a local TAGS keyword. Instead, to disable these tags
  3072. on a per-file basis, insert anywhere in the file:
  3073. #+STARTUP: noptag"
  3074. :group 'org-tags
  3075. :type '(repeat
  3076. (choice
  3077. (cons (string :tag "Tag name")
  3078. (character :tag "Access char"))
  3079. (const :tag "Start radio group" (:startgroup))
  3080. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3081. (const :tag "Group tags delimiter" (:grouptags))
  3082. (const :tag "End radio group" (:endgroup))
  3083. (const :tag "End tag group, non distinct" (:endgrouptag))
  3084. (const :tag "New line" (:newline)))))
  3085. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3086. "If non-nil, always offer completion for all tags of all agenda files.
  3087. Instead of customizing this variable directly, you might want to
  3088. set it locally for capture buffers, because there no list of
  3089. tags in that file can be created dynamically (there are none).
  3090. (add-hook \\='org-capture-mode-hook
  3091. (lambda ()
  3092. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3093. :group 'org-tags
  3094. :version "24.1"
  3095. :type 'boolean)
  3096. (defvar org-file-tags nil
  3097. "List of tags that can be inherited by all entries in the file.
  3098. The tags will be inherited if the variable `org-use-tag-inheritance'
  3099. says they should be.
  3100. This variable is populated from #+FILETAGS lines.")
  3101. (defcustom org-use-fast-tag-selection 'auto
  3102. "Non-nil means use fast tag selection scheme.
  3103. This is a special interface to select and deselect tags with single keys.
  3104. When nil, fast selection is never used.
  3105. When the symbol `auto', fast selection is used if and only if selection
  3106. characters for tags have been configured, either through the variable
  3107. `org-tag-alist' or through a #+TAGS line in the buffer.
  3108. When t, fast selection is always used and selection keys are assigned
  3109. automatically if necessary."
  3110. :group 'org-tags
  3111. :type '(choice
  3112. (const :tag "Always" t)
  3113. (const :tag "Never" nil)
  3114. (const :tag "When selection characters are configured" auto)))
  3115. (defcustom org-fast-tag-selection-single-key nil
  3116. "Non-nil means fast tag selection exits after first change.
  3117. When nil, you have to press RET to exit it.
  3118. During fast tag selection, you can toggle this flag with `C-c'.
  3119. This variable can also have the value `expert'. In this case, the window
  3120. displaying the tags menu is not even shown, until you press C-c again."
  3121. :group 'org-tags
  3122. :type '(choice
  3123. (const :tag "No" nil)
  3124. (const :tag "Yes" t)
  3125. (const :tag "Expert" expert)))
  3126. (defvar org-fast-tag-selection-include-todo nil
  3127. "Non-nil means fast tags selection interface will also offer TODO states.
  3128. This is an undocumented feature, you should not rely on it.")
  3129. (defcustom org-tags-column -77
  3130. "The column to which tags should be indented in a headline.
  3131. If this number is positive, it specifies the column. If it is negative,
  3132. it means that the tags should be flushright to that column. For example,
  3133. -80 works well for a normal 80 character screen.
  3134. When 0, place tags directly after headline text, with only one space in
  3135. between."
  3136. :group 'org-tags
  3137. :type 'integer)
  3138. (defcustom org-auto-align-tags t
  3139. "Non-nil keeps tags aligned when modifying headlines.
  3140. Some operations (i.e. demoting) change the length of a headline and
  3141. therefore shift the tags around. With this option turned on, after
  3142. each such operation the tags are again aligned to `org-tags-column'."
  3143. :group 'org-tags
  3144. :type 'boolean)
  3145. (defcustom org-use-tag-inheritance t
  3146. "Non-nil means tags in levels apply also for sublevels.
  3147. When nil, only the tags directly given in a specific line apply there.
  3148. This may also be a list of tags that should be inherited, or a regexp that
  3149. matches tags that should be inherited. Additional control is possible
  3150. with the variable `org-tags-exclude-from-inheritance' which gives an
  3151. explicit list of tags to be excluded from inheritance, even if the value of
  3152. `org-use-tag-inheritance' would select it for inheritance.
  3153. If this option is t, a match early-on in a tree can lead to a large
  3154. number of matches in the subtree when constructing the agenda or creating
  3155. a sparse tree. If you only want to see the first match in a tree during
  3156. a search, check out the variable `org-tags-match-list-sublevels'."
  3157. :group 'org-tags
  3158. :type '(choice
  3159. (const :tag "Not" nil)
  3160. (const :tag "Always" t)
  3161. (repeat :tag "Specific tags" (string :tag "Tag"))
  3162. (regexp :tag "Tags matched by regexp")))
  3163. (defcustom org-tags-exclude-from-inheritance nil
  3164. "List of tags that should never be inherited.
  3165. This is a way to exclude a few tags from inheritance. For way to do
  3166. the opposite, to actively allow inheritance for selected tags,
  3167. see the variable `org-use-tag-inheritance'."
  3168. :group 'org-tags
  3169. :type '(repeat (string :tag "Tag")))
  3170. (defun org-tag-inherit-p (tag)
  3171. "Check if TAG is one that should be inherited."
  3172. (cond
  3173. ((member tag org-tags-exclude-from-inheritance) nil)
  3174. ((eq org-use-tag-inheritance t) t)
  3175. ((not org-use-tag-inheritance) nil)
  3176. ((stringp org-use-tag-inheritance)
  3177. (string-match org-use-tag-inheritance tag))
  3178. ((listp org-use-tag-inheritance)
  3179. (member tag org-use-tag-inheritance))
  3180. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3181. (defcustom org-tags-match-list-sublevels t
  3182. "Non-nil means list also sublevels of headlines matching a search.
  3183. This variable applies to tags/property searches, and also to stuck
  3184. projects because this search is based on a tags match as well.
  3185. When set to the symbol `indented', sublevels are indented with
  3186. leading dots.
  3187. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3188. the sublevels of a headline matching a tag search often also match
  3189. the same search. Listing all of them can create very long lists.
  3190. Setting this variable to nil causes subtrees of a match to be skipped.
  3191. This variable is semi-obsolete and probably should always be true. It
  3192. is better to limit inheritance to certain tags using the variables
  3193. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3194. :group 'org-tags
  3195. :type '(choice
  3196. (const :tag "No, don't list them" nil)
  3197. (const :tag "Yes, do list them" t)
  3198. (const :tag "List them, indented with leading dots" indented)))
  3199. (defcustom org-tags-sort-function nil
  3200. "When set, tags are sorted using this function as a comparator."
  3201. :group 'org-tags
  3202. :type '(choice
  3203. (const :tag "No sorting" nil)
  3204. (const :tag "Alphabetical" string<)
  3205. (const :tag "Reverse alphabetical" string>)
  3206. (function :tag "Custom function" nil)))
  3207. (defvar org-tags-history nil
  3208. "History of minibuffer reads for tags.")
  3209. (defvar org-last-tags-completion-table nil
  3210. "The last used completion table for tags.")
  3211. (defvar org-after-tags-change-hook nil
  3212. "Hook that is run after the tags in a line have changed.")
  3213. (defgroup org-properties nil
  3214. "Options concerning properties in Org-mode."
  3215. :tag "Org Properties"
  3216. :group 'org)
  3217. (defcustom org-property-format "%-10s %s"
  3218. "How property key/value pairs should be formatted by `indent-line'.
  3219. When `indent-line' hits a property definition, it will format the line
  3220. according to this format, mainly to make sure that the values are
  3221. lined-up with respect to each other."
  3222. :group 'org-properties
  3223. :type 'string)
  3224. (defcustom org-properties-postprocess-alist nil
  3225. "Alist of properties and functions to adjust inserted values.
  3226. Elements of this alist must be of the form
  3227. ([string] [function])
  3228. where [string] must be a property name and [function] must be a
  3229. lambda expression: this lambda expression must take one argument,
  3230. the value to adjust, and return the new value as a string.
  3231. For example, this element will allow the property \"Remaining\"
  3232. to be updated wrt the relation between the \"Effort\" property
  3233. and the clock summary:
  3234. ((\"Remaining\" (lambda(value)
  3235. (let ((clocksum (org-clock-sum-current-item))
  3236. (effort (org-duration-string-to-minutes
  3237. (org-entry-get (point) \"Effort\"))))
  3238. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3239. :group 'org-properties
  3240. :version "24.1"
  3241. :type '(alist :key-type (string :tag "Property")
  3242. :value-type (function :tag "Function")))
  3243. (defcustom org-use-property-inheritance nil
  3244. "Non-nil means properties apply also for sublevels.
  3245. This setting is chiefly used during property searches. Turning it on can
  3246. cause significant overhead when doing a search, which is why it is not
  3247. on by default.
  3248. When nil, only the properties directly given in the current entry count.
  3249. When t, every property is inherited. The value may also be a list of
  3250. properties that should have inheritance, or a regular expression matching
  3251. properties that should be inherited.
  3252. However, note that some special properties use inheritance under special
  3253. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3254. and the properties ending in \"_ALL\" when they are used as descriptor
  3255. for valid values of a property.
  3256. Note for programmers:
  3257. When querying an entry with `org-entry-get', you can control if inheritance
  3258. should be used. By default, `org-entry-get' looks only at the local
  3259. properties. You can request inheritance by setting the inherit argument
  3260. to t (to force inheritance) or to `selective' (to respect the setting
  3261. in this variable)."
  3262. :group 'org-properties
  3263. :type '(choice
  3264. (const :tag "Not" nil)
  3265. (const :tag "Always" t)
  3266. (repeat :tag "Specific properties" (string :tag "Property"))
  3267. (regexp :tag "Properties matched by regexp")))
  3268. (defun org-property-inherit-p (property)
  3269. "Check if PROPERTY is one that should be inherited."
  3270. (cond
  3271. ((eq org-use-property-inheritance t) t)
  3272. ((not org-use-property-inheritance) nil)
  3273. ((stringp org-use-property-inheritance)
  3274. (string-match org-use-property-inheritance property))
  3275. ((listp org-use-property-inheritance)
  3276. (member property org-use-property-inheritance))
  3277. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3278. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3279. "The default column format, if no other format has been defined.
  3280. This variable can be set on the per-file basis by inserting a line
  3281. #+COLUMNS: %25ITEM ....."
  3282. :group 'org-properties
  3283. :type 'string)
  3284. (defcustom org-columns-ellipses ".."
  3285. "The ellipses to be used when a field in column view is truncated.
  3286. When this is the empty string, as many characters as possible are shown,
  3287. but then there will be no visual indication that the field has been truncated.
  3288. When this is a string of length N, the last N characters of a truncated
  3289. field are replaced by this string. If the column is narrower than the
  3290. ellipses string, only part of the ellipses string will be shown."
  3291. :group 'org-properties
  3292. :type 'string)
  3293. (defconst org-global-properties-fixed
  3294. '(("VISIBILITY_ALL" . "folded children content all")
  3295. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3296. "List of property/value pairs that can be inherited by any entry.
  3297. These are fixed values, for the preset properties. The user variable
  3298. that can be used to add to this list is `org-global-properties'.
  3299. The entries in this list are cons cells where the car is a property
  3300. name and cdr is a string with the value. If the value represents
  3301. multiple items like an \"_ALL\" property, separate the items by
  3302. spaces.")
  3303. (defcustom org-global-properties nil
  3304. "List of property/value pairs that can be inherited by any entry.
  3305. This list will be combined with the constant `org-global-properties-fixed'.
  3306. The entries in this list are cons cells where the car is a property
  3307. name and cdr is a string with the value.
  3308. You can set buffer-local values for the same purpose in the variable
  3309. `org-file-properties' this by adding lines like
  3310. #+PROPERTY: NAME VALUE"
  3311. :group 'org-properties
  3312. :type '(repeat
  3313. (cons (string :tag "Property")
  3314. (string :tag "Value"))))
  3315. (defvar-local org-file-properties nil
  3316. "List of property/value pairs that can be inherited by any entry.
  3317. Valid for the current buffer.
  3318. This variable is populated from #+PROPERTY lines.")
  3319. (defgroup org-agenda nil
  3320. "Options concerning agenda views in Org-mode."
  3321. :tag "Org Agenda"
  3322. :group 'org)
  3323. (defvar-local org-category nil
  3324. "Variable used by org files to set a category for agenda display.
  3325. Such files should use a file variable to set it, for example
  3326. # -*- mode: org; org-category: \"ELisp\"
  3327. or contain a special line
  3328. #+CATEGORY: ELisp
  3329. If the file does not specify a category, then file's base name
  3330. is used instead.")
  3331. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3332. (defcustom org-agenda-files nil
  3333. "The files to be used for agenda display.
  3334. Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
  3335. \\[org-remove-file]. You can also use customize to edit the list.
  3336. If an entry is a directory, all files in that directory that are matched by
  3337. `org-agenda-file-regexp' will be part of the file list.
  3338. If the value of the variable is not a list but a single file name, then
  3339. the list of agenda files is actually stored and maintained in that file, one
  3340. agenda file per line. In this file paths can be given relative to
  3341. `org-directory'. Tilde expansion and environment variable substitution
  3342. are also made."
  3343. :group 'org-agenda
  3344. :type '(choice
  3345. (repeat :tag "List of files and directories" file)
  3346. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3347. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3348. "Regular expression to match files for `org-agenda-files'.
  3349. If any element in the list in that variable contains a directory instead
  3350. of a normal file, all files in that directory that are matched by this
  3351. regular expression will be included."
  3352. :group 'org-agenda
  3353. :type 'regexp)
  3354. (defcustom org-agenda-text-search-extra-files nil
  3355. "List of extra files to be searched by text search commands.
  3356. These files will be searched in addition to the agenda files by the
  3357. commands `org-search-view' (`\\[org-agenda] s') \
  3358. and `org-occur-in-agenda-files'.
  3359. Note that these files will only be searched for text search commands,
  3360. not for the other agenda views like todo lists, tag searches or the weekly
  3361. agenda. This variable is intended to list notes and possibly archive files
  3362. that should also be searched by these two commands.
  3363. In fact, if the first element in the list is the symbol `agenda-archives',
  3364. then all archive files of all agenda files will be added to the search
  3365. scope."
  3366. :group 'org-agenda
  3367. :type '(set :greedy t
  3368. (const :tag "Agenda Archives" agenda-archives)
  3369. (repeat :inline t (file))))
  3370. (defvaralias 'org-agenda-multi-occur-extra-files
  3371. 'org-agenda-text-search-extra-files)
  3372. (defcustom org-agenda-skip-unavailable-files nil
  3373. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3374. A nil value means to remove them, after a query, from the list."
  3375. :group 'org-agenda
  3376. :type 'boolean)
  3377. (defcustom org-calendar-to-agenda-key [?c]
  3378. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3379. The command `org-calendar-goto-agenda' will be bound to this key. The
  3380. default is the character `c' because then `c' can be used to switch back and
  3381. forth between agenda and calendar."
  3382. :group 'org-agenda
  3383. :type 'sexp)
  3384. (defcustom org-calendar-insert-diary-entry-key [?i]
  3385. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3386. This option is irrelevant until `org-agenda-diary-file' has been configured
  3387. to point to an Org file. When that is the case, the command
  3388. `org-agenda-diary-entry' will be bound to the key given here, by default
  3389. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3390. if you want to continue doing this, you need to change this to a different
  3391. key."
  3392. :group 'org-agenda
  3393. :type 'sexp)
  3394. (defcustom org-agenda-diary-file 'diary-file
  3395. "File to which to add new entries with the `i' key in agenda and calendar.
  3396. When this is the symbol `diary-file', the functionality in the Emacs
  3397. calendar will be used to add entries to the `diary-file'. But when this
  3398. points to a file, `org-agenda-diary-entry' will be used instead."
  3399. :group 'org-agenda
  3400. :type '(choice
  3401. (const :tag "The standard Emacs diary file" diary-file)
  3402. (file :tag "Special Org file diary entries")))
  3403. (eval-after-load "calendar"
  3404. '(progn
  3405. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3406. 'org-calendar-goto-agenda)
  3407. (add-hook 'calendar-mode-hook
  3408. (lambda ()
  3409. (unless (eq org-agenda-diary-file 'diary-file)
  3410. (define-key calendar-mode-map
  3411. org-calendar-insert-diary-entry-key
  3412. 'org-agenda-diary-entry))))))
  3413. (defgroup org-latex nil
  3414. "Options for embedding LaTeX code into Org-mode."
  3415. :tag "Org LaTeX"
  3416. :group 'org)
  3417. (defcustom org-format-latex-options
  3418. '(:foreground default :background default :scale 1.0
  3419. :html-foreground "Black" :html-background "Transparent"
  3420. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3421. "Options for creating images from LaTeX fragments.
  3422. This is a property list with the following properties:
  3423. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3424. `default' means use the foreground of the default face.
  3425. `auto' means use the foreground from the text face.
  3426. :background the background color, or \"Transparent\".
  3427. `default' means use the background of the default face.
  3428. `auto' means use the background from the text face.
  3429. :scale a scaling factor for the size of the images, to get more pixels
  3430. :html-foreground, :html-background, :html-scale
  3431. the same numbers for HTML export.
  3432. :matchers a list indicating which matchers should be used to
  3433. find LaTeX fragments. Valid members of this list are:
  3434. \"begin\" find environments
  3435. \"$1\" find single characters surrounded by $.$
  3436. \"$\" find math expressions surrounded by $...$
  3437. \"$$\" find math expressions surrounded by $$....$$
  3438. \"\\(\" find math expressions surrounded by \\(...\\)
  3439. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3440. :group 'org-latex
  3441. :type 'plist)
  3442. (defcustom org-format-latex-signal-error t
  3443. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3444. When nil, just push out a message."
  3445. :group 'org-latex
  3446. :version "24.1"
  3447. :type 'boolean)
  3448. (defcustom org-latex-to-mathml-jar-file nil
  3449. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3450. Use this to specify additional executable file say a jar file.
  3451. When using MathToWeb as the converter, specify the full-path to
  3452. your mathtoweb.jar file."
  3453. :group 'org-latex
  3454. :version "24.1"
  3455. :type '(choice
  3456. (const :tag "None" nil)
  3457. (file :tag "JAR file" :must-match t)))
  3458. (defcustom org-latex-to-mathml-convert-command nil
  3459. "Command to convert LaTeX fragments to MathML.
  3460. Replace format-specifiers in the command as noted below and use
  3461. `shell-command' to convert LaTeX to MathML.
  3462. %j: Executable file in fully expanded form as specified by
  3463. `org-latex-to-mathml-jar-file'.
  3464. %I: Input LaTeX file in fully expanded form.
  3465. %i: The latex fragment to be converted.
  3466. %o: Output MathML file.
  3467. This command is used by `org-create-math-formula'.
  3468. When using MathToWeb as the converter, set this option to
  3469. \"java -jar %j -unicode -force -df %o %I\".
  3470. When using LaTeXML set this option to
  3471. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3472. :group 'org-latex
  3473. :version "24.1"
  3474. :type '(choice
  3475. (const :tag "None" nil)
  3476. (string :tag "\nShell command")))
  3477. (defcustom org-preview-latex-default-process 'dvipng
  3478. "The default process to convert LaTeX fragments to image files.
  3479. All available processes and theirs documents can be found in
  3480. `org-preview-latex-process-alist', which see."
  3481. :group 'org-latex
  3482. :version "25.2"
  3483. :package-version '(Org . "9.0")
  3484. :type 'symbol)
  3485. (defcustom org-preview-latex-process-alist
  3486. '((dvipng
  3487. :programs ("latex" "dvipng" "gs")
  3488. :description "dvi > png"
  3489. :message "you need to install the programs: latex, dvipng and ghostscript."
  3490. :image-input-type "dvi"
  3491. :image-output-type "png"
  3492. :image-size-adjust (1.0 . 1.0)
  3493. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3494. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
  3495. (dvisvgm
  3496. :programs ("latex" "dvisvgm" "gs")
  3497. :description "dvi > svg"
  3498. :message "you need to install the programs: latex, dvisvgm and ghostscript."
  3499. :use-xcolor t
  3500. :image-input-type "dvi"
  3501. :image-output-type "svg"
  3502. :image-size-adjust (1.7 . 1.5)
  3503. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3504. :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
  3505. (imagemagick
  3506. :programs ("latex" "convert" "gs")
  3507. :description "pdf > png"
  3508. :message
  3509. "you need to install the programs: latex, imagemagick and ghostscript."
  3510. :use-xcolor t
  3511. :image-input-type "pdf"
  3512. :image-output-type "png"
  3513. :image-size-adjust (1.0 . 1.0)
  3514. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3515. :image-converter
  3516. ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
  3517. "Definitions of external processes for LaTeX previewing.
  3518. Org mode can use some external commands to generate TeX snippet's images for
  3519. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3520. `org-create-formula-image' how to call them.
  3521. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3522. PROPERTIES accepts the following attributes:
  3523. :programs list of strings, required programs.
  3524. :description string, describe the process.
  3525. :message string, message it when required programs cannot be found.
  3526. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3527. :image-output-type string, output file type of image converter (e.g., \"png\").
  3528. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3529. deal with background and foreground color of image.
  3530. Otherwise, dvipng style background and foregroud color
  3531. format are generated. You may then refer to them in
  3532. command options with \"%F\" and \"%B\".
  3533. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3534. image size showed in buffer and the cdr element is for
  3535. HTML file. This option is only useful for process
  3536. developers, users should use variable
  3537. `org-format-latex-options' instead.
  3538. :post-clean list of strings, files matched are to be cleaned up once
  3539. the image is generated. When nil, the files with \".dvi\",
  3540. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3541. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3542. be cleaned up.
  3543. :latex-header list of strings, the LaTeX header of the snippet file.
  3544. When nil, the fallback value is used instead, which is
  3545. controlled by `org-format-latex-header',
  3546. `org-latex-default-packages-alist' and
  3547. `org-latex-packages-alist', which see.
  3548. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3549. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3550. replaced with values defined below.
  3551. :image-converter list of image converter commands strings. Each of them is
  3552. given to the shell and supports any of the following
  3553. place-holders defined below.
  3554. Place-holders used by `:image-converter' and `:latex-compiler':
  3555. %f input file name.
  3556. %b base name of input file.
  3557. %o base directory of input file.
  3558. Place-holders only used by `:image-converter':
  3559. %F foreground of image
  3560. %B background of image
  3561. %D dpi, which is used to adjust image size by some processing commands.
  3562. %S the image size scale ratio, which is used to adjust image size by some
  3563. processing commands."
  3564. :group 'org-latex
  3565. :version "25.2"
  3566. :package-version '(Org . "9.0")
  3567. :type '(alist :tag "LaTeX to image backends"
  3568. :value-type (plist)))
  3569. (defcustom org-preview-latex-image-directory "ltximg/"
  3570. "Path to store latex preview images.
  3571. A relative path here creates many directories relative to the
  3572. processed org files paths. An absolute path puts all preview
  3573. images at the same place."
  3574. :group 'org-latex
  3575. :version "25.1"
  3576. :package-version '(Org . "9.0")
  3577. :type 'string)
  3578. (defun org-format-latex-mathml-available-p ()
  3579. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3580. (save-match-data
  3581. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3582. org-latex-to-mathml-convert-command)
  3583. (let ((executable (car (split-string
  3584. org-latex-to-mathml-convert-command))))
  3585. (when (executable-find executable)
  3586. (if (string-match
  3587. "%j" org-latex-to-mathml-convert-command)
  3588. (file-readable-p org-latex-to-mathml-jar-file)
  3589. t))))))
  3590. (defcustom org-format-latex-header "\\documentclass{article}
  3591. \\usepackage[usenames]{color}
  3592. \[PACKAGES]
  3593. \[DEFAULT-PACKAGES]
  3594. \\pagestyle{empty} % do not remove
  3595. % The settings below are copied from fullpage.sty
  3596. \\setlength{\\textwidth}{\\paperwidth}
  3597. \\addtolength{\\textwidth}{-3cm}
  3598. \\setlength{\\oddsidemargin}{1.5cm}
  3599. \\addtolength{\\oddsidemargin}{-2.54cm}
  3600. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3601. \\setlength{\\textheight}{\\paperheight}
  3602. \\addtolength{\\textheight}{-\\headheight}
  3603. \\addtolength{\\textheight}{-\\headsep}
  3604. \\addtolength{\\textheight}{-\\footskip}
  3605. \\addtolength{\\textheight}{-3cm}
  3606. \\setlength{\\topmargin}{1.5cm}
  3607. \\addtolength{\\topmargin}{-2.54cm}"
  3608. "The document header used for processing LaTeX fragments.
  3609. It is imperative that this header make sure that no page number
  3610. appears on the page. The package defined in the variables
  3611. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3612. will either replace the placeholder \"[PACKAGES]\" in this
  3613. header, or they will be appended."
  3614. :group 'org-latex
  3615. :type 'string)
  3616. (defun org-set-packages-alist (var val)
  3617. "Set the packages alist and make sure it has 3 elements per entry."
  3618. (set var (mapcar (lambda (x)
  3619. (if (and (consp x) (= (length x) 2))
  3620. (list (car x) (nth 1 x) t)
  3621. x))
  3622. val)))
  3623. (defun org-get-packages-alist (var)
  3624. "Get the packages alist and make sure it has 3 elements per entry."
  3625. (mapcar (lambda (x)
  3626. (if (and (consp x) (= (length x) 2))
  3627. (list (car x) (nth 1 x) t)
  3628. x))
  3629. (default-value var)))
  3630. (defcustom org-latex-default-packages-alist
  3631. '(("AUTO" "inputenc" t ("pdflatex"))
  3632. ("T1" "fontenc" t ("pdflatex"))
  3633. ("" "graphicx" t)
  3634. ("" "grffile" t)
  3635. ("" "longtable" nil)
  3636. ("" "wrapfig" nil)
  3637. ("" "rotating" nil)
  3638. ("normalem" "ulem" t)
  3639. ("" "amsmath" t)
  3640. ("" "textcomp" t)
  3641. ("" "amssymb" t)
  3642. ("" "capt-of" nil)
  3643. ("" "hyperref" nil))
  3644. "Alist of default packages to be inserted in the header.
  3645. Change this only if one of the packages here causes an
  3646. incompatibility with another package you are using.
  3647. The packages in this list are needed by one part or another of
  3648. Org mode to function properly:
  3649. - inputenc, fontenc: for basic font and character selection
  3650. - graphicx: for including images
  3651. - grffile: allow periods and spaces in graphics file names
  3652. - longtable: For multipage tables
  3653. - wrapfig: for figure placement
  3654. - rotating: for sideways figures and tables
  3655. - ulem: for underline and strike-through
  3656. - amsmath: for subscript and superscript and math environments
  3657. - textcomp, amssymb: for various symbols used
  3658. for interpreting the entities in `org-entities'. You can skip
  3659. some of these packages if you don't use any of their symbols.
  3660. - capt-of: for captions outside of floats
  3661. - hyperref: for cross references
  3662. Therefore you should not modify this variable unless you know
  3663. what you are doing. The one reason to change it anyway is that
  3664. you might be loading some other package that conflicts with one
  3665. of the default packages. Each element is either a cell or
  3666. a string.
  3667. A cell is of the format
  3668. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3669. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3670. when compiling LaTeX snippets into images for inclusion into
  3671. non-LaTeX output. COMPILERS is a list of compilers that should
  3672. include the package, see `org-latex-compiler'. If the document
  3673. compiler is not in the list, and the list is non-nil, the package
  3674. will not be inserted in the final document.
  3675. A string will be inserted as-is in the header of the document."
  3676. :group 'org-latex
  3677. :group 'org-export-latex
  3678. :set 'org-set-packages-alist
  3679. :get 'org-get-packages-alist
  3680. :version "25.1"
  3681. :package-version '(Org . "8.3")
  3682. :type '(repeat
  3683. (choice
  3684. (list :tag "options/package pair"
  3685. (string :tag "options")
  3686. (string :tag "package")
  3687. (boolean :tag "Snippet"))
  3688. (string :tag "A line of LaTeX"))))
  3689. (defcustom org-latex-packages-alist nil
  3690. "Alist of packages to be inserted in every LaTeX header.
  3691. These will be inserted after `org-latex-default-packages-alist'.
  3692. Each element is either a cell or a string.
  3693. A cell is of the format:
  3694. (\"options\" \"package\" SNIPPET-FLAG)
  3695. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3696. needed when turning LaTeX snippets into images for inclusion into
  3697. non-LaTeX output.
  3698. A string will be inserted as-is in the header of the document.
  3699. Make sure that you only list packages here which:
  3700. - you want in every file;
  3701. - do not conflict with the setup in `org-format-latex-header';
  3702. - do not conflict with the default packages in
  3703. `org-latex-default-packages-alist'."
  3704. :group 'org-latex
  3705. :group 'org-export-latex
  3706. :set 'org-set-packages-alist
  3707. :get 'org-get-packages-alist
  3708. :type '(repeat
  3709. (choice
  3710. (list :tag "options/package pair"
  3711. (string :tag "options")
  3712. (string :tag "package")
  3713. (boolean :tag "Snippet"))
  3714. (string :tag "A line of LaTeX"))))
  3715. (defgroup org-appearance nil
  3716. "Settings for Org mode appearance."
  3717. :tag "Org Appearance"
  3718. :group 'org)
  3719. (defcustom org-level-color-stars-only nil
  3720. "Non-nil means fontify only the stars in each headline.
  3721. When nil, the entire headline is fontified.
  3722. Changing it requires restart of `font-lock-mode' to become effective
  3723. also in regions already fontified."
  3724. :group 'org-appearance
  3725. :type 'boolean)
  3726. (defcustom org-hide-leading-stars nil
  3727. "Non-nil means hide the first N-1 stars in a headline.
  3728. This works by using the face `org-hide' for these stars. This
  3729. face is white for a light background, and black for a dark
  3730. background. You may have to customize the face `org-hide' to
  3731. make this work.
  3732. Changing it requires restart of `font-lock-mode' to become effective
  3733. also in regions already fontified.
  3734. You may also set this on a per-file basis by adding one of the following
  3735. lines to the buffer:
  3736. #+STARTUP: hidestars
  3737. #+STARTUP: showstars"
  3738. :group 'org-appearance
  3739. :type 'boolean)
  3740. (defcustom org-hidden-keywords nil
  3741. "List of symbols corresponding to keywords to be hidden the org buffer.
  3742. For example, a value \\='(title) for this list will make the document's title
  3743. appear in the buffer without the initial #+TITLE: keyword."
  3744. :group 'org-appearance
  3745. :version "24.1"
  3746. :type '(set (const :tag "#+AUTHOR" author)
  3747. (const :tag "#+DATE" date)
  3748. (const :tag "#+EMAIL" email)
  3749. (const :tag "#+TITLE" title)))
  3750. (defcustom org-custom-properties nil
  3751. "List of properties (as strings) with a special meaning.
  3752. The default use of these custom properties is to let the user
  3753. hide them with `org-toggle-custom-properties-visibility'."
  3754. :group 'org-properties
  3755. :group 'org-appearance
  3756. :version "24.3"
  3757. :type '(repeat (string :tag "Property Name")))
  3758. (defcustom org-fontify-done-headline nil
  3759. "Non-nil means change the face of a headline if it is marked DONE.
  3760. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3761. When this is non-nil, the headline after the keyword is set to the
  3762. `org-headline-done' as an additional indication."
  3763. :group 'org-appearance
  3764. :type 'boolean)
  3765. (defcustom org-fontify-emphasized-text t
  3766. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3767. Changing this variable requires a restart of Emacs to take effect."
  3768. :group 'org-appearance
  3769. :type 'boolean)
  3770. (defcustom org-fontify-whole-heading-line nil
  3771. "Non-nil means fontify the whole line for headings.
  3772. This is useful when setting a background color for the
  3773. org-level-* faces."
  3774. :group 'org-appearance
  3775. :type 'boolean)
  3776. (defcustom org-highlight-latex-and-related nil
  3777. "Non-nil means highlight LaTeX related syntax in the buffer.
  3778. When non nil, the value should be a list containing any of the
  3779. following symbols:
  3780. `latex' Highlight LaTeX snippets and environments.
  3781. `script' Highlight subscript and superscript.
  3782. `entities' Highlight entities."
  3783. :group 'org-appearance
  3784. :version "24.4"
  3785. :package-version '(Org . "8.0")
  3786. :type '(choice
  3787. (const :tag "No highlighting" nil)
  3788. (set :greedy t :tag "Highlight"
  3789. (const :tag "LaTeX snippets and environments" latex)
  3790. (const :tag "Subscript and superscript" script)
  3791. (const :tag "Entities" entities))))
  3792. (defcustom org-hide-emphasis-markers nil
  3793. "Non-nil mean font-lock should hide the emphasis marker characters."
  3794. :group 'org-appearance
  3795. :type 'boolean)
  3796. (defcustom org-hide-macro-markers nil
  3797. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3798. :group 'org-appearance
  3799. :type 'boolean)
  3800. (defcustom org-pretty-entities nil
  3801. "Non-nil means show entities as UTF8 characters.
  3802. When nil, the \\name form remains in the buffer."
  3803. :group 'org-appearance
  3804. :version "24.1"
  3805. :type 'boolean)
  3806. (defcustom org-pretty-entities-include-sub-superscripts t
  3807. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3808. :group 'org-appearance
  3809. :version "24.1"
  3810. :type 'boolean)
  3811. (defvar org-emph-re nil
  3812. "Regular expression for matching emphasis.
  3813. After a match, the match groups contain these elements:
  3814. 0 The match of the full regular expression, including the characters
  3815. before and after the proper match
  3816. 1 The character before the proper match, or empty at beginning of line
  3817. 2 The proper match, including the leading and trailing markers
  3818. 3 The leading marker like * or /, indicating the type of highlighting
  3819. 4 The text between the emphasis markers, not including the markers
  3820. 5 The character after the match, empty at the end of a line")
  3821. (defvar org-verbatim-re nil
  3822. "Regular expression for matching verbatim text.")
  3823. (defvar org-emphasis-regexp-components) ; defined just below
  3824. (defvar org-emphasis-alist) ; defined just below
  3825. (defun org-set-emph-re (var val)
  3826. "Set variable and compute the emphasis regular expression."
  3827. (set var val)
  3828. (when (and (boundp 'org-emphasis-alist)
  3829. (boundp 'org-emphasis-regexp-components)
  3830. org-emphasis-alist org-emphasis-regexp-components)
  3831. (let* ((e org-emphasis-regexp-components)
  3832. (pre (car e))
  3833. (post (nth 1 e))
  3834. (border (nth 2 e))
  3835. (body (nth 3 e))
  3836. (nl (nth 4 e))
  3837. (body1 (concat body "*?"))
  3838. (markers (mapconcat 'car org-emphasis-alist ""))
  3839. (vmarkers (mapconcat
  3840. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3841. org-emphasis-alist "")))
  3842. ;; make sure special characters appear at the right position in the class
  3843. (if (string-match "\\^" markers)
  3844. (setq markers (concat (replace-match "" t t markers) "^")))
  3845. (if (string-match "-" markers)
  3846. (setq markers (concat (replace-match "" t t markers) "-")))
  3847. (if (string-match "\\^" vmarkers)
  3848. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3849. (if (string-match "-" vmarkers)
  3850. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3851. (if (> nl 0)
  3852. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3853. (int-to-string nl) "\\}")))
  3854. ;; Make the regexp
  3855. (setq org-emph-re
  3856. (concat "\\([" pre "]\\|^\\)"
  3857. "\\("
  3858. "\\([" markers "]\\)"
  3859. "\\("
  3860. "[^" border "]\\|"
  3861. "[^" border "]"
  3862. body1
  3863. "[^" border "]"
  3864. "\\)"
  3865. "\\3\\)"
  3866. "\\([" post "]\\|$\\)"))
  3867. (setq org-verbatim-re
  3868. (concat "\\([" pre "]\\|^\\)"
  3869. "\\("
  3870. "\\([" vmarkers "]\\)"
  3871. "\\("
  3872. "[^" border "]\\|"
  3873. "[^" border "]"
  3874. body1
  3875. "[^" border "]"
  3876. "\\)"
  3877. "\\3\\)"
  3878. "\\([" post "]\\|$\\)")))))
  3879. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3880. ;; set this option proved cumbersome. See this message/thread:
  3881. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3882. (defvar org-emphasis-regexp-components
  3883. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3884. "Components used to build the regular expression for emphasis.
  3885. This is a list with five entries. Terminology: In an emphasis string
  3886. like \" *strong word* \", we call the initial space PREMATCH, the final
  3887. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3888. and \"trong wor\" is the body. The different components in this variable
  3889. specify what is allowed/forbidden in each part:
  3890. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3891. post Chars allowed as postmatch. End of line will be allowed too.
  3892. border The chars *forbidden* as border characters.
  3893. body-regexp A regexp like \".\" to match a body character. Don't use
  3894. non-shy groups here, and don't allow newline here.
  3895. newline The maximum number of newlines allowed in an emphasis exp.
  3896. You need to reload Org or to restart Emacs after customizing this.")
  3897. (defcustom org-emphasis-alist
  3898. '(("*" bold)
  3899. ("/" italic)
  3900. ("_" underline)
  3901. ("=" org-verbatim verbatim)
  3902. ("~" org-code verbatim)
  3903. ("+" (:strike-through t)))
  3904. "Alist of characters and faces to emphasize text.
  3905. Text starting and ending with a special character will be emphasized,
  3906. for example *bold*, _underlined_ and /italic/. This variable sets the
  3907. marker characters and the face to be used by font-lock for highlighting
  3908. in Org buffers.
  3909. You need to reload Org or to restart Emacs after customizing this."
  3910. :group 'org-appearance
  3911. :set 'org-set-emph-re
  3912. :version "24.4"
  3913. :package-version '(Org . "8.0")
  3914. :type '(repeat
  3915. (list
  3916. (string :tag "Marker character")
  3917. (choice
  3918. (face :tag "Font-lock-face")
  3919. (plist :tag "Face property list"))
  3920. (option (const verbatim)))))
  3921. (defvar org-protecting-blocks '("src" "example" "export")
  3922. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3923. This is needed for font-lock setup.")
  3924. ;;; Functions and variables from their packages
  3925. ;; Declared here to avoid compiler warnings
  3926. (defvar mark-active)
  3927. ;; Various packages
  3928. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3929. (declare-function calendar-forward-day "cal-move" (arg))
  3930. (declare-function calendar-goto-date "cal-move" (date))
  3931. (declare-function calendar-goto-today "cal-move" ())
  3932. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3933. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3934. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3935. (declare-function cdlatex-tab "ext:cdlatex" ())
  3936. (declare-function dired-get-filename
  3937. "dired"
  3938. (&optional localp no-error-if-not-filep))
  3939. (declare-function iswitchb-read-buffer
  3940. "iswitchb"
  3941. (prompt &optional
  3942. default require-match _predicate start matches-set))
  3943. (declare-function org-agenda-change-all-lines
  3944. "org-agenda"
  3945. (newhead hdmarker &optional fixface just-this))
  3946. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3947. "org-agenda"
  3948. (&optional end))
  3949. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3950. (declare-function org-agenda-format-item
  3951. "org-agenda"
  3952. (extra txt &optional level category tags dotime
  3953. remove-re habitp))
  3954. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3955. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3956. (declare-function org-agenda-save-markers-for-cut-and-paste
  3957. "org-agenda"
  3958. (beg end))
  3959. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3960. (declare-function org-agenda-skip "org-agenda" ())
  3961. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3962. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3963. (declare-function org-indent-mode "org-indent" (&optional arg))
  3964. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3965. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3966. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3967. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3968. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3969. (declare-function parse-time-string "parse-time" (string))
  3970. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3971. (defvar align-mode-rules-list)
  3972. (defvar calc-embedded-close-formula)
  3973. (defvar calc-embedded-open-formula)
  3974. (defvar calc-embedded-open-mode)
  3975. (defvar font-lock-unfontify-region-function)
  3976. (defvar iswitchb-temp-buflist)
  3977. (defvar org-agenda-tags-todo-honor-ignore-options)
  3978. (defvar remember-data-file)
  3979. (defvar texmathp-why)
  3980. ;;;###autoload
  3981. (defun turn-on-orgtbl ()
  3982. "Unconditionally turn on `orgtbl-mode'."
  3983. (require 'org-table)
  3984. (orgtbl-mode 1))
  3985. (defun org-at-table-p (&optional table-type)
  3986. "Non-nil if the cursor is inside an Org table.
  3987. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3988. If `org-enable-table-editor' is nil, return nil unconditionally."
  3989. (and
  3990. org-enable-table-editor
  3991. (save-excursion
  3992. (beginning-of-line)
  3993. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3994. (or (not (derived-mode-p 'org-mode))
  3995. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3996. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3997. (defun org-at-table.el-p ()
  3998. "Non-nil when point is at a table.el table."
  3999. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4000. (let ((element (org-element-at-point)))
  4001. (and (eq (org-element-type element) 'table)
  4002. (eq (org-element-property :type element) 'table.el)))))
  4003. (defun org-at-table-hline-p ()
  4004. "Non-nil when point is inside a hline in a table.
  4005. Assume point is already in a table. If `org-enable-table-editor'
  4006. is nil, return nil unconditionally."
  4007. (and org-enable-table-editor
  4008. (save-excursion
  4009. (beginning-of-line)
  4010. (looking-at org-table-hline-regexp))))
  4011. (defun org-table-map-tables (function &optional quietly)
  4012. "Apply FUNCTION to the start of all tables in the buffer."
  4013. (org-with-wide-buffer
  4014. (goto-char (point-min))
  4015. (while (re-search-forward org-table-any-line-regexp nil t)
  4016. (unless quietly
  4017. (message "Mapping tables: %d%%"
  4018. (floor (* 100.0 (point)) (buffer-size))))
  4019. (beginning-of-line 1)
  4020. (when (and (looking-at org-table-line-regexp)
  4021. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4022. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4023. (save-excursion (funcall function))
  4024. (or (looking-at org-table-line-regexp)
  4025. (forward-char 1)))
  4026. (re-search-forward org-table-any-border-regexp nil 1)))
  4027. (unless quietly (message "Mapping tables: done")))
  4028. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4029. (declare-function org-clock-update-mode-line "org-clock" ())
  4030. (declare-function org-resolve-clocks "org-clock"
  4031. (&optional also-non-dangling-p prompt last-valid))
  4032. (defun org-at-TBLFM-p (&optional pos)
  4033. "Non-nil when point (or POS) is in #+TBLFM line."
  4034. (save-excursion
  4035. (goto-char (or pos (point)))
  4036. (beginning-of-line)
  4037. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4038. (eq (org-element-type (org-element-at-point)) 'table))))
  4039. (defvar org-clock-start-time)
  4040. (defvar org-clock-marker (make-marker)
  4041. "Marker recording the last clock-in.")
  4042. (defvar org-clock-hd-marker (make-marker)
  4043. "Marker recording the last clock-in, but the headline position.")
  4044. (defvar org-clock-heading ""
  4045. "The heading of the current clock entry.")
  4046. (defun org-clock-is-active ()
  4047. "Return the buffer where the clock is currently running.
  4048. Return nil if no clock is running."
  4049. (marker-buffer org-clock-marker))
  4050. (defun org-check-running-clock ()
  4051. "Check if the current buffer contains the running clock.
  4052. If yes, offer to stop it and to save the buffer with the changes."
  4053. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4054. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4055. (buffer-name))))
  4056. (org-clock-out)
  4057. (when (y-or-n-p "Save changed buffer?")
  4058. (save-buffer))))
  4059. (defun org-clocktable-try-shift (dir n)
  4060. "Check if this line starts a clock table, if yes, shift the time block."
  4061. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4062. (org-clocktable-shift dir n)))
  4063. ;;;###autoload
  4064. (defun org-clock-persistence-insinuate ()
  4065. "Set up hooks for clock persistence."
  4066. (require 'org-clock)
  4067. (add-hook 'org-mode-hook 'org-clock-load)
  4068. (add-hook 'kill-emacs-hook 'org-clock-save))
  4069. (defgroup org-archive nil
  4070. "Options concerning archiving in Org-mode."
  4071. :tag "Org Archive"
  4072. :group 'org-structure)
  4073. (defcustom org-archive-location "%s_archive::"
  4074. "The location where subtrees should be archived.
  4075. The value of this variable is a string, consisting of two parts,
  4076. separated by a double-colon. The first part is a filename and
  4077. the second part is a headline.
  4078. When the filename is omitted, archiving happens in the same file.
  4079. %s in the filename will be replaced by the current file
  4080. name (without the directory part). Archiving to a different file
  4081. is useful to keep archived entries from contributing to the
  4082. Org Agenda.
  4083. The archived entries will be filed as subtrees of the specified
  4084. headline. When the headline is omitted, the subtrees are simply
  4085. filed away at the end of the file, as top-level entries. Also in
  4086. the heading you can use %s to represent the file name, this can be
  4087. useful when using the same archive for a number of different files.
  4088. Here are a few examples:
  4089. \"%s_archive::\"
  4090. If the current file is Projects.org, archive in file
  4091. Projects.org_archive, as top-level trees. This is the default.
  4092. \"::* Archived Tasks\"
  4093. Archive in the current file, under the top-level headline
  4094. \"* Archived Tasks\".
  4095. \"~/org/archive.org::\"
  4096. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4097. \"~/org/archive.org::* From %s\"
  4098. Archive in file ~/org/archive.org (absolute path), under headlines
  4099. \"From FILENAME\" where file name is the current file name.
  4100. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4101. The \"datetree/\" string is special, signifying to archive
  4102. items to the datetree. Items are placed in either the CLOSED
  4103. date of the item, or the current date if there is no CLOSED date.
  4104. The heading will be a subentry to the current date. There doesn't
  4105. need to be a heading, but there always needs to be a slash after
  4106. datetree. For example, to store archived items directly in the
  4107. datetree, use \"~/org/datetree.org::datetree/\".
  4108. \"basement::** Finished Tasks\"
  4109. Archive in file ./basement (relative path), as level 3 trees
  4110. below the level 2 heading \"** Finished Tasks\".
  4111. You may set this option on a per-file basis by adding to the buffer a
  4112. line like
  4113. #+ARCHIVE: basement::** Finished Tasks
  4114. You may also define it locally for a subtree by setting an ARCHIVE property
  4115. in the entry. If such a property is found in an entry, or anywhere up
  4116. the hierarchy, it will be used."
  4117. :group 'org-archive
  4118. :type 'string)
  4119. (defcustom org-agenda-skip-archived-trees t
  4120. "Non-nil means the agenda will skip any items located in archived trees.
  4121. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4122. variable is no longer recommended, you should leave it at the value t.
  4123. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4124. :group 'org-archive
  4125. :group 'org-agenda-skip
  4126. :type 'boolean)
  4127. (defcustom org-columns-skip-archived-trees t
  4128. "Non-nil means ignore archived trees when creating column view."
  4129. :group 'org-archive
  4130. :group 'org-properties
  4131. :type 'boolean)
  4132. (defcustom org-cycle-open-archived-trees nil
  4133. "Non-nil means `org-cycle' will open archived trees.
  4134. An archived tree is a tree marked with the tag ARCHIVE.
  4135. When nil, archived trees will stay folded. You can still open them with
  4136. normal outline commands like `show-all', but not with the cycling commands."
  4137. :group 'org-archive
  4138. :group 'org-cycle
  4139. :type 'boolean)
  4140. (defcustom org-sparse-tree-open-archived-trees nil
  4141. "Non-nil means sparse tree construction shows matches in archived trees.
  4142. When nil, matches in these trees are highlighted, but the trees are kept in
  4143. collapsed state."
  4144. :group 'org-archive
  4145. :group 'org-sparse-trees
  4146. :type 'boolean)
  4147. (defcustom org-sparse-tree-default-date-type nil
  4148. "The default date type when building a sparse tree.
  4149. When this is nil, a date is a scheduled or a deadline timestamp.
  4150. Otherwise, these types are allowed:
  4151. all: all timestamps
  4152. active: only active timestamps (<...>)
  4153. inactive: only inactive timestamps ([...])
  4154. scheduled: only scheduled timestamps
  4155. deadline: only deadline timestamps"
  4156. :type '(choice (const :tag "Scheduled or deadline" nil)
  4157. (const :tag "All timestamps" all)
  4158. (const :tag "Only active timestamps" active)
  4159. (const :tag "Only inactive timestamps" inactive)
  4160. (const :tag "Only scheduled timestamps" scheduled)
  4161. (const :tag "Only deadline timestamps" deadline)
  4162. (const :tag "Only closed timestamps" closed))
  4163. :version "25.1"
  4164. :package-version '(Org . "8.3")
  4165. :group 'org-sparse-trees)
  4166. (defun org-cycle-hide-archived-subtrees (state)
  4167. "Re-hide all archived subtrees after a visibility state change."
  4168. (when (and (not org-cycle-open-archived-trees)
  4169. (not (memq state '(overview folded))))
  4170. (save-excursion
  4171. (let* ((globalp (memq state '(contents all)))
  4172. (beg (if globalp (point-min) (point)))
  4173. (end (if globalp (point-max) (org-end-of-subtree t))))
  4174. (org-hide-archived-subtrees beg end)
  4175. (goto-char beg)
  4176. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4177. (message "%s" (substitute-command-keys
  4178. "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
  4179. (defun org-force-cycle-archived ()
  4180. "Cycle subtree even if it is archived."
  4181. (interactive)
  4182. (setq this-command 'org-cycle)
  4183. (let ((org-cycle-open-archived-trees t))
  4184. (call-interactively 'org-cycle)))
  4185. (defun org-hide-archived-subtrees (beg end)
  4186. "Re-hide all archived subtrees after a visibility state change."
  4187. (org-with-wide-buffer
  4188. (let ((case-fold-search nil)
  4189. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4190. (goto-char beg)
  4191. ;; Include headline point is currently on.
  4192. (beginning-of-line)
  4193. (while (and (< (point) end) (re-search-forward re end t))
  4194. (when (member org-archive-tag (org-get-tags))
  4195. (org-flag-subtree t)
  4196. (org-end-of-subtree t))))))
  4197. (declare-function outline-end-of-heading "outline" ())
  4198. (declare-function outline-flag-region "outline" (from to flag))
  4199. (defun org-flag-subtree (flag)
  4200. (save-excursion
  4201. (org-back-to-heading t)
  4202. (outline-end-of-heading)
  4203. (outline-flag-region (point)
  4204. (progn (org-end-of-subtree t) (point))
  4205. flag)))
  4206. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4207. ;; Declare Column View Code
  4208. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4209. (declare-function org-columns-compute "org-colview" (property))
  4210. ;; Declare ID code
  4211. (declare-function org-id-store-link "org-id")
  4212. (declare-function org-id-locations-load "org-id")
  4213. (declare-function org-id-locations-save "org-id")
  4214. (defvar org-id-track-globally)
  4215. ;;; Variables for pre-computed regular expressions, all buffer local
  4216. (defvar-local org-todo-regexp nil
  4217. "Matches any of the TODO state keywords.")
  4218. (defvar-local org-not-done-regexp nil
  4219. "Matches any of the TODO state keywords except the last one.")
  4220. (defvar-local org-not-done-heading-regexp nil
  4221. "Matches a TODO headline that is not done.")
  4222. (defvar-local org-todo-line-regexp nil
  4223. "Matches a headline and puts TODO state into group 2 if present.")
  4224. (defvar-local org-complex-heading-regexp nil
  4225. "Matches a headline and puts everything into groups:
  4226. group 1: the stars
  4227. group 2: The todo keyword, maybe
  4228. group 3: Priority cookie
  4229. group 4: True headline
  4230. group 5: Tags")
  4231. (defvar-local org-complex-heading-regexp-format nil
  4232. "Printf format to make regexp to match an exact headline.
  4233. This regexp will match the headline of any node which has the
  4234. exact headline text that is put into the format, but may have any
  4235. TODO state, priority and tags.")
  4236. (defvar-local org-todo-line-tags-regexp nil
  4237. "Matches a headline and puts TODO state into group 2 if present.
  4238. Also put tags into group 4 if tags are present.")
  4239. (defconst org-plain-time-of-day-regexp
  4240. (concat
  4241. "\\(\\<[012]?[0-9]"
  4242. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4243. "\\(--?"
  4244. "\\(\\<[012]?[0-9]"
  4245. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4246. "\\)?")
  4247. "Regular expression to match a plain time or time range.
  4248. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4249. groups carry important information:
  4250. 0 the full match
  4251. 1 the first time, range or not
  4252. 8 the second time, if it is a range.")
  4253. (defconst org-plain-time-extension-regexp
  4254. (concat
  4255. "\\(\\<[012]?[0-9]"
  4256. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4257. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4258. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4259. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4260. groups carry important information:
  4261. 0 the full match
  4262. 7 hours of duration
  4263. 9 minutes of duration")
  4264. (defconst org-stamp-time-of-day-regexp
  4265. (concat
  4266. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4267. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4268. "\\(--?"
  4269. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4270. "Regular expression to match a timestamp time or time range.
  4271. After a match, the following groups carry important information:
  4272. 0 the full match
  4273. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4274. 2 the first time, range or not
  4275. 4 the second time, if it is a range.")
  4276. (defconst org-startup-options
  4277. '(("fold" org-startup-folded t)
  4278. ("overview" org-startup-folded t)
  4279. ("nofold" org-startup-folded nil)
  4280. ("showall" org-startup-folded nil)
  4281. ("showeverything" org-startup-folded showeverything)
  4282. ("content" org-startup-folded content)
  4283. ("indent" org-startup-indented t)
  4284. ("noindent" org-startup-indented nil)
  4285. ("hidestars" org-hide-leading-stars t)
  4286. ("showstars" org-hide-leading-stars nil)
  4287. ("odd" org-odd-levels-only t)
  4288. ("oddeven" org-odd-levels-only nil)
  4289. ("align" org-startup-align-all-tables t)
  4290. ("noalign" org-startup-align-all-tables nil)
  4291. ("inlineimages" org-startup-with-inline-images t)
  4292. ("noinlineimages" org-startup-with-inline-images nil)
  4293. ("latexpreview" org-startup-with-latex-preview t)
  4294. ("nolatexpreview" org-startup-with-latex-preview nil)
  4295. ("customtime" org-display-custom-times t)
  4296. ("logdone" org-log-done time)
  4297. ("lognotedone" org-log-done note)
  4298. ("nologdone" org-log-done nil)
  4299. ("lognoteclock-out" org-log-note-clock-out t)
  4300. ("nolognoteclock-out" org-log-note-clock-out nil)
  4301. ("logrepeat" org-log-repeat state)
  4302. ("lognoterepeat" org-log-repeat note)
  4303. ("logdrawer" org-log-into-drawer t)
  4304. ("nologdrawer" org-log-into-drawer nil)
  4305. ("logstatesreversed" org-log-states-order-reversed t)
  4306. ("nologstatesreversed" org-log-states-order-reversed nil)
  4307. ("nologrepeat" org-log-repeat nil)
  4308. ("logreschedule" org-log-reschedule time)
  4309. ("lognotereschedule" org-log-reschedule note)
  4310. ("nologreschedule" org-log-reschedule nil)
  4311. ("logredeadline" org-log-redeadline time)
  4312. ("lognoteredeadline" org-log-redeadline note)
  4313. ("nologredeadline" org-log-redeadline nil)
  4314. ("logrefile" org-log-refile time)
  4315. ("lognoterefile" org-log-refile note)
  4316. ("nologrefile" org-log-refile nil)
  4317. ("fninline" org-footnote-define-inline t)
  4318. ("nofninline" org-footnote-define-inline nil)
  4319. ("fnlocal" org-footnote-section nil)
  4320. ("fnauto" org-footnote-auto-label t)
  4321. ("fnprompt" org-footnote-auto-label nil)
  4322. ("fnconfirm" org-footnote-auto-label confirm)
  4323. ("fnplain" org-footnote-auto-label plain)
  4324. ("fnadjust" org-footnote-auto-adjust t)
  4325. ("nofnadjust" org-footnote-auto-adjust nil)
  4326. ("constcgs" constants-unit-system cgs)
  4327. ("constSI" constants-unit-system SI)
  4328. ("noptag" org-tag-persistent-alist nil)
  4329. ("hideblocks" org-hide-block-startup t)
  4330. ("nohideblocks" org-hide-block-startup nil)
  4331. ("beamer" org-startup-with-beamer-mode t)
  4332. ("entitiespretty" org-pretty-entities t)
  4333. ("entitiesplain" org-pretty-entities nil))
  4334. "Variable associated with STARTUP options for org-mode.
  4335. Each element is a list of three items: the startup options (as written
  4336. in the #+STARTUP line), the corresponding variable, and the value to set
  4337. this variable to if the option is found. An optional forth element PUSH
  4338. means to push this value onto the list in the variable.")
  4339. (defcustom org-group-tags t
  4340. "When non-nil (the default), use group tags.
  4341. This can be turned on/off through `org-toggle-tags-groups'."
  4342. :group 'org-tags
  4343. :group 'org-startup
  4344. :type 'boolean)
  4345. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4346. (defun org-toggle-tags-groups ()
  4347. "Toggle support for group tags.
  4348. Support for group tags is controlled by the option
  4349. `org-group-tags', which is non-nil by default."
  4350. (interactive)
  4351. (setq org-group-tags (not org-group-tags))
  4352. (cond ((and (derived-mode-p 'org-agenda-mode)
  4353. org-group-tags)
  4354. (org-agenda-redo))
  4355. ((derived-mode-p 'org-mode)
  4356. (let ((org-inhibit-startup t)) (org-mode))))
  4357. (message "Groups tags support has been turned %s"
  4358. (if org-group-tags "on" "off")))
  4359. (defun org-set-regexps-and-options (&optional tags-only)
  4360. "Precompute regular expressions used in the current buffer.
  4361. When optional argument TAGS-ONLY is non-nil, only compute tags
  4362. related expressions."
  4363. (when (derived-mode-p 'org-mode)
  4364. (let ((alist (org--setup-collect-keywords
  4365. (org-make-options-regexp
  4366. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4367. (and (not tags-only)
  4368. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4369. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4370. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4371. ;; Startup options. Get this early since it does change
  4372. ;; behavior for other options (e.g., tags).
  4373. (let ((startup (cdr (assq 'startup alist))))
  4374. (dolist (option startup)
  4375. (let ((entry (assoc-string option org-startup-options t)))
  4376. (when entry
  4377. (let ((var (nth 1 entry))
  4378. (val (nth 2 entry)))
  4379. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4380. (unless (listp (symbol-value var))
  4381. (set (make-local-variable var) nil))
  4382. (add-to-list var val)))))))
  4383. (setq-local org-file-tags
  4384. (mapcar #'org-add-prop-inherited
  4385. (cdr (assq 'filetags alist))))
  4386. (setq org-current-tag-alist
  4387. (append org-tag-persistent-alist
  4388. (let ((tags (cdr (assq 'tags alist))))
  4389. (if tags (org-tag-string-to-alist tags)
  4390. org-tag-alist))))
  4391. (setq org-tag-groups-alist
  4392. (org-tag-alist-to-groups org-current-tag-alist))
  4393. (unless tags-only
  4394. ;; File properties.
  4395. (setq-local org-file-properties (cdr (assq 'property alist)))
  4396. ;; Archive location.
  4397. (let ((archive (cdr (assq 'archive alist))))
  4398. (when archive (setq-local org-archive-location archive)))
  4399. ;; Category.
  4400. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4401. (when cat
  4402. (setq-local org-category (intern cat))
  4403. (setq-local org-file-properties
  4404. (org--update-property-plist
  4405. "CATEGORY" cat org-file-properties))))
  4406. ;; Columns.
  4407. (let ((column (cdr (assq 'columns alist))))
  4408. (when column (setq-local org-columns-default-format column)))
  4409. ;; Constants.
  4410. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4411. ;; Link abbreviations.
  4412. (let ((links (cdr (assq 'link alist))))
  4413. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4414. ;; Priorities.
  4415. (let ((priorities (cdr (assq 'priorities alist))))
  4416. (when priorities
  4417. (setq-local org-highest-priority (nth 0 priorities))
  4418. (setq-local org-lowest-priority (nth 1 priorities))
  4419. (setq-local org-default-priority (nth 2 priorities))))
  4420. ;; Scripts.
  4421. (let ((scripts (assq 'scripts alist)))
  4422. (when scripts
  4423. (setq-local org-use-sub-superscripts (cdr scripts))))
  4424. ;; TODO keywords.
  4425. (setq-local org-todo-kwd-alist nil)
  4426. (setq-local org-todo-key-alist nil)
  4427. (setq-local org-todo-key-trigger nil)
  4428. (setq-local org-todo-keywords-1 nil)
  4429. (setq-local org-done-keywords nil)
  4430. (setq-local org-todo-heads nil)
  4431. (setq-local org-todo-sets nil)
  4432. (setq-local org-todo-log-states nil)
  4433. (let ((todo-sequences
  4434. (or (nreverse (cdr (assq 'todo alist)))
  4435. (let ((d (default-value 'org-todo-keywords)))
  4436. (if (not (stringp (car d))) d
  4437. ;; XXX: Backward compatibility code.
  4438. (list (cons org-todo-interpretation d)))))))
  4439. (dolist (sequence todo-sequences)
  4440. (let* ((sequence (or (run-hook-with-args-until-success
  4441. 'org-todo-setup-filter-hook sequence)
  4442. sequence))
  4443. (sequence-type (car sequence))
  4444. (keywords (cdr sequence))
  4445. (sep (member "|" keywords))
  4446. names alist)
  4447. (dolist (k (remove "|" keywords))
  4448. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4449. k)
  4450. (error "Invalid TODO keyword %s" k))
  4451. (let ((name (match-string 1 k))
  4452. (key (match-string 2 k))
  4453. (log (org-extract-log-state-settings k)))
  4454. (push name names)
  4455. (push (cons name (and key (string-to-char key))) alist)
  4456. (when log (push log org-todo-log-states))))
  4457. (let* ((names (nreverse names))
  4458. (done (if sep (org-remove-keyword-keys (cdr sep))
  4459. (last names)))
  4460. (head (car names))
  4461. (tail (list sequence-type head (car done) (org-last done))))
  4462. (add-to-list 'org-todo-heads head 'append)
  4463. (push names org-todo-sets)
  4464. (setq org-done-keywords (append org-done-keywords done nil))
  4465. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4466. (setq org-todo-key-alist
  4467. (append org-todo-key-alist
  4468. (and alist
  4469. (append '((:startgroup))
  4470. (nreverse alist)
  4471. '((:endgroup))))))
  4472. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4473. (setq org-todo-sets (nreverse org-todo-sets)
  4474. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4475. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4476. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4477. ;; Compute the regular expressions and other local variables.
  4478. ;; Using `org-outline-regexp-bol' would complicate them much,
  4479. ;; because of the fixed white space at the end of that string.
  4480. (unless org-done-keywords
  4481. (setq org-done-keywords
  4482. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4483. (setq org-not-done-keywords
  4484. (org-delete-all org-done-keywords
  4485. (copy-sequence org-todo-keywords-1))
  4486. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4487. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4488. org-not-done-heading-regexp
  4489. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4490. org-todo-line-regexp
  4491. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4492. org-complex-heading-regexp
  4493. (concat "^\\(\\*+\\)"
  4494. "\\(?: +" org-todo-regexp "\\)?"
  4495. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4496. "\\(?: +\\(.*?\\)\\)??"
  4497. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4498. "[ \t]*$")
  4499. org-complex-heading-regexp-format
  4500. (concat "^\\(\\*+\\)"
  4501. "\\(?: +" org-todo-regexp "\\)?"
  4502. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4503. "\\(?: +"
  4504. ;; Stats cookies can be stuck to body.
  4505. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4506. "\\(%s\\)"
  4507. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4508. "\\)"
  4509. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4510. "[ \t]*$")
  4511. org-todo-line-tags-regexp
  4512. (concat "^\\(\\*+\\)"
  4513. "\\(?: +" org-todo-regexp "\\)?"
  4514. "\\(?: +\\(.*?\\)\\)??"
  4515. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4516. "[ \t]*$"))
  4517. (org-compute-latex-and-related-regexp)))))
  4518. (defun org--setup-collect-keywords (regexp &optional files alist)
  4519. "Return setup keywords values as an alist.
  4520. REGEXP matches a subset of setup keywords. FILES is a list of
  4521. file names already visited. It is used to avoid circular setup
  4522. files. ALIST, when non-nil, is the alist computed so far.
  4523. Return value contains the following keys: `archive', `category',
  4524. `columns', `constants', `filetags', `link', `priorities',
  4525. `property', `scripts', `startup', `tags' and `todo'."
  4526. (org-with-wide-buffer
  4527. (goto-char (point-min))
  4528. (let ((case-fold-search t))
  4529. (while (re-search-forward regexp nil t)
  4530. (let ((element (org-element-at-point)))
  4531. (when (eq (org-element-type element) 'keyword)
  4532. (let ((key (org-element-property :key element))
  4533. (value (org-element-property :value element)))
  4534. (cond
  4535. ((equal key "ARCHIVE")
  4536. (when (org-string-nw-p value)
  4537. (push (cons 'archive value) alist)))
  4538. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4539. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4540. ((equal key "CONSTANTS")
  4541. (let* ((constants (assq 'constants alist))
  4542. (store (cdr constants)))
  4543. (dolist (pair (org-split-string value))
  4544. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4545. pair)
  4546. (let* ((name (match-string 1 pair))
  4547. (value (match-string 2 pair))
  4548. (old (assoc name store)))
  4549. (if old (setcdr old value)
  4550. (push (cons name value) store)))))
  4551. (if constants (setcdr constants store)
  4552. (push (cons 'constants store) alist))))
  4553. ((equal key "FILETAGS")
  4554. (when (org-string-nw-p value)
  4555. (let ((old (assq 'filetags alist))
  4556. (new (apply #'nconc
  4557. (mapcar (lambda (x) (org-split-string x ":"))
  4558. (org-split-string value)))))
  4559. (if old (setcdr old (append new (cdr old)))
  4560. (push (cons 'filetags new) alist)))))
  4561. ((equal key "LINK")
  4562. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4563. (let ((links (assq 'link alist))
  4564. (pair (cons (match-string-no-properties 1 value)
  4565. (match-string-no-properties 2 value))))
  4566. (if links (push pair (cdr links))
  4567. (push (list 'link pair) alist)))))
  4568. ((equal key "OPTIONS")
  4569. (when (and (org-string-nw-p value)
  4570. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4571. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4572. ((equal key "PRIORITIES")
  4573. (push (cons 'priorities
  4574. (let ((prio (org-split-string value)))
  4575. (if (< (length prio) 3) '(?A ?C ?B)
  4576. (mapcar #'string-to-char prio))))
  4577. alist))
  4578. ((equal key "PROPERTY")
  4579. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4580. (let* ((property (assq 'property alist))
  4581. (value (org--update-property-plist
  4582. (match-string-no-properties 1 value)
  4583. (match-string-no-properties 2 value)
  4584. (cdr property))))
  4585. (if property (setcdr property value)
  4586. (push (cons 'property value) alist)))))
  4587. ((equal key "STARTUP")
  4588. (let ((startup (assq 'startup alist)))
  4589. (if startup
  4590. (setcdr startup
  4591. (append (cdr startup) (org-split-string value)))
  4592. (push (cons 'startup (org-split-string value)) alist))))
  4593. ((equal key "TAGS")
  4594. (let ((tag-cell (assq 'tags alist)))
  4595. (if tag-cell
  4596. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4597. (push (cons 'tags value) alist))))
  4598. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4599. (let ((todo (assq 'todo alist))
  4600. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4601. (org-split-string value))))
  4602. (if todo (push value (cdr todo))
  4603. (push (list 'todo value) alist))))
  4604. ((equal key "SETUPFILE")
  4605. (unless buffer-read-only ; Do not check in Gnus messages.
  4606. (let ((f (and (org-string-nw-p value)
  4607. (expand-file-name
  4608. (org-unbracket-string "\"" "\"" value)))))
  4609. (when (and f (file-readable-p f) (not (member f files)))
  4610. (with-temp-buffer
  4611. (setq default-directory (file-name-directory f))
  4612. (insert-file-contents f)
  4613. (setq alist
  4614. ;; Fake Org mode to benefit from cache
  4615. ;; without recurring needlessly.
  4616. (let ((major-mode 'org-mode))
  4617. (org--setup-collect-keywords
  4618. regexp (cons f files) alist)))))))))))))))
  4619. alist)
  4620. (defun org-tag-string-to-alist (s)
  4621. "Return tag alist associated to string S.
  4622. S is a value for TAGS keyword or produced with
  4623. `org-tag-alist-to-string'. Return value is an alist suitable for
  4624. `org-tag-alist' or `org-tag-persistent-alist'."
  4625. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4626. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4627. "\\|{.+?}\\)" ; regular expression
  4628. "\\(?:(\\(.\\))\\)?\\'"))
  4629. alist group-flag)
  4630. (dolist (tokens lines (cdr (nreverse alist)))
  4631. (push '(:newline) alist)
  4632. (while tokens
  4633. (let ((token (pop tokens)))
  4634. (pcase token
  4635. ("{"
  4636. (push '(:startgroup) alist)
  4637. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4638. ("}"
  4639. (push '(:endgroup) alist)
  4640. (setq group-flag nil))
  4641. ("["
  4642. (push '(:startgrouptag) alist)
  4643. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4644. ("]"
  4645. (push '(:endgrouptag) alist)
  4646. (setq group-flag nil))
  4647. (":"
  4648. (push '(:grouptags) alist))
  4649. ((guard (string-match tag-re token))
  4650. (let ((tag (match-string 1 token))
  4651. (key (and (match-beginning 2)
  4652. (string-to-char (match-string 2 token)))))
  4653. ;; Push all tags in groups, no matter if they already
  4654. ;; appear somewhere else in the list.
  4655. (when (or group-flag (not (assoc tag alist)))
  4656. (push (cons tag key) alist))))))))))
  4657. (defun org-tag-alist-to-string (alist &optional skip-key)
  4658. "Return tag string associated to ALIST.
  4659. ALIST is an alist, as defined in `org-tag-alist' or
  4660. `org-tag-persistent-alist', or produced with
  4661. `org-tag-string-to-alist'.
  4662. Return value is a string suitable as a value for \"TAGS\"
  4663. keyword.
  4664. When optional argument SKIP-KEY is non-nil, skip selection keys
  4665. next to tags."
  4666. (mapconcat (lambda (token)
  4667. (pcase token
  4668. (`(:startgroup) "{")
  4669. (`(:endgroup) "}")
  4670. (`(:startgrouptag) "[")
  4671. (`(:endgrouptag) "]")
  4672. (`(:grouptags) ":")
  4673. (`(:newline) "\\n")
  4674. ((and
  4675. (guard (not skip-key))
  4676. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4677. (format "%s(%c)" tag key))
  4678. (`(,(and tag (pred stringp)) . ,_) tag)
  4679. (_ (user-error "Invalid tag token: %S" token))))
  4680. alist
  4681. " "))
  4682. (defun org-tag-alist-to-groups (alist)
  4683. "Return group alist from tag ALIST.
  4684. ALIST is an alist, as defined in `org-tag-alist' or
  4685. `org-tag-persistent-alist', or produced with
  4686. `org-tag-string-to-alist'. Return value is an alist following
  4687. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4688. a string, summarizing TAGS, as a list of strings."
  4689. (let (groups group-status current-group)
  4690. (dolist (token alist (nreverse groups))
  4691. (pcase token
  4692. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4693. (`(,(or :endgroup :endgrouptag))
  4694. (when (eq group-status 'append)
  4695. (push (nreverse current-group) groups))
  4696. (setq group-status nil))
  4697. (`(:grouptags) (setq group-status 'append))
  4698. ((and `(,tag . ,_) (guard group-status))
  4699. (if (eq group-status 'append) (push tag current-group)
  4700. (setq current-group (list tag))))
  4701. (_ nil)))))
  4702. (defun org-file-contents (file &optional noerror)
  4703. "Return the contents of FILE, as a string."
  4704. (if (and file (file-readable-p file))
  4705. (with-temp-buffer
  4706. (insert-file-contents file)
  4707. (buffer-string))
  4708. (funcall (if noerror 'message 'error)
  4709. "Cannot read file \"%s\"%s"
  4710. file
  4711. (let ((from (buffer-file-name (buffer-base-buffer))))
  4712. (if from (concat " (referenced in file \"" from "\")") "")))))
  4713. (defun org-extract-log-state-settings (x)
  4714. "Extract the log state setting from a TODO keyword string.
  4715. This will extract info from a string like \"WAIT(w@/!)\"."
  4716. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4717. (let ((kw (match-string 1 x))
  4718. (log1 (and (match-end 3) (match-string 3 x)))
  4719. (log2 (and (match-end 4) (match-string 4 x))))
  4720. (and (or log1 log2)
  4721. (list kw
  4722. (and log1 (if (equal log1 "!") 'time 'note))
  4723. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4724. (defun org-remove-keyword-keys (list)
  4725. "Remove a pair of parenthesis at the end of each string in LIST."
  4726. (mapcar (lambda (x)
  4727. (if (string-match "(.*)$" x)
  4728. (substring x 0 (match-beginning 0))
  4729. x))
  4730. list))
  4731. (defun org-assign-fast-keys (alist)
  4732. "Assign fast keys to a keyword-key alist.
  4733. Respect keys that are already there."
  4734. (let (new e (alt ?0))
  4735. (while (setq e (pop alist))
  4736. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4737. (cdr e)) ;; Key already assigned.
  4738. (push e new)
  4739. (let ((clist (string-to-list (downcase (car e))))
  4740. (used (append new alist)))
  4741. (when (= (car clist) ?@)
  4742. (pop clist))
  4743. (while (and clist (rassoc (car clist) used))
  4744. (pop clist))
  4745. (unless clist
  4746. (while (rassoc alt used)
  4747. (cl-incf alt)))
  4748. (push (cons (car e) (or (car clist) alt)) new))))
  4749. (nreverse new)))
  4750. ;;; Some variables used in various places
  4751. (defvar org-window-configuration nil
  4752. "Used in various places to store a window configuration.")
  4753. (defvar org-selected-window nil
  4754. "Used in various places to store a window configuration.")
  4755. (defvar org-finish-function nil
  4756. "Function to be called when `C-c C-c' is used.
  4757. This is for getting out of special buffers like capture.")
  4758. (defvar org-last-state)
  4759. ;; Defined somewhere in this file, but used before definition.
  4760. (defvar org-entities) ;; defined in org-entities.el
  4761. (defvar org-struct-menu)
  4762. (defvar org-org-menu)
  4763. (defvar org-tbl-menu)
  4764. ;;;; Define the Org mode
  4765. ;; We use a before-change function to check if a table might need
  4766. ;; an update.
  4767. (defvar org-table-may-need-update t
  4768. "Indicates that a table might need an update.
  4769. This variable is set by `org-before-change-function'.
  4770. `org-table-align' sets it back to nil.")
  4771. (defun org-before-change-function (_beg _end)
  4772. "Every change indicates that a table might need an update."
  4773. (setq org-table-may-need-update t))
  4774. (defvar org-mode-map)
  4775. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4776. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4777. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4778. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4779. (defvar org-table-buffer-is-an nil)
  4780. (defvar bidi-paragraph-direction)
  4781. (defvar buffer-face-mode-face)
  4782. (require 'outline)
  4783. ;; Other stuff we need.
  4784. (require 'time-date)
  4785. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4786. (require 'easymenu)
  4787. (autoload 'easy-menu-add "easymenu")
  4788. (require 'overlay)
  4789. ;; (require 'org-macs) moved higher up in the file before it is first used
  4790. (require 'org-entities)
  4791. ;; (require 'org-compat) moved higher up in the file before it is first used
  4792. (require 'org-faces)
  4793. (require 'org-list)
  4794. (require 'org-pcomplete)
  4795. (require 'org-src)
  4796. (require 'org-footnote)
  4797. (require 'org-macro)
  4798. ;; babel
  4799. (require 'ob)
  4800. ;;;###autoload
  4801. (define-derived-mode org-mode outline-mode "Org"
  4802. "Outline-based notes management and organizer, alias
  4803. \"Carsten's outline-mode for keeping track of everything.\"
  4804. Org mode develops organizational tasks around a NOTES file which
  4805. contains information about projects as plain text. Org mode is
  4806. implemented on top of Outline mode, which is ideal to keep the content
  4807. of large files well structured. It supports ToDo items, deadlines and
  4808. time stamps, which magically appear in the diary listing of the Emacs
  4809. calendar. Tables are easily created with a built-in table editor.
  4810. Plain text URL-like links connect to websites, emails (VM), Usenet
  4811. messages (Gnus), BBDB entries, and any files related to the project.
  4812. For printing and sharing of notes, an Org file (or a part of it)
  4813. can be exported as a structured ASCII or HTML file.
  4814. The following commands are available:
  4815. \\{org-mode-map}"
  4816. ;; Get rid of Outline menus, they are not needed
  4817. ;; Need to do this here because define-derived-mode sets up
  4818. ;; the keymap so late. Still, it is a waste to call this each time
  4819. ;; we switch another buffer into Org mode.
  4820. (define-key org-mode-map [menu-bar headings] 'undefined)
  4821. (define-key org-mode-map [menu-bar hide] 'undefined)
  4822. (define-key org-mode-map [menu-bar show] 'undefined)
  4823. (org-load-modules-maybe)
  4824. (org-install-agenda-files-menu)
  4825. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4826. (add-to-invisibility-spec '(org-cwidth))
  4827. (add-to-invisibility-spec '(org-hide-block . t))
  4828. (setq-local outline-regexp org-outline-regexp)
  4829. (setq-local outline-level 'org-outline-level)
  4830. (setq bidi-paragraph-direction 'left-to-right)
  4831. (when (and org-ellipsis
  4832. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4833. (fboundp 'make-glyph-code))
  4834. (unless org-display-table
  4835. (setq org-display-table (make-display-table)))
  4836. (set-display-table-slot
  4837. org-display-table 4
  4838. (vconcat (mapcar
  4839. (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
  4840. org-ellipsis)))
  4841. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4842. (setq buffer-display-table org-display-table))
  4843. (org-set-regexps-and-options)
  4844. (org-set-font-lock-defaults)
  4845. (when (and org-tag-faces (not org-tags-special-faces-re))
  4846. ;; tag faces set outside customize.... force initialization.
  4847. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4848. ;; Calc embedded
  4849. (setq-local calc-embedded-open-mode "# ")
  4850. ;; Modify a few syntax entries
  4851. (modify-syntax-entry ?@ "w")
  4852. (modify-syntax-entry ?\" "\"")
  4853. (modify-syntax-entry ?\\ "_")
  4854. (modify-syntax-entry ?~ "_")
  4855. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4856. ;; Activate before-change-function
  4857. (setq-local org-table-may-need-update t)
  4858. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4859. ;; Check for running clock before killing a buffer
  4860. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4861. ;; Initialize macros templates.
  4862. (org-macro-initialize-templates)
  4863. ;; Initialize radio targets.
  4864. (org-update-radio-target-regexp)
  4865. ;; Indentation.
  4866. (setq-local indent-line-function 'org-indent-line)
  4867. (setq-local indent-region-function 'org-indent-region)
  4868. ;; Filling and auto-filling.
  4869. (org-setup-filling)
  4870. ;; Comments.
  4871. (org-setup-comments-handling)
  4872. ;; Initialize cache.
  4873. (org-element-cache-reset)
  4874. ;; Beginning/end of defun
  4875. (setq-local beginning-of-defun-function 'org-backward-element)
  4876. (setq-local end-of-defun-function
  4877. (lambda ()
  4878. (if (not (org-at-heading-p))
  4879. (org-forward-element)
  4880. (org-forward-element)
  4881. (forward-char -1))))
  4882. ;; Next error for sparse trees
  4883. (setq-local next-error-function 'org-occur-next-match)
  4884. ;; Make sure dependence stuff works reliably, even for users who set it
  4885. ;; too late :-(
  4886. (if org-enforce-todo-dependencies
  4887. (add-hook 'org-blocker-hook
  4888. 'org-block-todo-from-children-or-siblings-or-parent)
  4889. (remove-hook 'org-blocker-hook
  4890. 'org-block-todo-from-children-or-siblings-or-parent))
  4891. (if org-enforce-todo-checkbox-dependencies
  4892. (add-hook 'org-blocker-hook
  4893. 'org-block-todo-from-checkboxes)
  4894. (remove-hook 'org-blocker-hook
  4895. 'org-block-todo-from-checkboxes))
  4896. ;; Align options lines
  4897. (setq-local
  4898. align-mode-rules-list
  4899. '((org-in-buffer-settings
  4900. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4901. (modes . '(org-mode)))))
  4902. ;; Imenu
  4903. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4904. ;; Make isearch reveal context
  4905. (setq-local outline-isearch-open-invisible-function
  4906. (lambda (&rest _) (org-show-context 'isearch)))
  4907. ;; Setup the pcomplete hooks
  4908. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4909. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4910. (setq-local pcomplete-default-completion-function 'ignore)
  4911. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4912. (setq-local pcomplete-termination-string "")
  4913. (setq-local buffer-face-mode-face 'org-default)
  4914. ;; If empty file that did not turn on Org mode automatically, make
  4915. ;; it to.
  4916. (when (and org-insert-mode-line-in-empty-file
  4917. (called-interactively-p 'any)
  4918. (= (point-min) (point-max)))
  4919. (insert "# -*- mode: org -*-\n\n"))
  4920. (unless org-inhibit-startup
  4921. (org-unmodified
  4922. (when org-startup-with-beamer-mode (org-beamer-mode))
  4923. (when org-startup-align-all-tables
  4924. (org-table-map-tables #'org-table-align t))
  4925. (when org-startup-with-inline-images (org-display-inline-images))
  4926. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4927. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4928. (when org-startup-truncated (setq truncate-lines t))
  4929. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4930. (org-refresh-effort-properties)))
  4931. ;; Try to set `org-hide' face correctly.
  4932. (let ((foreground (org-find-invisible-foreground)))
  4933. (when foreground
  4934. (set-face-foreground 'org-hide foreground))))
  4935. ;; Update `customize-package-emacs-version-alist'
  4936. (add-to-list 'customize-package-emacs-version-alist
  4937. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4938. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4939. ("8.2.6" . "24.4") ("8.3" . "25.1")))
  4940. (defvar org-mode-transpose-word-syntax-table
  4941. (let ((st (make-syntax-table text-mode-syntax-table)))
  4942. (dolist (c org-emphasis-alist st)
  4943. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4944. (when (fboundp 'abbrev-table-put)
  4945. (abbrev-table-put org-mode-abbrev-table
  4946. :parents (list text-mode-abbrev-table)))
  4947. (defun org-find-invisible-foreground ()
  4948. (let ((candidates (remove
  4949. "unspecified-bg"
  4950. (nconc
  4951. (list (face-background 'default)
  4952. (face-background 'org-default))
  4953. (mapcar
  4954. (lambda (alist)
  4955. (when (boundp alist)
  4956. (cdr (assq 'background-color (symbol-value alist)))))
  4957. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4958. (list (face-foreground 'org-hide))))))
  4959. (car (remove nil candidates))))
  4960. (defun org-current-time (&optional rounding-minutes past)
  4961. "Current time, possibly rounded to ROUNDING-MINUTES.
  4962. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4963. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4964. the rounding returns a past time."
  4965. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4966. (car org-time-stamp-rounding-minutes)))
  4967. (time (decode-time)) res)
  4968. (if (< r 1)
  4969. (current-time)
  4970. (setq res
  4971. (apply 'encode-time
  4972. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4973. (nthcdr 2 time))))
  4974. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4975. (seconds-to-time (- (float-time res) (* r 60)))
  4976. res))))
  4977. (defun org-today ()
  4978. "Return today date, considering `org-extend-today-until'."
  4979. (time-to-days
  4980. (time-subtract (current-time)
  4981. (list 0 (* 3600 org-extend-today-until) 0))))
  4982. ;;;; Font-Lock stuff, including the activators
  4983. (defvar org-mouse-map (make-sparse-keymap))
  4984. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4985. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4986. (when org-mouse-1-follows-link
  4987. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4988. (when org-tab-follows-link
  4989. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4990. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4991. (require 'font-lock)
  4992. (defconst org-non-link-chars "]\t\n\r<>")
  4993. (defvar org-link-types-re nil
  4994. "Matches a link that has a url-like prefix like \"http:\"")
  4995. (defvar org-link-re-with-space nil
  4996. "Matches a link with spaces, optional angular brackets around it.")
  4997. (defvar org-link-re-with-space2 nil
  4998. "Matches a link with spaces, optional angular brackets around it.")
  4999. (defvar org-link-re-with-space3 nil
  5000. "Matches a link with spaces, only for internal part in bracket links.")
  5001. (defvar org-angle-link-re nil
  5002. "Matches link with angular brackets, spaces are allowed.")
  5003. (defvar org-plain-link-re nil
  5004. "Matches plain link, without spaces.")
  5005. (defvar org-bracket-link-regexp nil
  5006. "Matches a link in double brackets.")
  5007. (defvar org-bracket-link-analytic-regexp nil
  5008. "Regular expression used to analyze links.
  5009. Here is what the match groups contain after a match:
  5010. 1: http:
  5011. 2: http
  5012. 3: path
  5013. 4: [desc]
  5014. 5: desc")
  5015. (defvar org-bracket-link-analytic-regexp++ nil
  5016. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5017. (defvar org-any-link-re nil
  5018. "Regular expression matching any link.")
  5019. (defconst org-match-sexp-depth 3
  5020. "Number of stacked braces for sub/superscript matching.")
  5021. (defun org-create-multibrace-regexp (left right n)
  5022. "Create a regular expression which will match a balanced sexp.
  5023. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5024. as single character strings.
  5025. The regexp returned will match the entire expression including the
  5026. delimiters. It will also define a single group which contains the
  5027. match except for the outermost delimiters. The maximum depth of
  5028. stacked delimiters is N. Escaping delimiters is not possible."
  5029. (let* ((nothing (concat "[^" left right "]*?"))
  5030. (or "\\|")
  5031. (re nothing)
  5032. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5033. (while (> n 1)
  5034. (setq n (1- n)
  5035. re (concat re or next)
  5036. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5037. (concat left "\\(" re "\\)" right)))
  5038. (defconst org-match-substring-regexp
  5039. (concat
  5040. "\\(\\S-\\)\\([_^]\\)\\("
  5041. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5042. "\\|"
  5043. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5044. "\\|"
  5045. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5046. "The regular expression matching a sub- or superscript.")
  5047. (defconst org-match-substring-with-braces-regexp
  5048. (concat
  5049. "\\(\\S-\\)\\([_^]\\)"
  5050. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5051. "The regular expression matching a sub- or superscript, forcing braces.")
  5052. (defun org-make-link-regexps ()
  5053. "Update the link regular expressions.
  5054. This should be called after the variable `org-link-parameters' has changed."
  5055. (let ((types-re (regexp-opt (org-link-types) t)))
  5056. (setq org-link-types-re
  5057. (concat "\\`" types-re ":")
  5058. org-link-re-with-space
  5059. (concat "<?" types-re ":"
  5060. "\\([^" org-non-link-chars " ]"
  5061. "[^" org-non-link-chars "]*"
  5062. "[^" org-non-link-chars " ]\\)>?")
  5063. org-link-re-with-space2
  5064. (concat "<?" types-re ":"
  5065. "\\([^" org-non-link-chars " ]"
  5066. "[^\t\n\r]*"
  5067. "[^" org-non-link-chars " ]\\)>?")
  5068. org-link-re-with-space3
  5069. (concat "<?" types-re ":"
  5070. "\\([^" org-non-link-chars " ]"
  5071. "[^\t\n\r]*\\)")
  5072. org-angle-link-re
  5073. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5074. types-re)
  5075. org-plain-link-re
  5076. (concat
  5077. "\\<" types-re ":"
  5078. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5079. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5080. org-bracket-link-regexp
  5081. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5082. org-bracket-link-analytic-regexp
  5083. (concat
  5084. "\\[\\["
  5085. "\\(" types-re ":\\)?"
  5086. "\\([^]]+\\)"
  5087. "\\]"
  5088. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5089. "\\]")
  5090. org-bracket-link-analytic-regexp++
  5091. (concat
  5092. "\\[\\["
  5093. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5094. "\\([^]]+\\)"
  5095. "\\]"
  5096. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5097. "\\]")
  5098. org-any-link-re
  5099. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5100. org-angle-link-re "\\)\\|\\("
  5101. org-plain-link-re "\\)"))))
  5102. (org-make-link-regexps)
  5103. (defvar org-emph-face nil)
  5104. (defun org-do-emphasis-faces (limit)
  5105. "Run through the buffer and emphasize strings."
  5106. (let (rtn a)
  5107. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5108. (let* ((border (char-after (match-beginning 3)))
  5109. (bre (regexp-quote (char-to-string border))))
  5110. (when (and (not (= border (char-after (match-beginning 4))))
  5111. (not (string-match-p (concat bre ".*" bre)
  5112. (replace-regexp-in-string
  5113. "\n" " "
  5114. (substring (match-string 2) 1 -1)))))
  5115. (setq rtn t)
  5116. (setq a (assoc (match-string 3) org-emphasis-alist))
  5117. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5118. 'face
  5119. (nth 1 a))
  5120. (and (nth 2 a)
  5121. (org-remove-flyspell-overlays-in
  5122. (match-beginning 0) (match-end 0)))
  5123. (add-text-properties (match-beginning 2) (match-end 2)
  5124. '(font-lock-multiline t org-emphasis t))
  5125. (when org-hide-emphasis-markers
  5126. (add-text-properties (match-end 4) (match-beginning 5)
  5127. '(invisible org-link))
  5128. (add-text-properties (match-beginning 3) (match-end 3)
  5129. '(invisible org-link)))))
  5130. (goto-char (1+ (match-beginning 0))))
  5131. rtn))
  5132. (defun org-emphasize (&optional char)
  5133. "Insert or change an emphasis, i.e. a font like bold or italic.
  5134. If there is an active region, change that region to a new emphasis.
  5135. If there is no region, just insert the marker characters and position
  5136. the cursor between them.
  5137. CHAR should be the marker character. If it is a space, it means to
  5138. remove the emphasis of the selected region.
  5139. If CHAR is not given (for example in an interactive call) it will be
  5140. prompted for."
  5141. (interactive)
  5142. (let ((erc org-emphasis-regexp-components)
  5143. (string "") beg end move s)
  5144. (if (org-region-active-p)
  5145. (setq beg (region-beginning)
  5146. end (region-end)
  5147. string (buffer-substring beg end))
  5148. (setq move t))
  5149. (unless char
  5150. (message "Emphasis marker or tag: [%s]"
  5151. (mapconcat #'car org-emphasis-alist ""))
  5152. (setq char (read-char-exclusive)))
  5153. (if (equal char ?\s)
  5154. (setq s ""
  5155. move nil)
  5156. (unless (assoc (char-to-string char) org-emphasis-alist)
  5157. (user-error "No such emphasis marker: \"%c\"" char))
  5158. (setq s (char-to-string char)))
  5159. (while (and (> (length string) 1)
  5160. (equal (substring string 0 1) (substring string -1))
  5161. (assoc (substring string 0 1) org-emphasis-alist))
  5162. (setq string (substring string 1 -1)))
  5163. (setq string (concat s string s))
  5164. (when beg (delete-region beg end))
  5165. (unless (or (bolp)
  5166. (string-match (concat "[" (nth 0 erc) "\n]")
  5167. (char-to-string (char-before (point)))))
  5168. (insert " "))
  5169. (unless (or (eobp)
  5170. (string-match (concat "[" (nth 1 erc) "\n]")
  5171. (char-to-string (char-after (point)))))
  5172. (insert " ") (backward-char 1))
  5173. (insert string)
  5174. (and move (backward-char 1))))
  5175. (defconst org-nonsticky-props
  5176. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5177. (defsubst org-rear-nonsticky-at (pos)
  5178. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5179. (defun org-activate-plain-links (limit)
  5180. "Add link properties for plain links."
  5181. (when (and (re-search-forward org-plain-link-re limit t)
  5182. (not (org-in-src-block-p)))
  5183. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5184. 'face))
  5185. (link (match-string-no-properties 0))
  5186. (type (match-string-no-properties 1))
  5187. (path (match-string-no-properties 2))
  5188. (link-start (match-beginning 0))
  5189. (link-end (match-end 0))
  5190. (link-face (org-link-get-parameter type :face))
  5191. (help-echo (org-link-get-parameter type :help-echo))
  5192. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5193. (activate-func (org-link-get-parameter type :activate-func)))
  5194. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5195. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5196. (add-text-properties (match-beginning 0) (match-end 0)
  5197. (list
  5198. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5199. 'highlight)
  5200. 'face (cond
  5201. ;; A function that returns a face
  5202. ((functionp link-face)
  5203. (funcall link-face path))
  5204. ;; a face
  5205. ((facep link-face)
  5206. link-face)
  5207. ;; An anonymous face
  5208. ((consp link-face)
  5209. link-face)
  5210. ;; default
  5211. (t
  5212. 'org-link))
  5213. 'help-echo (cond
  5214. ((stringp help-echo)
  5215. help-echo)
  5216. ((functionp help-echo)
  5217. help-echo)
  5218. (t
  5219. (concat "LINK: "
  5220. (save-match-data
  5221. (org-link-unescape link)))))
  5222. 'htmlize-link (cond
  5223. ((functionp htmlize-link)
  5224. (funcall htmlize-link path))
  5225. (t
  5226. `(:uri ,link)))
  5227. 'keymap (or (org-link-get-parameter type :keymap)
  5228. org-mouse-map)
  5229. 'org-link-start (match-beginning 0)))
  5230. (org-rear-nonsticky-at (match-end 0))
  5231. (when activate-func
  5232. (funcall activate-func link-start link-end path nil))
  5233. t))))
  5234. (defun org-activate-code (limit)
  5235. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5236. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5237. (remove-text-properties (match-beginning 0) (match-end 0)
  5238. '(display t invisible t intangible t))
  5239. t))
  5240. (defcustom org-src-fontify-natively t
  5241. "When non-nil, fontify code in code blocks.
  5242. See also the `org-block' face."
  5243. :type 'boolean
  5244. :version "24.4"
  5245. :package-version '(Org . "8.3")
  5246. :group 'org-appearance
  5247. :group 'org-babel)
  5248. (defcustom org-allow-promoting-top-level-subtree nil
  5249. "When non-nil, allow promoting a top level subtree.
  5250. The leading star of the top level headline will be replaced
  5251. by a #."
  5252. :type 'boolean
  5253. :version "24.1"
  5254. :group 'org-appearance)
  5255. (defun org-fontify-meta-lines-and-blocks (limit)
  5256. (condition-case nil
  5257. (org-fontify-meta-lines-and-blocks-1 limit)
  5258. (error (message "org-mode fontification error in %S at %d"
  5259. (current-buffer)
  5260. (line-number-at-pos)))))
  5261. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5262. "Fontify #+ lines and blocks."
  5263. (let ((case-fold-search t))
  5264. (when (re-search-forward
  5265. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5266. limit t)
  5267. (let ((beg (match-beginning 0))
  5268. (block-start (match-end 0))
  5269. (block-end nil)
  5270. (lang (match-string 7))
  5271. (beg1 (line-beginning-position 2))
  5272. (dc1 (downcase (match-string 2)))
  5273. (dc3 (downcase (match-string 3)))
  5274. end end1 quoting block-type)
  5275. (cond
  5276. ((and (match-end 4) (equal dc3 "+begin"))
  5277. ;; Truly a block
  5278. (setq block-type (downcase (match-string 5))
  5279. quoting (member block-type org-protecting-blocks))
  5280. (when (re-search-forward
  5281. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5282. nil t) ;; on purpose, we look further than LIMIT
  5283. (setq end (min (point-max) (match-end 0))
  5284. end1 (min (point-max) (1- (match-beginning 0))))
  5285. (setq block-end (match-beginning 0))
  5286. (when quoting
  5287. (org-remove-flyspell-overlays-in beg1 end1)
  5288. (remove-text-properties beg end
  5289. '(display t invisible t intangible t)))
  5290. (add-text-properties
  5291. beg end '(font-lock-fontified t font-lock-multiline t))
  5292. (add-text-properties beg beg1 '(face org-meta-line))
  5293. (org-remove-flyspell-overlays-in beg beg1)
  5294. (add-text-properties ; For end_src
  5295. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5296. (org-remove-flyspell-overlays-in end1 end)
  5297. (cond
  5298. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5299. (org-src-font-lock-fontify-block lang block-start block-end)
  5300. (add-text-properties beg1 block-end '(src-block t)))
  5301. (quoting
  5302. (add-text-properties beg1 (min (point-max) (1+ end1))
  5303. (list 'face
  5304. (list :inherit
  5305. (let ((face-name
  5306. (intern (format "org-block-%s" lang))))
  5307. (append (and (facep face-name) (list face-name))
  5308. '(org-block))))))) ; end of source block
  5309. ((not org-fontify-quote-and-verse-blocks))
  5310. ((string= block-type "quote")
  5311. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5312. ((string= block-type "verse")
  5313. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5314. (add-text-properties beg beg1 '(face org-block-begin-line))
  5315. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5316. '(face org-block-end-line))
  5317. t))
  5318. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5319. (org-remove-flyspell-overlays-in
  5320. (match-beginning 0)
  5321. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5322. (add-text-properties
  5323. beg (match-end 3)
  5324. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5325. '(font-lock-fontified t invisible t)
  5326. '(font-lock-fontified t face org-document-info-keyword)))
  5327. (add-text-properties
  5328. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5329. (if (string-equal dc1 "+title:")
  5330. '(font-lock-fontified t face org-document-title)
  5331. '(font-lock-fontified t face org-document-info))))
  5332. ((equal dc1 "+caption:")
  5333. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5334. (remove-text-properties (match-beginning 0) (match-end 0)
  5335. '(display t invisible t intangible t))
  5336. (add-text-properties (match-beginning 1) (match-end 3)
  5337. '(font-lock-fontified t face org-meta-line))
  5338. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5339. '(font-lock-fontified t face org-block))
  5340. t)
  5341. ((member dc3 '(" " ""))
  5342. (org-remove-flyspell-overlays-in beg (match-end 0))
  5343. (add-text-properties
  5344. beg (match-end 0)
  5345. '(font-lock-fontified t face font-lock-comment-face)))
  5346. (t ;; just any other in-buffer setting, but not indented
  5347. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5348. (remove-text-properties (match-beginning 0) (match-end 0)
  5349. '(display t invisible t intangible t))
  5350. (add-text-properties beg (match-end 0)
  5351. '(font-lock-fontified t face org-meta-line))
  5352. t))))))
  5353. (defun org-fontify-drawers (limit)
  5354. "Fontify drawers."
  5355. (when (re-search-forward org-drawer-regexp limit t)
  5356. (add-text-properties
  5357. (match-beginning 0) (match-end 0)
  5358. '(font-lock-fontified t face org-special-keyword))
  5359. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5360. t))
  5361. (defun org-fontify-macros (limit)
  5362. "Fontify macros."
  5363. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5364. (add-text-properties
  5365. (match-beginning 0) (match-end 0)
  5366. '(font-lock-fontified t face org-macro))
  5367. (when org-hide-macro-markers
  5368. (add-text-properties (match-end 2) (match-beginning 2)
  5369. '(invisible t))
  5370. (add-text-properties (match-beginning 1) (match-end 1)
  5371. '(invisible t)))
  5372. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5373. t))
  5374. (defun org-activate-angle-links (limit)
  5375. "Add text properties for angle links."
  5376. (when (and (re-search-forward org-angle-link-re limit t)
  5377. (not (org-in-src-block-p)))
  5378. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5379. (add-text-properties (match-beginning 0) (match-end 0)
  5380. (list 'mouse-face 'highlight
  5381. 'keymap org-mouse-map
  5382. 'font-lock-multiline t))
  5383. (org-rear-nonsticky-at (match-end 0))
  5384. t))
  5385. (defun org-activate-footnote-links (limit)
  5386. "Add text properties for footnotes."
  5387. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5388. (when fn
  5389. (let* ((beg (nth 1 fn))
  5390. (end (nth 2 fn))
  5391. (label (car fn))
  5392. (referencep (/= (line-beginning-position) beg)))
  5393. (when (and referencep (nth 3 fn))
  5394. (save-excursion
  5395. (goto-char beg)
  5396. (search-forward (or label "fn:"))
  5397. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5398. (add-text-properties beg end
  5399. (list 'mouse-face 'highlight
  5400. 'keymap org-mouse-map
  5401. 'help-echo
  5402. (if referencep "Footnote reference"
  5403. "Footnote definition")
  5404. 'font-lock-fontified t
  5405. 'font-lock-multiline t
  5406. 'face 'org-footnote))))))
  5407. (defun org-activate-bracket-links (limit)
  5408. "Add text properties for bracketed links."
  5409. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5410. (not (org-in-src-block-p)))
  5411. (let* ((hl (save-match-data
  5412. (org-link-expand-abbrev (match-string-no-properties 1))))
  5413. (type (save-match-data
  5414. (and (string-match org-plain-link-re hl)
  5415. (match-string-no-properties 1 hl))))
  5416. (path (save-match-data
  5417. (and (string-match org-plain-link-re hl)
  5418. (match-string-no-properties 2 hl))))
  5419. (link-start (match-beginning 0))
  5420. (link-end (match-end 0))
  5421. (bracketp t)
  5422. (help-echo (org-link-get-parameter type :help-echo))
  5423. (help (cond
  5424. ((stringp help-echo)
  5425. help-echo)
  5426. ((functionp help-echo)
  5427. help-echo)
  5428. (t
  5429. (concat "LINK: "
  5430. (save-match-data
  5431. (org-link-unescape hl))))))
  5432. (link-face (org-link-get-parameter type :face))
  5433. (face (cond
  5434. ;; A function that returns a face
  5435. ((functionp link-face)
  5436. (funcall link-face path))
  5437. ;; a face
  5438. ((facep link-face)
  5439. link-face)
  5440. ;; An anonymous face
  5441. ((consp link-face)
  5442. link-face)
  5443. ;; default
  5444. (t
  5445. 'org-link)))
  5446. (keymap (or (org-link-get-parameter type :keymap)
  5447. org-mouse-map))
  5448. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5449. 'highlight))
  5450. (htmlize (org-link-get-parameter type :htmlize-link))
  5451. (htmlize-link (cond
  5452. ((functionp htmlize)
  5453. (funcall htmlize))
  5454. (t
  5455. `(:uri ,(format "%s:%s" type path)))))
  5456. (activate-func (org-link-get-parameter type :activate-func))
  5457. ;; invisible part
  5458. (ip (list 'invisible (or
  5459. (org-link-get-parameter type :display)
  5460. 'org-link)
  5461. 'face face
  5462. 'keymap keymap
  5463. 'mouse-face mouse-face
  5464. 'font-lock-multiline t
  5465. 'help-echo help
  5466. 'htmlize-link htmlize-link))
  5467. ;; visible part
  5468. (vp (list 'keymap keymap
  5469. 'face face
  5470. 'mouse-face mouse-face
  5471. 'font-lock-multiline t
  5472. 'help-echo help
  5473. 'htmlize-link htmlize-link)))
  5474. ;; We need to remove the invisible property here. Table narrowing
  5475. ;; may have made some of this invisible.
  5476. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5477. (remove-text-properties (match-beginning 0) (match-end 0)
  5478. '(invisible nil))
  5479. (if (match-end 3)
  5480. (progn
  5481. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5482. (org-rear-nonsticky-at (match-beginning 3))
  5483. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5484. (org-rear-nonsticky-at (match-end 3))
  5485. (add-text-properties (match-end 3) (match-end 0) ip)
  5486. (org-rear-nonsticky-at (match-end 0)))
  5487. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5488. (org-rear-nonsticky-at (match-beginning 1))
  5489. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5490. (org-rear-nonsticky-at (match-end 1))
  5491. (add-text-properties (match-end 1) (match-end 0) ip)
  5492. (org-rear-nonsticky-at (match-end 0)))
  5493. (when activate-func
  5494. (funcall activate-func link-start link-end path bracketp))
  5495. t)))
  5496. (defun org-activate-dates (limit)
  5497. "Add text properties for dates."
  5498. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5499. (not (equal (char-before (match-beginning 0)) 91)))
  5500. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5501. (add-text-properties (match-beginning 0) (match-end 0)
  5502. (list 'mouse-face 'highlight
  5503. 'keymap org-mouse-map))
  5504. (org-rear-nonsticky-at (match-end 0))
  5505. (when org-display-custom-times
  5506. (if (match-end 3)
  5507. (org-display-custom-time (match-beginning 3) (match-end 3))
  5508. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5509. t))
  5510. (defvar-local org-target-link-regexp nil
  5511. "Regular expression matching radio targets in plain text.")
  5512. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5513. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5514. border border border))
  5515. "Regular expression matching a link target.")
  5516. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5517. "Regular expression matching a radio target.")
  5518. (defconst org-any-target-regexp
  5519. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5520. "Regular expression matching any target.")
  5521. (defun org-activate-target-links (limit)
  5522. "Add text properties for target matches."
  5523. (when org-target-link-regexp
  5524. (let ((case-fold-search t))
  5525. (when (re-search-forward org-target-link-regexp limit t)
  5526. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5527. (add-text-properties (match-beginning 1) (match-end 1)
  5528. (list 'mouse-face 'highlight
  5529. 'keymap org-mouse-map
  5530. 'help-echo "Radio target link"
  5531. 'org-linked-text t))
  5532. (org-rear-nonsticky-at (match-end 1))
  5533. t))))
  5534. (defun org-update-radio-target-regexp ()
  5535. "Find all radio targets in this file and update the regular expression.
  5536. Also refresh fontification if needed."
  5537. (interactive)
  5538. (let ((old-regexp org-target-link-regexp)
  5539. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5540. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5541. (targets
  5542. (org-with-wide-buffer
  5543. (goto-char (point-min))
  5544. (let (rtn)
  5545. (while (re-search-forward org-radio-target-regexp nil t)
  5546. ;; Make sure point is really within the object.
  5547. (backward-char)
  5548. (let ((obj (org-element-context)))
  5549. (when (eq (org-element-type obj) 'radio-target)
  5550. (cl-pushnew (org-element-property :value obj) rtn
  5551. :test #'equal))))
  5552. rtn))))
  5553. (setq org-target-link-regexp
  5554. (and targets
  5555. (concat before-re
  5556. (mapconcat
  5557. (lambda (x)
  5558. (replace-regexp-in-string
  5559. " +" "\\s-+" (regexp-quote x) t t))
  5560. targets
  5561. "\\|")
  5562. after-re)))
  5563. (unless (equal old-regexp org-target-link-regexp)
  5564. ;; Clean-up cache.
  5565. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5566. ((not org-target-link-regexp) old-regexp)
  5567. (t
  5568. (concat before-re
  5569. (mapconcat
  5570. (lambda (re)
  5571. (substring re (length before-re)
  5572. (- (length after-re))))
  5573. (list old-regexp org-target-link-regexp)
  5574. "\\|")
  5575. after-re)))))
  5576. (org-with-wide-buffer
  5577. (goto-char (point-min))
  5578. (while (re-search-forward regexp nil t)
  5579. (org-element-cache-refresh (match-beginning 1)))))
  5580. ;; Re fontify buffer.
  5581. (when (memq 'radio org-highlight-links)
  5582. (org-restart-font-lock)))))
  5583. (defun org-hide-wide-columns (limit)
  5584. (let (s e)
  5585. (setq s (text-property-any (point) (or limit (point-max))
  5586. 'org-cwidth t))
  5587. (when s
  5588. (setq e (next-single-property-change s 'org-cwidth))
  5589. (add-text-properties s e '(invisible org-cwidth))
  5590. (goto-char e)
  5591. t)))
  5592. (defvar org-latex-and-related-regexp nil
  5593. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5594. (defun org-compute-latex-and-related-regexp ()
  5595. "Compute regular expression for LaTeX, entities and sub/superscript.
  5596. Result depends on variable `org-highlight-latex-and-related'."
  5597. (setq-local
  5598. org-latex-and-related-regexp
  5599. (let* ((re-sub
  5600. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5601. ((eq org-use-sub-superscripts '{})
  5602. (list org-match-substring-with-braces-regexp))
  5603. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5604. (re-latex
  5605. (when (memq 'latex org-highlight-latex-and-related)
  5606. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5607. (delq nil
  5608. (mapcar (lambda (x)
  5609. (and (member (car x) matchers) (nth 1 x)))
  5610. org-latex-regexps)))))
  5611. (re-entities
  5612. (when (memq 'entities org-highlight-latex-and-related)
  5613. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5614. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5615. (defun org-do-latex-and-related (limit)
  5616. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5617. LIMIT bounds the search for syntax to highlight. Stop at first
  5618. highlighted object, if any. Return t if some highlighting was
  5619. done, nil otherwise."
  5620. (when (org-string-nw-p org-latex-and-related-regexp)
  5621. (catch 'found
  5622. (while (re-search-forward org-latex-and-related-regexp limit t)
  5623. (unless
  5624. (cl-some
  5625. (lambda (f)
  5626. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5627. (save-excursion
  5628. (goto-char (1+ (match-beginning 0)))
  5629. (face-at-point nil t)))
  5630. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5631. '(?_ ?^))
  5632. 1
  5633. 0)))
  5634. (font-lock-prepend-text-property
  5635. (+ offset (match-beginning 0)) (match-end 0)
  5636. 'face 'org-latex-and-related)
  5637. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5638. '(font-lock-multiline t)))
  5639. (throw 'found t)))
  5640. nil)))
  5641. (defun org-restart-font-lock ()
  5642. "Restart `font-lock-mode', to force refontification."
  5643. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5644. (font-lock-mode -1)
  5645. (font-lock-mode 1)))
  5646. (defun org-activate-tags (limit)
  5647. (when (re-search-forward
  5648. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5649. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5650. (add-text-properties (match-beginning 1) (match-end 1)
  5651. (list 'mouse-face 'highlight
  5652. 'keymap org-mouse-map))
  5653. (org-rear-nonsticky-at (match-end 1))
  5654. t))
  5655. (defun org-outline-level ()
  5656. "Compute the outline level of the heading at point.
  5657. If this is called at a normal headline, the level is the number
  5658. of stars. Use `org-reduced-level' to remove the effect of
  5659. `org-odd-levels'. Unlike to `org-current-level', this function
  5660. takes into consideration inlinetasks."
  5661. (org-with-wide-buffer
  5662. (end-of-line)
  5663. (if (re-search-backward org-outline-regexp-bol nil t)
  5664. (1- (- (match-end 0) (match-beginning 0)))
  5665. 0)))
  5666. (defvar org-font-lock-keywords nil)
  5667. (defsubst org-re-property (property &optional literal allow-null value)
  5668. "Return a regexp matching a PROPERTY line.
  5669. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5670. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5671. non-nil, match properties even without a value.
  5672. Match group 3 is set to the value when it exists. If there is no
  5673. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5674. With optional argument VALUE, match only property lines with
  5675. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5676. unless LITERAL is non-nil."
  5677. (concat
  5678. "^\\(?4:[ \t]*\\)"
  5679. (format "\\(?1::\\(?2:%s\\):\\)"
  5680. (if literal property (regexp-quote property)))
  5681. (cond (value
  5682. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5683. (if literal value (regexp-quote value))))
  5684. (allow-null
  5685. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5686. (t
  5687. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5688. (defconst org-property-re
  5689. (org-re-property "\\S-+" 'literal t)
  5690. "Regular expression matching a property line.
  5691. There are four matching groups:
  5692. 1: :PROPKEY: including the leading and trailing colon,
  5693. 2: PROPKEY without the leading and trailing colon,
  5694. 3: PROPVAL without leading or trailing spaces,
  5695. 4: the indentation of the current line,
  5696. 5: trailing whitespace.")
  5697. (defvar org-font-lock-hook nil
  5698. "Functions to be called for special font lock stuff.")
  5699. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5700. (defvar org-font-lock-set-keywords-hook nil
  5701. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5702. This is called after `org-font-lock-extra-keywords' is defined, but before
  5703. it is installed to be used by font lock. This can be useful if something
  5704. needs to be inserted at a specific position in the font-lock sequence.")
  5705. (defun org-font-lock-hook (limit)
  5706. "Run `org-font-lock-hook' within LIMIT."
  5707. (run-hook-with-args 'org-font-lock-hook limit))
  5708. (defun org-set-font-lock-defaults ()
  5709. "Set font lock defaults for the current buffer."
  5710. (let* ((em org-fontify-emphasized-text)
  5711. (lk org-highlight-links)
  5712. (org-font-lock-extra-keywords
  5713. (list
  5714. ;; Call the hook
  5715. '(org-font-lock-hook)
  5716. ;; Headlines
  5717. `(,(if org-fontify-whole-heading-line
  5718. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5719. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5720. (1 (org-get-level-face 1))
  5721. (2 (org-get-level-face 2))
  5722. (3 (org-get-level-face 3)))
  5723. ;; Table lines
  5724. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5725. (1 'org-table t))
  5726. ;; Table internals
  5727. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5728. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5729. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5730. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5731. ;; Drawers
  5732. '(org-fontify-drawers)
  5733. ;; Properties
  5734. (list org-property-re
  5735. '(1 'org-special-keyword t)
  5736. '(3 'org-property-value t))
  5737. ;; Links
  5738. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5739. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5740. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5741. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5742. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5743. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5744. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5745. ;; Targets.
  5746. (list org-any-target-regexp '(0 'org-target t))
  5747. ;; Diary sexps.
  5748. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5749. ;; Macro
  5750. '(org-fontify-macros)
  5751. '(org-hide-wide-columns (0 nil append))
  5752. ;; TODO keyword
  5753. (list (format org-heading-keyword-regexp-format
  5754. org-todo-regexp)
  5755. '(2 (org-get-todo-face 2) t))
  5756. ;; DONE
  5757. (if org-fontify-done-headline
  5758. (list (format org-heading-keyword-regexp-format
  5759. (concat
  5760. "\\(?:"
  5761. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5762. "\\)"))
  5763. '(2 'org-headline-done t))
  5764. nil)
  5765. ;; Priorities
  5766. '(org-font-lock-add-priority-faces)
  5767. ;; Tags
  5768. '(org-font-lock-add-tag-faces)
  5769. ;; Tags groups
  5770. (when (and org-group-tags org-tag-groups-alist)
  5771. (list (concat org-outline-regexp-bol ".+\\(:"
  5772. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5773. ":\\).*$")
  5774. '(1 'org-tag-group prepend)))
  5775. ;; Special keywords
  5776. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5777. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5778. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5779. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5780. ;; Emphasis
  5781. (when em '(org-do-emphasis-faces))
  5782. ;; Checkboxes
  5783. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5784. 1 'org-checkbox prepend)
  5785. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5786. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5787. (0 (org-get-checkbox-statistics-face) t)))
  5788. ;; Description list items
  5789. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5790. 1 'org-list-dt prepend)
  5791. ;; ARCHIVEd headings
  5792. (list (concat
  5793. org-outline-regexp-bol
  5794. "\\(.*:" org-archive-tag ":.*\\)")
  5795. '(1 'org-archived prepend))
  5796. ;; Specials
  5797. '(org-do-latex-and-related)
  5798. '(org-fontify-entities)
  5799. '(org-raise-scripts)
  5800. ;; Code
  5801. '(org-activate-code (1 'org-code t))
  5802. ;; COMMENT
  5803. (list (format
  5804. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5805. org-todo-regexp
  5806. org-comment-string)
  5807. '(9 'org-special-keyword t))
  5808. ;; Blocks and meta lines
  5809. '(org-fontify-meta-lines-and-blocks))))
  5810. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5811. (run-hooks 'org-font-lock-set-keywords-hook)
  5812. ;; Now set the full font-lock-keywords
  5813. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5814. (setq-local font-lock-defaults
  5815. '(org-font-lock-keywords t nil nil backward-paragraph))
  5816. (kill-local-variable 'font-lock-keywords)
  5817. nil))
  5818. (defun org-toggle-pretty-entities ()
  5819. "Toggle the composition display of entities as UTF8 characters."
  5820. (interactive)
  5821. (setq-local org-pretty-entities (not org-pretty-entities))
  5822. (org-restart-font-lock)
  5823. (if org-pretty-entities
  5824. (message "Entities are now displayed as UTF8 characters")
  5825. (save-restriction
  5826. (widen)
  5827. (decompose-region (point-min) (point-max))
  5828. (message "Entities are now displayed as plain text"))))
  5829. (defvar-local org-custom-properties-overlays nil
  5830. "List of overlays used for custom properties.")
  5831. (defun org-toggle-custom-properties-visibility ()
  5832. "Display or hide properties in `org-custom-properties'."
  5833. (interactive)
  5834. (if org-custom-properties-overlays
  5835. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5836. (setq org-custom-properties-overlays nil))
  5837. (when org-custom-properties
  5838. (org-with-wide-buffer
  5839. (goto-char (point-min))
  5840. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5841. (while (re-search-forward regexp nil t)
  5842. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5843. (when (and end (< (point) end))
  5844. ;; Hide first custom property in current drawer.
  5845. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5846. (overlay-put o 'invisible t)
  5847. (overlay-put o 'org-custom-property t)
  5848. (push o org-custom-properties-overlays))
  5849. ;; Hide additional custom properties in the same drawer.
  5850. (while (re-search-forward regexp end t)
  5851. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5852. (overlay-put o 'invisible t)
  5853. (overlay-put o 'org-custom-property t)
  5854. (push o org-custom-properties-overlays)))))
  5855. ;; Each entry is limited to a single property drawer.
  5856. (outline-next-heading)))))))
  5857. (defun org-fontify-entities (limit)
  5858. "Find an entity to fontify."
  5859. (let (ee)
  5860. (when org-pretty-entities
  5861. (catch 'match
  5862. ;; "\_ "-family is left out on purpose. Only the first one,
  5863. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5864. ;; confusing when adding a second white space character.
  5865. (while (re-search-forward
  5866. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5867. limit t)
  5868. (when (and (not (org-at-comment-p))
  5869. (setq ee (org-entity-get (match-string 1)))
  5870. (= (length (nth 6 ee)) 1))
  5871. (let* ((end (if (equal (match-string 2) "{}")
  5872. (match-end 2)
  5873. (match-end 1))))
  5874. (add-text-properties
  5875. (match-beginning 0) end
  5876. (list 'font-lock-fontified t))
  5877. (compose-region (match-beginning 0) end
  5878. (nth 6 ee) nil)
  5879. (backward-char 1)
  5880. (throw 'match t))))
  5881. nil))))
  5882. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5883. "Fontify string S like in Org-mode."
  5884. (with-temp-buffer
  5885. (insert s)
  5886. (let ((org-odd-levels-only odd-levels))
  5887. (org-mode)
  5888. (org-font-lock-ensure)
  5889. (buffer-string))))
  5890. (defvar org-m nil)
  5891. (defvar org-l nil)
  5892. (defvar org-f nil)
  5893. (defun org-get-level-face (n)
  5894. "Get the right face for match N in font-lock matching of headlines."
  5895. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5896. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5897. (if org-cycle-level-faces
  5898. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5899. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5900. (cond
  5901. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5902. ((eq n 2) org-f)
  5903. (t (unless org-level-color-stars-only org-f))))
  5904. (defun org-face-from-face-or-color (context inherit face-or-color)
  5905. "Create a face list that inherits INHERIT, but sets the foreground color.
  5906. When FACE-OR-COLOR is not a string, just return it."
  5907. (if (stringp face-or-color)
  5908. (list :inherit inherit
  5909. (cdr (assoc context org-faces-easy-properties))
  5910. face-or-color)
  5911. face-or-color))
  5912. (defun org-get-todo-face (kwd)
  5913. "Get the right face for a TODO keyword KWD.
  5914. If KWD is a number, get the corresponding match group."
  5915. (when (numberp kwd) (setq kwd (match-string kwd)))
  5916. (or (org-face-from-face-or-color
  5917. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5918. (and (member kwd org-done-keywords) 'org-done)
  5919. 'org-todo))
  5920. (defun org-get-priority-face (priority)
  5921. "Get the right face for PRIORITY.
  5922. PRIORITY is a character."
  5923. (or (org-face-from-face-or-color
  5924. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5925. 'org-priority))
  5926. (defun org-get-tag-face (tag)
  5927. "Get the right face for TAG.
  5928. If TAG is a number, get the corresponding match group."
  5929. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5930. (or (org-face-from-face-or-color
  5931. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5932. 'org-tag)))
  5933. (defun org-font-lock-add-priority-faces (limit)
  5934. "Add the special priority faces."
  5935. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5936. (add-text-properties
  5937. (match-beginning 1) (match-end 1)
  5938. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5939. 'font-lock-fontified t))))
  5940. (defun org-font-lock-add-tag-faces (limit)
  5941. "Add the special tag faces."
  5942. (when (and org-tag-faces org-tags-special-faces-re)
  5943. (while (re-search-forward org-tags-special-faces-re limit t)
  5944. (add-text-properties (match-beginning 1) (match-end 1)
  5945. (list 'face (org-get-tag-face 1)
  5946. 'font-lock-fontified t))
  5947. (backward-char 1))))
  5948. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5949. "Remove fontification and activation overlays from links."
  5950. (font-lock-default-unfontify-region beg end)
  5951. (let* ((buffer-undo-list t)
  5952. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5953. (inhibit-modification-hooks t)
  5954. deactivate-mark buffer-file-name buffer-file-truename)
  5955. (decompose-region beg end)
  5956. (remove-text-properties beg end
  5957. '(mouse-face t keymap t org-linked-text t
  5958. invisible t intangible t
  5959. org-emphasis t))
  5960. (org-remove-font-lock-display-properties beg end)))
  5961. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5962. ((raise 0.3) (height 0.7))
  5963. ((raise -0.5))
  5964. ((raise 0.5)))
  5965. "Display properties for showing superscripts and subscripts.")
  5966. (defun org-remove-font-lock-display-properties (beg end)
  5967. "Remove specific display properties that have been added by font lock.
  5968. The will remove the raise properties that are used to show superscripts
  5969. and subscripts."
  5970. (let (next prop)
  5971. (while (< beg end)
  5972. (setq next (next-single-property-change beg 'display nil end)
  5973. prop (get-text-property beg 'display))
  5974. (when (member prop org-script-display)
  5975. (put-text-property beg next 'display nil))
  5976. (setq beg next))))
  5977. (defun org-raise-scripts (limit)
  5978. "Add raise properties to sub/superscripts."
  5979. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5980. (re-search-forward
  5981. (if (eq org-use-sub-superscripts t)
  5982. org-match-substring-regexp
  5983. org-match-substring-with-braces-regexp)
  5984. limit t))
  5985. (let* ((pos (point)) table-p comment-p
  5986. (mpos (match-beginning 3))
  5987. (emph-p (get-text-property mpos 'org-emphasis))
  5988. (link-p (get-text-property mpos 'mouse-face))
  5989. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5990. (goto-char (point-at-bol))
  5991. (setq table-p (looking-at-p org-table-dataline-regexp)
  5992. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5993. (goto-char pos)
  5994. ;; Handle a_b^c
  5995. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5996. (unless (or comment-p emph-p link-p keyw-p)
  5997. (put-text-property (match-beginning 3) (match-end 0)
  5998. 'display
  5999. (if (equal (char-after (match-beginning 2)) ?^)
  6000. (nth (if table-p 3 1) org-script-display)
  6001. (nth (if table-p 2 0) org-script-display)))
  6002. (add-text-properties (match-beginning 2) (match-end 2)
  6003. (list 'invisible t
  6004. 'org-dwidth t 'org-dwidth-n 1))
  6005. (if (and (eq (char-after (match-beginning 3)) ?{)
  6006. (eq (char-before (match-end 3)) ?}))
  6007. (progn
  6008. (add-text-properties
  6009. (match-beginning 3) (1+ (match-beginning 3))
  6010. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6011. (add-text-properties
  6012. (1- (match-end 3)) (match-end 3)
  6013. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6014. t)))
  6015. ;;;; Visibility cycling, including org-goto and indirect buffer
  6016. ;;; Cycling
  6017. (defvar-local org-cycle-global-status nil)
  6018. (put 'org-cycle-global-status 'org-state t)
  6019. (defvar-local org-cycle-subtree-status nil)
  6020. (put 'org-cycle-subtree-status 'org-state t)
  6021. (defvar org-inlinetask-min-level)
  6022. (defun org-unlogged-message (&rest args)
  6023. "Display a message, but avoid logging it in the *Messages* buffer."
  6024. (let ((message-log-max nil))
  6025. (apply 'message args)))
  6026. ;;;###autoload
  6027. (defun org-cycle (&optional arg)
  6028. "TAB-action and visibility cycling for Org-mode.
  6029. This is the command invoked in Org mode by the TAB key. Its main purpose
  6030. is outline visibility cycling, but it also invokes other actions
  6031. in special contexts.
  6032. - When this function is called with a prefix argument, rotate the entire
  6033. buffer through 3 states (global cycling)
  6034. 1. OVERVIEW: Show only top-level headlines.
  6035. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6036. 3. SHOW ALL: Show everything.
  6037. With a double \\[universal-argument] prefix argument, \
  6038. switch to the startup visibility,
  6039. determined by the variable `org-startup-folded', and by any VISIBILITY
  6040. properties in the buffer.
  6041. With a triple \\[universal-argument] prefix argument, \
  6042. show the entire buffer, including any drawers.
  6043. - When inside a table, re-align the table and move to the next field.
  6044. - When point is at the beginning of a headline, rotate the subtree started
  6045. by this line through 3 different states (local cycling)
  6046. 1. FOLDED: Only the main headline is shown.
  6047. 2. CHILDREN: The main headline and the direct children are shown.
  6048. From this state, you can move to one of the children
  6049. and zoom in further.
  6050. 3. SUBTREE: Show the entire subtree, including body text.
  6051. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6052. - When point is at the beginning of an empty headline and the variable
  6053. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6054. of the headline by demoting and promoting it to likely levels. This
  6055. speeds up creation document structure by pressing TAB once or several
  6056. times right after creating a new headline.
  6057. - When there is a numeric prefix, go up to a heading with level ARG, do
  6058. a `show-subtree' and return to the previous cursor position. If ARG
  6059. is negative, go up that many levels.
  6060. - When point is not at the beginning of a headline, execute the global
  6061. binding for TAB, which is re-indenting the line. See the option
  6062. `org-cycle-emulate-tab' for details.
  6063. - Special case: if point is at the beginning of the buffer and there is
  6064. no headline in line 1, this function will act as if called with prefix arg
  6065. (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
  6066. But only if also the variable `org-cycle-global-at-bob' is t."
  6067. (interactive "P")
  6068. (org-load-modules-maybe)
  6069. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6070. (and org-cycle-level-after-item/entry-creation
  6071. (or (org-cycle-level)
  6072. (org-cycle-item-indentation))))
  6073. (let* ((limit-level
  6074. (or org-cycle-max-level
  6075. (and (boundp 'org-inlinetask-min-level)
  6076. org-inlinetask-min-level
  6077. (1- org-inlinetask-min-level))))
  6078. (nstars (and limit-level
  6079. (if org-odd-levels-only
  6080. (and limit-level (1- (* limit-level 2)))
  6081. limit-level)))
  6082. (org-outline-regexp
  6083. (if (not (derived-mode-p 'org-mode))
  6084. outline-regexp
  6085. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6086. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6087. (not (looking-at org-outline-regexp))))
  6088. (org-cycle-hook
  6089. (if bob-special
  6090. (delq 'org-optimize-window-after-visibility-change
  6091. (copy-sequence org-cycle-hook))
  6092. org-cycle-hook))
  6093. (pos (point)))
  6094. (when (or bob-special (equal arg '(4)))
  6095. ;; special case: use global cycling
  6096. (setq arg t))
  6097. (cond
  6098. ((equal arg '(16))
  6099. (setq last-command 'dummy)
  6100. (org-set-startup-visibility)
  6101. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6102. ((equal arg '(64))
  6103. (outline-show-all)
  6104. (org-unlogged-message "Entire buffer visible, including drawers"))
  6105. ;; Try cdlatex TAB completion
  6106. ((org-try-cdlatex-tab))
  6107. ;; Table: enter it or move to the next field.
  6108. ((org-at-table-p 'any)
  6109. (if (org-at-table.el-p)
  6110. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6111. Use \\[org-edit-special] to edit table.el tables"))
  6112. (if arg (org-table-edit-field t)
  6113. (org-table-justify-field-maybe)
  6114. (call-interactively 'org-table-next-field))))
  6115. ((run-hook-with-args-until-success
  6116. 'org-tab-after-check-for-table-hook))
  6117. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6118. ((eq arg t) (org-cycle-internal-global))
  6119. ;; Drawers: delegate to `org-flag-drawer'.
  6120. ((save-excursion
  6121. (beginning-of-line 1)
  6122. (looking-at org-drawer-regexp))
  6123. (org-flag-drawer ; toggle block visibility
  6124. (not (get-char-property (match-end 0) 'invisible))))
  6125. ;; Show-subtree, ARG levels up from here.
  6126. ((integerp arg)
  6127. (save-excursion
  6128. (org-back-to-heading)
  6129. (outline-up-heading (if (< arg 0) (- arg)
  6130. (- (funcall outline-level) arg)))
  6131. (org-show-subtree)))
  6132. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6133. ((and (featurep 'org-inlinetask)
  6134. (org-inlinetask-at-task-p)
  6135. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6136. (org-inlinetask-toggle-visibility))
  6137. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6138. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6139. (save-excursion (move-beginning-of-line 1)
  6140. (looking-at org-outline-regexp)))
  6141. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6142. (org-cycle-internal-local))
  6143. ;; From there: TAB emulation and template completion.
  6144. (buffer-read-only (org-back-to-heading))
  6145. ((run-hook-with-args-until-success
  6146. 'org-tab-after-check-for-cycling-hook))
  6147. ((org-try-structure-completion))
  6148. ((run-hook-with-args-until-success
  6149. 'org-tab-before-tab-emulation-hook))
  6150. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6151. (or (not (bolp))
  6152. (not (looking-at org-outline-regexp))))
  6153. (call-interactively (global-key-binding "\t")))
  6154. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6155. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6156. (or (and (eq org-cycle-emulate-tab 'white)
  6157. (= (match-end 0) (point-at-eol)))
  6158. (and (eq org-cycle-emulate-tab 'whitestart)
  6159. (>= (match-end 0) pos))))
  6160. t
  6161. (eq org-cycle-emulate-tab t))
  6162. (call-interactively (global-key-binding "\t")))
  6163. (t (save-excursion
  6164. (org-back-to-heading)
  6165. (org-cycle)))))))
  6166. (defun org-cycle-internal-global ()
  6167. "Do the global cycling action."
  6168. ;; Hack to avoid display of messages for .org attachments in Gnus
  6169. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6170. (cond
  6171. ((and (eq last-command this-command)
  6172. (eq org-cycle-global-status 'overview))
  6173. ;; We just created the overview - now do table of contents
  6174. ;; This can be slow in very large buffers, so indicate action
  6175. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6176. (unless ga (org-unlogged-message "CONTENTS..."))
  6177. (org-content)
  6178. (unless ga (org-unlogged-message "CONTENTS...done"))
  6179. (setq org-cycle-global-status 'contents)
  6180. (run-hook-with-args 'org-cycle-hook 'contents))
  6181. ((and (eq last-command this-command)
  6182. (eq org-cycle-global-status 'contents))
  6183. ;; We just showed the table of contents - now show everything
  6184. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6185. (outline-show-all)
  6186. (unless ga (org-unlogged-message "SHOW ALL"))
  6187. (setq org-cycle-global-status 'all)
  6188. (run-hook-with-args 'org-cycle-hook 'all))
  6189. (t
  6190. ;; Default action: go to overview
  6191. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6192. (org-overview)
  6193. (unless ga (org-unlogged-message "OVERVIEW"))
  6194. (setq org-cycle-global-status 'overview)
  6195. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6196. (defvar org-called-with-limited-levels nil
  6197. "Non-nil when `org-with-limited-levels' is currently active.")
  6198. (defun org-cycle-internal-local ()
  6199. "Do the local cycling action."
  6200. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6201. ;; First, determine end of headline (EOH), end of subtree or item
  6202. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6203. (save-excursion
  6204. (if (org-at-item-p)
  6205. (progn
  6206. (beginning-of-line)
  6207. (setq struct (org-list-struct))
  6208. (setq eoh (point-at-eol))
  6209. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6210. (setq has-children (org-list-has-child-p (point) struct)))
  6211. (org-back-to-heading)
  6212. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6213. (setq eos (save-excursion (org-end-of-subtree t t)
  6214. (when (bolp) (backward-char)) (point)))
  6215. (setq has-children
  6216. (or (save-excursion
  6217. (let ((level (funcall outline-level)))
  6218. (outline-next-heading)
  6219. (and (org-at-heading-p t)
  6220. (> (funcall outline-level) level))))
  6221. (save-excursion
  6222. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6223. ;; Determine end invisible part of buffer (EOL)
  6224. (beginning-of-line 2)
  6225. (while (and (not (eobp)) ;This is like `next-line'.
  6226. (get-char-property (1- (point)) 'invisible))
  6227. (goto-char (next-single-char-property-change (point) 'invisible))
  6228. (and (eolp) (beginning-of-line 2)))
  6229. (setq eol (point)))
  6230. ;; Find out what to do next and set `this-command'
  6231. (cond
  6232. ((= eos eoh)
  6233. ;; Nothing is hidden behind this heading
  6234. (unless (org-before-first-heading-p)
  6235. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6236. (org-unlogged-message "EMPTY ENTRY")
  6237. (setq org-cycle-subtree-status nil)
  6238. (save-excursion
  6239. (goto-char eos)
  6240. (outline-next-heading)
  6241. (when (outline-invisible-p) (org-flag-heading nil))))
  6242. ((and (or (>= eol eos)
  6243. (not (string-match "\\S-" (buffer-substring eol eos))))
  6244. (or has-children
  6245. (not (setq children-skipped
  6246. org-cycle-skip-children-state-if-no-children))))
  6247. ;; Entire subtree is hidden in one line: children view
  6248. (unless (org-before-first-heading-p)
  6249. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6250. (if (org-at-item-p)
  6251. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6252. (org-show-entry)
  6253. (org-with-limited-levels (org-show-children))
  6254. ;; FIXME: This slows down the func way too much.
  6255. ;; How keep drawers hidden in subtree anyway?
  6256. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6257. ;; (org-cycle-hide-drawers 'subtree))
  6258. ;; Fold every list in subtree to top-level items.
  6259. (when (eq org-cycle-include-plain-lists 'integrate)
  6260. (save-excursion
  6261. (org-back-to-heading)
  6262. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6263. (beginning-of-line 1)
  6264. (let* ((struct (org-list-struct))
  6265. (prevs (org-list-prevs-alist struct))
  6266. (end (org-list-get-bottom-point struct)))
  6267. (dolist (e (org-list-get-all-items (point) struct prevs))
  6268. (org-list-set-item-visibility e struct 'folded))
  6269. (goto-char (if (< end eos) end eos)))))))
  6270. (org-unlogged-message "CHILDREN")
  6271. (save-excursion
  6272. (goto-char eos)
  6273. (outline-next-heading)
  6274. (when (outline-invisible-p) (org-flag-heading nil)))
  6275. (setq org-cycle-subtree-status 'children)
  6276. (unless (org-before-first-heading-p)
  6277. (run-hook-with-args 'org-cycle-hook 'children)))
  6278. ((or children-skipped
  6279. (and (eq last-command this-command)
  6280. (eq org-cycle-subtree-status 'children)))
  6281. ;; We just showed the children, or no children are there,
  6282. ;; now show everything.
  6283. (unless (org-before-first-heading-p)
  6284. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6285. (outline-flag-region eoh eos nil)
  6286. (org-unlogged-message
  6287. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6288. (setq org-cycle-subtree-status 'subtree)
  6289. (unless (org-before-first-heading-p)
  6290. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6291. (t
  6292. ;; Default action: hide the subtree.
  6293. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6294. (outline-flag-region eoh eos t)
  6295. (org-unlogged-message "FOLDED")
  6296. (setq org-cycle-subtree-status 'folded)
  6297. (unless (org-before-first-heading-p)
  6298. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6299. ;;;###autoload
  6300. (defun org-global-cycle (&optional arg)
  6301. "Cycle the global visibility. For details see `org-cycle'.
  6302. With \\[universal-argument] prefix arg, switch to startup visibility.
  6303. With a numeric prefix, show all headlines up to that level."
  6304. (interactive "P")
  6305. (let ((org-cycle-include-plain-lists
  6306. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6307. (cond
  6308. ((integerp arg)
  6309. (outline-show-all)
  6310. (outline-hide-sublevels arg)
  6311. (setq org-cycle-global-status 'contents))
  6312. ((equal arg '(4))
  6313. (org-set-startup-visibility)
  6314. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6315. (t
  6316. (org-cycle '(4))))))
  6317. (defun org-set-startup-visibility ()
  6318. "Set the visibility required by startup options and properties."
  6319. (cond
  6320. ((eq org-startup-folded t)
  6321. (org-overview))
  6322. ((eq org-startup-folded 'content)
  6323. (org-content))
  6324. ((or (eq org-startup-folded 'showeverything)
  6325. (eq org-startup-folded nil))
  6326. (outline-show-all)))
  6327. (unless (eq org-startup-folded 'showeverything)
  6328. (when org-hide-block-startup (org-hide-block-all))
  6329. (org-set-visibility-according-to-property 'no-cleanup)
  6330. (org-cycle-hide-archived-subtrees 'all)
  6331. (org-cycle-hide-drawers 'all)
  6332. (org-cycle-show-empty-lines t)))
  6333. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6334. "Switch subtree visibilities according to :VISIBILITY: property."
  6335. (interactive)
  6336. (org-with-wide-buffer
  6337. (goto-char (point-min))
  6338. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6339. (if (not (org-at-property-p)) (outline-next-heading)
  6340. (let ((state (match-string 3)))
  6341. (save-excursion
  6342. (org-back-to-heading t)
  6343. (outline-hide-subtree)
  6344. (org-reveal)
  6345. (cond
  6346. ((equal state "folded")
  6347. (outline-hide-subtree))
  6348. ((equal state "children")
  6349. (org-show-hidden-entry)
  6350. (org-show-children))
  6351. ((equal state "content")
  6352. (save-excursion
  6353. (save-restriction
  6354. (org-narrow-to-subtree)
  6355. (org-content))))
  6356. ((member state '("all" "showall"))
  6357. (outline-show-subtree)))))))
  6358. (unless no-cleanup
  6359. (org-cycle-hide-archived-subtrees 'all)
  6360. (org-cycle-hide-drawers 'all)
  6361. (org-cycle-show-empty-lines 'all))))
  6362. ;; This function uses outline-regexp instead of the more fundamental
  6363. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6364. ;; buffers, where outline-regexp is needed.
  6365. (defun org-overview ()
  6366. "Switch to overview mode, showing only top-level headlines.
  6367. This shows all headlines with a level equal or greater than the level
  6368. of the first headline in the buffer. This is important, because if the
  6369. first headline is not level one, then (hide-sublevels 1) gives confusing
  6370. results."
  6371. (interactive)
  6372. (save-excursion
  6373. (let ((level
  6374. (save-excursion
  6375. (goto-char (point-min))
  6376. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6377. (goto-char (match-beginning 0))
  6378. (funcall outline-level)))))
  6379. (and level (outline-hide-sublevels level)))))
  6380. (defun org-content (&optional arg)
  6381. "Show all headlines in the buffer, like a table of contents.
  6382. With numerical argument N, show content up to level N."
  6383. (interactive "P")
  6384. (org-overview)
  6385. (save-excursion
  6386. ;; Visit all headings and show their offspring
  6387. (and (integerp arg) (org-overview))
  6388. (goto-char (point-max))
  6389. (catch 'exit
  6390. (while (and (progn (condition-case nil
  6391. (outline-previous-visible-heading 1)
  6392. (error (goto-char (point-min))))
  6393. t)
  6394. (looking-at org-outline-regexp))
  6395. (if (integerp arg)
  6396. (org-show-children (1- arg))
  6397. (outline-show-branches))
  6398. (when (bobp) (throw 'exit nil))))))
  6399. (defun org-optimize-window-after-visibility-change (state)
  6400. "Adjust the window after a change in outline visibility.
  6401. This function is the default value of the hook `org-cycle-hook'."
  6402. (when (get-buffer-window (current-buffer))
  6403. (cond
  6404. ((eq state 'content) nil)
  6405. ((eq state 'all) nil)
  6406. ((eq state 'folded) nil)
  6407. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6408. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6409. (defun org-remove-empty-overlays-at (pos)
  6410. "Remove outline overlays that do not contain non-white stuff."
  6411. (dolist (o (overlays-at pos))
  6412. (and (eq 'outline (overlay-get o 'invisible))
  6413. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6414. (overlay-end o))))
  6415. (delete-overlay o))))
  6416. (defun org-clean-visibility-after-subtree-move ()
  6417. "Fix visibility issues after moving a subtree."
  6418. ;; First, find a reasonable region to look at:
  6419. ;; Start two siblings above, end three below
  6420. (let* ((beg (save-excursion
  6421. (and (org-get-last-sibling)
  6422. (org-get-last-sibling))
  6423. (point)))
  6424. (end (save-excursion
  6425. (and (org-get-next-sibling)
  6426. (org-get-next-sibling)
  6427. (org-get-next-sibling))
  6428. (if (org-at-heading-p)
  6429. (point-at-eol)
  6430. (point))))
  6431. (level (looking-at "\\*+"))
  6432. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6433. (save-excursion
  6434. (save-restriction
  6435. (narrow-to-region beg end)
  6436. (when re
  6437. ;; Properly fold already folded siblings
  6438. (goto-char (point-min))
  6439. (while (re-search-forward re nil t)
  6440. (when (and (not (outline-invisible-p))
  6441. (save-excursion
  6442. (goto-char (point-at-eol)) (outline-invisible-p)))
  6443. (outline-hide-entry))))
  6444. (org-cycle-show-empty-lines 'overview)
  6445. (org-cycle-hide-drawers 'overview)))))
  6446. (defun org-cycle-show-empty-lines (state)
  6447. "Show empty lines above all visible headlines.
  6448. The region to be covered depends on STATE when called through
  6449. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6450. entire buffer covered. Note that an empty line is only shown if there
  6451. are at least `org-cycle-separator-lines' empty lines before the headline."
  6452. (when (/= org-cycle-separator-lines 0)
  6453. (save-excursion
  6454. (let* ((n (abs org-cycle-separator-lines))
  6455. (re (cond
  6456. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6457. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6458. (t (let ((ns (number-to-string (- n 2))))
  6459. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6460. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6461. beg end)
  6462. (cond
  6463. ((memq state '(overview contents t))
  6464. (setq beg (point-min) end (point-max)))
  6465. ((memq state '(children folded))
  6466. (setq beg (point)
  6467. end (progn (org-end-of-subtree t t)
  6468. (line-beginning-position 2)))))
  6469. (when beg
  6470. (goto-char beg)
  6471. (while (re-search-forward re end t)
  6472. (unless (get-char-property (match-end 1) 'invisible)
  6473. (let ((e (match-end 1))
  6474. (b (if (>= org-cycle-separator-lines 0)
  6475. (match-beginning 1)
  6476. (save-excursion
  6477. (goto-char (match-beginning 0))
  6478. (skip-chars-backward " \t\n")
  6479. (line-end-position)))))
  6480. (outline-flag-region b e nil))))))))
  6481. ;; Never hide empty lines at the end of the file.
  6482. (save-excursion
  6483. (goto-char (point-max))
  6484. (outline-previous-heading)
  6485. (outline-end-of-heading)
  6486. (when (and (looking-at "[ \t\n]+")
  6487. (= (match-end 0) (point-max)))
  6488. (outline-flag-region (point) (match-end 0) nil))))
  6489. (defun org-show-empty-lines-in-parent ()
  6490. "Move to the parent and re-show empty lines before visible headlines."
  6491. (save-excursion
  6492. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6493. (org-cycle-show-empty-lines context))))
  6494. (defun org-files-list ()
  6495. "Return `org-agenda-files' list, plus all open Org files.
  6496. This is useful for operations that need to scan all of a user's
  6497. open and agenda-wise Org files."
  6498. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6499. (dolist (buf (buffer-list))
  6500. (with-current-buffer buf
  6501. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6502. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6503. files))
  6504. (defsubst org-entry-beginning-position ()
  6505. "Return the beginning position of the current entry."
  6506. (save-excursion (org-back-to-heading t) (point)))
  6507. (defsubst org-entry-end-position ()
  6508. "Return the end position of the current entry."
  6509. (save-excursion (outline-next-heading) (point)))
  6510. (defun org-cycle-hide-drawers (state &optional exceptions)
  6511. "Re-hide all drawers after a visibility state change.
  6512. When non-nil, optional argument EXCEPTIONS is a list of strings
  6513. specifying which drawers should not be hidden."
  6514. (when (and (derived-mode-p 'org-mode)
  6515. (not (memq state '(overview folded contents))))
  6516. (save-excursion
  6517. (let* ((globalp (memq state '(contents all)))
  6518. (beg (if globalp (point-min) (point)))
  6519. (end (if globalp (point-max)
  6520. (if (eq state 'children)
  6521. (save-excursion (outline-next-heading) (point))
  6522. (org-end-of-subtree t)))))
  6523. (goto-char beg)
  6524. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6525. (unless (member-ignore-case (match-string 1) exceptions)
  6526. (let ((drawer (org-element-at-point)))
  6527. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6528. (org-flag-drawer t drawer)
  6529. ;; Make sure to skip drawer entirely or we might flag
  6530. ;; it another time when matching its ending line with
  6531. ;; `org-drawer-regexp'.
  6532. (goto-char (org-element-property :end drawer))))))))))
  6533. (defun org-flag-drawer (flag &optional element)
  6534. "When FLAG is non-nil, hide the drawer we are at.
  6535. Otherwise make it visible. When optional argument ELEMENT is
  6536. a parsed drawer, as returned by `org-element-at-point', hide or
  6537. show that drawer instead."
  6538. (let ((drawer (or element
  6539. (and (save-excursion
  6540. (beginning-of-line)
  6541. (looking-at-p org-drawer-regexp))
  6542. (org-element-at-point)))))
  6543. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6544. (let ((post (org-element-property :post-affiliated drawer)))
  6545. (save-excursion
  6546. (outline-flag-region
  6547. (progn (goto-char post) (line-end-position))
  6548. (progn (goto-char (org-element-property :end drawer))
  6549. (skip-chars-backward " \r\t\n")
  6550. (line-end-position))
  6551. flag))
  6552. ;; When the drawer is hidden away, make sure point lies in
  6553. ;; a visible part of the buffer.
  6554. (when (and flag (> (line-beginning-position) post))
  6555. (goto-char post))))))
  6556. (defun org-subtree-end-visible-p ()
  6557. "Is the end of the current subtree visible?"
  6558. (pos-visible-in-window-p
  6559. (save-excursion (org-end-of-subtree t) (point))))
  6560. (defun org-first-headline-recenter ()
  6561. "Move cursor to the first headline and recenter the headline."
  6562. (let ((window (get-buffer-window)))
  6563. (when window
  6564. (goto-char (point-min))
  6565. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6566. (set-window-start window (line-beginning-position))))))
  6567. ;;; Saving and restoring visibility
  6568. (defun org-outline-overlay-data (&optional use-markers)
  6569. "Return a list of the locations of all outline overlays.
  6570. These are overlays with the `invisible' property value `outline'.
  6571. The return value is a list of cons cells, with start and stop
  6572. positions for each overlay.
  6573. If USE-MARKERS is set, return the positions as markers."
  6574. (let (beg end)
  6575. (org-with-wide-buffer
  6576. (delq nil
  6577. (mapcar (lambda (o)
  6578. (when (eq (overlay-get o 'invisible) 'outline)
  6579. (setq beg (overlay-start o)
  6580. end (overlay-end o))
  6581. (and beg end (> end beg)
  6582. (if use-markers
  6583. (cons (copy-marker beg)
  6584. (copy-marker end t))
  6585. (cons beg end)))))
  6586. (overlays-in (point-min) (point-max)))))))
  6587. (defun org-set-outline-overlay-data (data)
  6588. "Create visibility overlays for all positions in DATA.
  6589. DATA should have been made by `org-outline-overlay-data'."
  6590. (org-with-wide-buffer
  6591. (outline-show-all)
  6592. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6593. ;;; Folding of blocks
  6594. (defvar-local org-hide-block-overlays nil
  6595. "Overlays hiding blocks.")
  6596. (defun org-block-map (function &optional start end)
  6597. "Call FUNCTION at the head of all source blocks in the current buffer.
  6598. Optional arguments START and END can be used to limit the range."
  6599. (let ((start (or start (point-min)))
  6600. (end (or end (point-max))))
  6601. (save-excursion
  6602. (goto-char start)
  6603. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6604. (save-excursion
  6605. (save-match-data
  6606. (goto-char (match-beginning 0))
  6607. (funcall function)))))))
  6608. (defun org-hide-block-toggle-all ()
  6609. "Toggle the visibility of all blocks in the current buffer."
  6610. (org-block-map 'org-hide-block-toggle))
  6611. (defun org-hide-block-all ()
  6612. "Fold all blocks in the current buffer."
  6613. (interactive)
  6614. (org-show-block-all)
  6615. (org-block-map 'org-hide-block-toggle-maybe))
  6616. (defun org-show-block-all ()
  6617. "Unfold all blocks in the current buffer."
  6618. (interactive)
  6619. (mapc #'delete-overlay org-hide-block-overlays)
  6620. (setq org-hide-block-overlays nil))
  6621. (defun org-hide-block-toggle-maybe ()
  6622. "Toggle visibility of block at point.
  6623. Unlike to `org-hide-block-toggle', this function does not throw
  6624. an error. Return a non-nil value when toggling is successful."
  6625. (interactive)
  6626. (ignore-errors (org-hide-block-toggle)))
  6627. (defun org-hide-block-toggle (&optional force)
  6628. "Toggle the visibility of the current block.
  6629. When optional argument FORCE is `off', make block visible. If it
  6630. is non-nil, hide it unconditionally. Throw an error when not at
  6631. a block. Return a non-nil value when toggling is successful."
  6632. (interactive)
  6633. (let ((element (org-element-at-point)))
  6634. (unless (memq (org-element-type element)
  6635. '(center-block comment-block dynamic-block example-block
  6636. export-block quote-block special-block
  6637. src-block verse-block))
  6638. (user-error "Not at a block"))
  6639. (let* ((start (save-excursion
  6640. (goto-char (org-element-property :post-affiliated element))
  6641. (line-end-position)))
  6642. (end (save-excursion
  6643. (goto-char (org-element-property :end element))
  6644. (skip-chars-backward " \r\t\n")
  6645. (line-end-position)))
  6646. (overlays (overlays-at start)))
  6647. (cond
  6648. ;; Do nothing when not before or at the block opening line or
  6649. ;; at the block closing line.
  6650. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6651. ((and (not (eq force 'off))
  6652. (not (memq t (mapcar
  6653. (lambda (o)
  6654. (eq (overlay-get o 'invisible) 'org-hide-block))
  6655. overlays))))
  6656. (let ((ov (make-overlay start end)))
  6657. (overlay-put ov 'invisible 'org-hide-block)
  6658. ;; Make the block accessible to `isearch'.
  6659. (overlay-put
  6660. ov 'isearch-open-invisible
  6661. (lambda (ov)
  6662. (when (memq ov org-hide-block-overlays)
  6663. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6664. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6665. (delete-overlay ov))))
  6666. (push ov org-hide-block-overlays)
  6667. ;; When the block is hidden away, make sure point is left in
  6668. ;; a visible part of the buffer.
  6669. (when (> (line-beginning-position) start)
  6670. (goto-char start)
  6671. (beginning-of-line))
  6672. ;; Signal successful toggling.
  6673. t))
  6674. ((or (not force) (eq force 'off))
  6675. (dolist (ov overlays t)
  6676. (when (memq ov org-hide-block-overlays)
  6677. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6678. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6679. (delete-overlay ov))))))))
  6680. ;; org-tab-after-check-for-cycling-hook
  6681. (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
  6682. ;; Remove overlays when changing major mode
  6683. (add-hook 'org-mode-hook
  6684. (lambda () (add-hook 'change-major-mode-hook
  6685. 'org-show-block-all 'append 'local)))
  6686. ;;; Org-goto
  6687. (defvar org-goto-window-configuration nil)
  6688. (defvar org-goto-marker nil)
  6689. (defvar org-goto-map)
  6690. (defun org-goto-map ()
  6691. "Set the keymap `org-goto'."
  6692. (setq org-goto-map
  6693. (let ((map (make-sparse-keymap)))
  6694. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6695. mouse-drag-region universal-argument org-occur)))
  6696. (dolist (cmd cmds)
  6697. (substitute-key-definition cmd cmd map global-map)))
  6698. (suppress-keymap map)
  6699. (org-defkey map "\C-m" 'org-goto-ret)
  6700. (org-defkey map [(return)] 'org-goto-ret)
  6701. (org-defkey map [(left)] 'org-goto-left)
  6702. (org-defkey map [(right)] 'org-goto-right)
  6703. (org-defkey map [(control ?g)] 'org-goto-quit)
  6704. (org-defkey map "\C-i" 'org-cycle)
  6705. (org-defkey map [(tab)] 'org-cycle)
  6706. (org-defkey map [(down)] 'outline-next-visible-heading)
  6707. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6708. (if org-goto-auto-isearch
  6709. (if (fboundp 'define-key-after)
  6710. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6711. nil)
  6712. (org-defkey map "q" 'org-goto-quit)
  6713. (org-defkey map "n" 'outline-next-visible-heading)
  6714. (org-defkey map "p" 'outline-previous-visible-heading)
  6715. (org-defkey map "f" 'outline-forward-same-level)
  6716. (org-defkey map "b" 'outline-backward-same-level)
  6717. (org-defkey map "u" 'outline-up-heading))
  6718. (org-defkey map "/" 'org-occur)
  6719. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6720. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6721. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6722. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6723. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6724. map)))
  6725. (defconst org-goto-help
  6726. "Browse buffer copy, to find location or copy text.%s
  6727. RET=jump to location C-g=quit and return to previous location
  6728. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6729. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6730. (defun org-goto (&optional alternative-interface)
  6731. "Look up a different location in the current file, keeping current visibility.
  6732. When you want look-up or go to a different location in a
  6733. document, the fastest way is often to fold the entire buffer and
  6734. then dive into the tree. This method has the disadvantage, that
  6735. the previous location will be folded, which may not be what you
  6736. want.
  6737. This command works around this by showing a copy of the current
  6738. buffer in an indirect buffer, in overview mode. You can dive
  6739. into the tree in that copy, use org-occur and incremental search
  6740. to find a location. When pressing RET or `Q', the command
  6741. returns to the original buffer in which the visibility is still
  6742. unchanged. After RET it will also jump to the location selected
  6743. in the indirect buffer and expose the headline hierarchy above.
  6744. With a prefix argument, use the alternative interface: e.g., if
  6745. `org-goto-interface' is `outline' use `outline-path-completion'."
  6746. (interactive "P")
  6747. (org-goto-map)
  6748. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6749. (org-refile-use-outline-path t)
  6750. (org-refile-target-verify-function nil)
  6751. (interface
  6752. (if (not alternative-interface)
  6753. org-goto-interface
  6754. (if (eq org-goto-interface 'outline)
  6755. 'outline-path-completion
  6756. 'outline)))
  6757. (org-goto-start-pos (point))
  6758. (selected-point
  6759. (if (eq interface 'outline)
  6760. (car (org-get-location (current-buffer) org-goto-help))
  6761. (let ((pa (org-refile-get-location "Goto")))
  6762. (org-refile-check-position pa)
  6763. (nth 3 pa)))))
  6764. (if selected-point
  6765. (progn
  6766. (org-mark-ring-push org-goto-start-pos)
  6767. (goto-char selected-point)
  6768. (when (or (outline-invisible-p) (org-invisible-p2))
  6769. (org-show-context 'org-goto)))
  6770. (message "Quit"))))
  6771. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6772. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6773. (defvar org-goto-local-auto-isearch-map) ; defined below
  6774. (defun org-get-location (_buf help)
  6775. "Let the user select a location in current buffer.
  6776. This function uses a recursive edit. It returns the selected position
  6777. or nil."
  6778. (org-no-popups
  6779. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6780. (isearch-hide-immediately nil)
  6781. (isearch-search-fun-function
  6782. (lambda () 'org-goto-local-search-headings))
  6783. (org-goto-selected-point org-goto-exit-command))
  6784. (save-excursion
  6785. (save-window-excursion
  6786. (delete-other-windows)
  6787. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6788. (pop-to-buffer-same-window
  6789. (condition-case nil
  6790. (make-indirect-buffer (current-buffer) "*org-goto*")
  6791. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6792. (with-output-to-temp-buffer "*Org Help*"
  6793. (princ (format help (if org-goto-auto-isearch
  6794. " Just type for auto-isearch."
  6795. " n/p/f/b/u to navigate, q to quit."))))
  6796. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6797. (setq buffer-read-only nil)
  6798. (let ((org-startup-truncated t)
  6799. (org-startup-folded nil)
  6800. (org-startup-align-all-tables nil))
  6801. (org-mode)
  6802. (org-overview))
  6803. (setq buffer-read-only t)
  6804. (if (and (boundp 'org-goto-start-pos)
  6805. (integer-or-marker-p org-goto-start-pos))
  6806. (progn (goto-char org-goto-start-pos)
  6807. (when (outline-invisible-p)
  6808. (org-show-set-visibility 'lineage)))
  6809. (goto-char (point-min)))
  6810. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6811. (message "Select location and press RET")
  6812. (use-local-map org-goto-map)
  6813. (recursive-edit)))
  6814. (kill-buffer "*org-goto*")
  6815. (cons org-goto-selected-point org-goto-exit-command))))
  6816. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6817. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6818. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6819. (if (fboundp 'isearch-other-control-char)
  6820. (progn
  6821. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6822. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6823. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6824. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6825. (define-key org-goto-local-auto-isearch-map [return] nil))
  6826. (defun org-goto-local-search-headings (string bound noerror)
  6827. "Search and make sure that any matches are in headlines."
  6828. (catch 'return
  6829. (while (if isearch-forward
  6830. (search-forward string bound noerror)
  6831. (search-backward string bound noerror))
  6832. (when (save-match-data
  6833. (and (save-excursion
  6834. (beginning-of-line)
  6835. (looking-at org-complex-heading-regexp))
  6836. (or (not (match-beginning 5))
  6837. (< (point) (match-beginning 5)))))
  6838. (throw 'return (point))))))
  6839. (defun org-goto-local-auto-isearch ()
  6840. "Start isearch."
  6841. (interactive)
  6842. (goto-char (point-min))
  6843. (let ((keys (this-command-keys)))
  6844. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6845. (isearch-mode t)
  6846. (isearch-process-search-char (string-to-char keys)))))
  6847. (defun org-goto-ret (&optional _arg)
  6848. "Finish `org-goto' by going to the new location."
  6849. (interactive "P")
  6850. (setq org-goto-selected-point (point))
  6851. (setq org-goto-exit-command 'return)
  6852. (throw 'exit nil))
  6853. (defun org-goto-left ()
  6854. "Finish `org-goto' by going to the new location."
  6855. (interactive)
  6856. (if (org-at-heading-p)
  6857. (progn
  6858. (beginning-of-line 1)
  6859. (setq org-goto-selected-point (point)
  6860. org-goto-exit-command 'left)
  6861. (throw 'exit nil))
  6862. (user-error "Not on a heading")))
  6863. (defun org-goto-right ()
  6864. "Finish `org-goto' by going to the new location."
  6865. (interactive)
  6866. (if (org-at-heading-p)
  6867. (progn
  6868. (setq org-goto-selected-point (point)
  6869. org-goto-exit-command 'right)
  6870. (throw 'exit nil))
  6871. (user-error "Not on a heading")))
  6872. (defun org-goto-quit ()
  6873. "Finish `org-goto' without cursor motion."
  6874. (interactive)
  6875. (setq org-goto-selected-point nil)
  6876. (setq org-goto-exit-command 'quit)
  6877. (throw 'exit nil))
  6878. ;;; Indirect buffer display of subtrees
  6879. (defvar org-indirect-dedicated-frame nil
  6880. "This is the frame being used for indirect tree display.")
  6881. (defvar org-last-indirect-buffer nil)
  6882. (defun org-tree-to-indirect-buffer (&optional arg)
  6883. "Create indirect buffer and narrow it to current subtree.
  6884. With a numerical prefix ARG, go up to this level and then take that tree.
  6885. If ARG is negative, go up that many levels.
  6886. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6887. indirect buffer previously made with this command, to avoid proliferation of
  6888. indirect buffers. However, when you call the command with a \
  6889. \\[universal-argument] prefix, or
  6890. when `org-indirect-buffer-display' is `new-frame', the last buffer
  6891. is kept so that you can work with several indirect buffers at the same time.
  6892. If `org-indirect-buffer-display' is `dedicated-frame', the \
  6893. \\[universal-argument] prefix also
  6894. requests that a new frame be made for the new buffer, so that the dedicated
  6895. frame is not changed."
  6896. (interactive "P")
  6897. (let ((cbuf (current-buffer))
  6898. (cwin (selected-window))
  6899. (pos (point))
  6900. beg end level heading ibuf)
  6901. (save-excursion
  6902. (org-back-to-heading t)
  6903. (when (numberp arg)
  6904. (setq level (org-outline-level))
  6905. (when (< arg 0) (setq arg (+ level arg)))
  6906. (while (> (setq level (org-outline-level)) arg)
  6907. (org-up-heading-safe)))
  6908. (setq beg (point)
  6909. heading (org-get-heading 'no-tags))
  6910. (org-end-of-subtree t t)
  6911. (when (org-at-heading-p) (backward-char 1))
  6912. (setq end (point)))
  6913. (when (and (buffer-live-p org-last-indirect-buffer)
  6914. (not (eq org-indirect-buffer-display 'new-frame))
  6915. (not arg))
  6916. (kill-buffer org-last-indirect-buffer))
  6917. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6918. org-last-indirect-buffer ibuf)
  6919. (cond
  6920. ((or (eq org-indirect-buffer-display 'new-frame)
  6921. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6922. (select-frame (make-frame))
  6923. (delete-other-windows)
  6924. (pop-to-buffer-same-window ibuf)
  6925. (org-set-frame-title heading))
  6926. ((eq org-indirect-buffer-display 'dedicated-frame)
  6927. (raise-frame
  6928. (select-frame (or (and org-indirect-dedicated-frame
  6929. (frame-live-p org-indirect-dedicated-frame)
  6930. org-indirect-dedicated-frame)
  6931. (setq org-indirect-dedicated-frame (make-frame)))))
  6932. (delete-other-windows)
  6933. (pop-to-buffer-same-window ibuf)
  6934. (org-set-frame-title (concat "Indirect: " heading)))
  6935. ((eq org-indirect-buffer-display 'current-window)
  6936. (pop-to-buffer-same-window ibuf))
  6937. ((eq org-indirect-buffer-display 'other-window)
  6938. (pop-to-buffer ibuf))
  6939. (t (error "Invalid value")))
  6940. (narrow-to-region beg end)
  6941. (outline-show-all)
  6942. (goto-char pos)
  6943. (run-hook-with-args 'org-cycle-hook 'all)
  6944. (and (window-live-p cwin) (select-window cwin))))
  6945. (defun org-get-indirect-buffer (&optional buffer heading)
  6946. (setq buffer (or buffer (current-buffer)))
  6947. (let ((n 1) (base (buffer-name buffer)) bname)
  6948. (while (buffer-live-p
  6949. (get-buffer
  6950. (setq bname
  6951. (concat base "-"
  6952. (if heading (concat heading "-" (number-to-string n))
  6953. (number-to-string n))))))
  6954. (setq n (1+ n)))
  6955. (condition-case nil
  6956. (make-indirect-buffer buffer bname 'clone)
  6957. (error (make-indirect-buffer buffer bname)))))
  6958. (defun org-set-frame-title (title)
  6959. "Set the title of the current frame to the string TITLE."
  6960. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6961. ;;;; Structure editing
  6962. ;;; Inserting headlines
  6963. (defun org--line-empty-p (n)
  6964. "Is the Nth next line empty?
  6965. Counts the current line as N = 1 and the previous line as N = 0;
  6966. see `beginning-of-line'."
  6967. (save-excursion
  6968. (and (not (bobp))
  6969. (or (beginning-of-line n) t)
  6970. (save-match-data
  6971. (looking-at "[ \t]*$")))))
  6972. (defun org-previous-line-empty-p ()
  6973. "Is the previous line a blank line?
  6974. When NEXT is non-nil, check the next line instead."
  6975. (org--line-empty-p 0))
  6976. (defun org-next-line-empty-p ()
  6977. "Is the previous line a blank line?
  6978. When NEXT is non-nil, check the next line instead."
  6979. (org--line-empty-p 2))
  6980. (defun org-insert-heading (&optional arg invisible-ok top)
  6981. "Insert a new heading or an item with the same depth at point.
  6982. If point is at the beginning of a heading or a list item, insert
  6983. a new heading or a new item above the current one. If point is
  6984. at the beginning of a normal line, turn the line into a heading.
  6985. If point is in the middle of a line, split it and create a new
  6986. headline/item with the text in the current line after point (see
  6987. `org-M-RET-may-split-line' on how to modify this behavior).
  6988. If point is at the beginning of the headline, insert a sibling
  6989. before it. If it is at the beginning of a regular line of text,
  6990. turn it into a heading.
  6991. With one universal prefix argument, set the user option
  6992. `org-insert-heading-respect-content' to t for the duration of the
  6993. command. This modifies the behavior described above in this
  6994. ways: on list items and at regular lines, force the insertion of
  6995. a heading after the current subtree.
  6996. With two universal prefix arguments, insert the heading at the
  6997. end of the grandparent subtree. For example, if point is within
  6998. a 2nd-level heading, then it will insert a 2nd-level heading at
  6999. the end of the 1st-level parent heading.
  7000. When INVISIBLE-OK is set, stop at invisible headlines when going
  7001. back. This is important for non-interactive uses of the
  7002. command.
  7003. When optional argument TOP is non-nil, insert a level 1 heading,
  7004. unconditionally."
  7005. (interactive "P")
  7006. (let ((itemp (and (not top) (org-in-item-p)))
  7007. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7008. (respect-content (or org-insert-heading-respect-content
  7009. (equal arg '(4))))
  7010. (initial-content ""))
  7011. (cond
  7012. ((or (= (buffer-size) 0)
  7013. (and (not (save-excursion
  7014. (and (ignore-errors (org-back-to-heading invisible-ok))
  7015. (org-at-heading-p))))
  7016. (or arg (not itemp))))
  7017. ;; At beginning of buffer or so high up that only a heading
  7018. ;; makes sense.
  7019. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7020. ((not respect-content)
  7021. (unless may-split (end-of-line))
  7022. (insert "\n* "))
  7023. ((re-search-forward org-outline-regexp-bol nil t)
  7024. (beginning-of-line)
  7025. (insert "* \n")
  7026. (backward-char))
  7027. (t (goto-char (point-max))
  7028. (insert "\n* ")))
  7029. (run-hooks 'org-insert-heading-hook))
  7030. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7031. (t
  7032. ;; Maybe move at the end of the subtree
  7033. (when (equal arg '(16))
  7034. (org-up-heading-safe)
  7035. (org-end-of-subtree t))
  7036. ;; Insert a heading
  7037. (save-restriction
  7038. (widen)
  7039. (let* ((level nil)
  7040. (on-heading (org-at-heading-p))
  7041. (empty-line-p (if on-heading
  7042. (org-previous-line-empty-p)
  7043. ;; We will decide later
  7044. nil))
  7045. ;; Get a level string to fall back on.
  7046. (fix-level
  7047. (if (org-before-first-heading-p) "*"
  7048. (save-excursion
  7049. (org-back-to-heading t)
  7050. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7051. (looking-at org-outline-regexp)
  7052. (make-string (1- (length (match-string 0))) ?*))))
  7053. (stars
  7054. (save-excursion
  7055. (condition-case nil
  7056. (if top "* "
  7057. (org-back-to-heading invisible-ok)
  7058. (when (and (not on-heading)
  7059. (featurep 'org-inlinetask)
  7060. (integerp org-inlinetask-min-level)
  7061. (>= (length (match-string 0))
  7062. org-inlinetask-min-level))
  7063. ;; Find a heading level before the inline
  7064. ;; task.
  7065. (while (and (setq level (org-up-heading-safe))
  7066. (>= level org-inlinetask-min-level)))
  7067. (if (org-at-heading-p)
  7068. (org-back-to-heading invisible-ok)
  7069. (error "This should not happen")))
  7070. (unless (and (save-excursion
  7071. (save-match-data
  7072. (org-backward-heading-same-level
  7073. 1 invisible-ok))
  7074. (= (point) (match-beginning 0)))
  7075. (not (org-next-line-empty-p)))
  7076. (setq empty-line-p (or empty-line-p
  7077. (org-previous-line-empty-p))))
  7078. (match-string 0))
  7079. (error (or fix-level "* ")))))
  7080. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7081. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7082. ;; If we insert after content, move there and clean up
  7083. ;; whitespace.
  7084. (when (and respect-content
  7085. (not (looking-at-p org-outline-regexp-bol)))
  7086. (if (not (org-before-first-heading-p))
  7087. (org-end-of-subtree nil t)
  7088. (re-search-forward org-outline-regexp-bol)
  7089. (beginning-of-line 0))
  7090. (skip-chars-backward " \r\t\n")
  7091. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7092. (looking-at "[ \t]+") (replace-match ""))
  7093. (unless (eobp) (forward-char 1))
  7094. (when (looking-at "^\\*")
  7095. (unless (bobp) (backward-char 1))
  7096. (insert "\n")))
  7097. ;; If we are splitting, grab the text that should be moved
  7098. ;; to the new headline.
  7099. (when may-split
  7100. (if (org-at-heading-p)
  7101. ;; This is a heading: split intelligently (keeping
  7102. ;; tags).
  7103. (let ((pos (point)))
  7104. (beginning-of-line)
  7105. (unless (looking-at org-complex-heading-regexp)
  7106. (error "This should not happen"))
  7107. (when (and (match-beginning 4)
  7108. (> pos (match-beginning 4))
  7109. (< pos (match-end 4)))
  7110. (setq initial-content (buffer-substring pos (match-end 4)))
  7111. (goto-char pos)
  7112. (delete-region (point) (match-end 4))
  7113. (if (looking-at "[ \t]*$")
  7114. (replace-match "")
  7115. (insert (make-string (length initial-content) ?\s)))
  7116. (setq initial-content (org-trim initial-content)))
  7117. (goto-char pos))
  7118. ;; A normal line.
  7119. (setq initial-content
  7120. (org-trim
  7121. (delete-and-extract-region (point) (line-end-position))))))
  7122. ;; If we are at the beginning of the line, insert before it.
  7123. ;; Otherwise, after it.
  7124. (cond
  7125. ((and (bolp) (looking-at "[ \t]*$")))
  7126. ((bolp) (save-excursion (insert "\n")))
  7127. (t (end-of-line)
  7128. (insert "\n")))
  7129. ;; Insert the new heading
  7130. (insert stars)
  7131. (just-one-space)
  7132. (insert initial-content)
  7133. (unless (and blank (org-previous-line-empty-p))
  7134. (org-N-empty-lines-before-current (if blank 1 0)))
  7135. ;; Adjust visibility, which may be messed up if we removed
  7136. ;; blank lines while previous entry was hidden.
  7137. (let ((bol (line-beginning-position)))
  7138. (dolist (o (overlays-at (1- bol)))
  7139. (when (and (eq (overlay-get o 'invisible) 'outline)
  7140. (eq (overlay-end o) bol))
  7141. (move-overlay o (overlay-start o) (1- bol)))))
  7142. (run-hooks 'org-insert-heading-hook)))))))
  7143. (defun org-N-empty-lines-before-current (N)
  7144. "Make the number of empty lines before current exactly N.
  7145. So this will delete or add empty lines."
  7146. (save-excursion
  7147. (beginning-of-line)
  7148. (let ((p (point)))
  7149. (skip-chars-backward " \r\t\n")
  7150. (unless (bolp) (forward-line))
  7151. (delete-region (point) p))
  7152. (when (> N 0) (insert (make-string N ?\n)))))
  7153. (defun org-get-heading (&optional no-tags no-todo)
  7154. "Return the heading of the current entry, without the stars.
  7155. When NO-TAGS is non-nil, don't include tags.
  7156. When NO-TODO is non-nil, don't include TODO keywords."
  7157. (save-excursion
  7158. (org-back-to-heading t)
  7159. (let ((case-fold-search nil))
  7160. (cond
  7161. ((and no-tags no-todo)
  7162. (looking-at org-complex-heading-regexp)
  7163. ;; Return value has to be a string, but match group 4 is
  7164. ;; optional.
  7165. (or (match-string 4) ""))
  7166. (no-tags
  7167. (looking-at (concat org-outline-regexp
  7168. "\\(.*?\\)"
  7169. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7170. (match-string 1))
  7171. (no-todo
  7172. (looking-at org-todo-line-regexp)
  7173. (match-string 3))
  7174. (t (looking-at org-heading-regexp)
  7175. (match-string 2))))))
  7176. (defvar orgstruct-mode) ; defined below
  7177. (defun org-heading-components ()
  7178. "Return the components of the current heading.
  7179. This is a list with the following elements:
  7180. - the level as an integer
  7181. - the reduced level, different if `org-odd-levels-only' is set.
  7182. - the TODO keyword, or nil
  7183. - the priority character, like ?A, or nil if no priority is given
  7184. - the headline text itself, or the tags string if no headline text
  7185. - the tags string, or nil."
  7186. (save-excursion
  7187. (org-back-to-heading t)
  7188. (when (let (case-fold-search)
  7189. (looking-at
  7190. (if orgstruct-mode
  7191. org-heading-regexp
  7192. org-complex-heading-regexp)))
  7193. (if orgstruct-mode
  7194. (list (length (match-string 1))
  7195. (org-reduced-level (length (match-string 1)))
  7196. nil
  7197. nil
  7198. (match-string 2)
  7199. nil)
  7200. (list (length (match-string 1))
  7201. (org-reduced-level (length (match-string 1)))
  7202. (match-string-no-properties 2)
  7203. (and (match-end 3) (aref (match-string 3) 2))
  7204. (match-string-no-properties 4)
  7205. (match-string-no-properties 5))))))
  7206. (defun org-get-entry ()
  7207. "Get the entry text, after heading, entire subtree."
  7208. (save-excursion
  7209. (org-back-to-heading t)
  7210. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7211. (defun org-edit-headline (&optional heading)
  7212. "Edit the current headline.
  7213. Set it to HEADING when provided."
  7214. (interactive)
  7215. (org-with-wide-buffer
  7216. (org-back-to-heading t)
  7217. (when (looking-at org-complex-heading-regexp)
  7218. (let* ((old (match-string-no-properties 4))
  7219. (new (save-match-data
  7220. (org-trim (or heading (read-string "Edit: " old))))))
  7221. (unless (equal old new)
  7222. (if old (replace-match new t t nil 4)
  7223. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7224. (insert " " new))
  7225. (org-set-tags nil t)
  7226. (when (looking-at "[ \t]*$") (replace-match "")))))))
  7227. (defun org-insert-heading-after-current ()
  7228. "Insert a new heading with same level as current, after current subtree."
  7229. (interactive)
  7230. (org-back-to-heading)
  7231. (org-insert-heading)
  7232. (org-move-subtree-down)
  7233. (end-of-line 1))
  7234. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7235. "Insert heading with `org-insert-heading-respect-content' set to t."
  7236. (interactive)
  7237. (org-insert-heading '(4) invisible-ok))
  7238. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7239. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7240. (interactive)
  7241. (org-insert-todo-heading force-state '(4)))
  7242. (defun org-insert-todo-heading (arg &optional force-heading)
  7243. "Insert a new heading with the same level and TODO state as current heading.
  7244. If the heading has no TODO state, or if the state is DONE, use
  7245. the first state (TODO by default). Also with one prefix arg,
  7246. force first state. With two prefix args, force inserting at the
  7247. end of the parent subtree.
  7248. When called at a plain list item, insert a new item with an
  7249. unchecked check box."
  7250. (interactive "P")
  7251. (when (or force-heading (not (org-insert-item 'checkbox)))
  7252. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7253. force-heading))
  7254. (save-excursion
  7255. (org-back-to-heading)
  7256. (outline-previous-heading)
  7257. (looking-at org-todo-line-regexp))
  7258. (let* ((new-mark-x
  7259. (if (or (equal arg '(4))
  7260. (not (match-beginning 2))
  7261. (member (match-string 2) org-done-keywords))
  7262. (car org-todo-keywords-1)
  7263. (match-string 2)))
  7264. (new-mark
  7265. (or
  7266. (run-hook-with-args-until-success
  7267. 'org-todo-get-default-hook new-mark-x nil)
  7268. new-mark-x)))
  7269. (beginning-of-line 1)
  7270. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7271. (if org-treat-insert-todo-heading-as-state-change
  7272. (org-todo new-mark)
  7273. (insert new-mark " "))))
  7274. (when org-provide-todo-statistics
  7275. (org-update-parent-todo-statistics))))
  7276. (defun org-insert-subheading (arg)
  7277. "Insert a new subheading and demote it.
  7278. Works for outline headings and for plain lists alike."
  7279. (interactive "P")
  7280. (org-insert-heading arg)
  7281. (cond
  7282. ((org-at-heading-p) (org-do-demote))
  7283. ((org-at-item-p) (org-indent-item))))
  7284. (defun org-insert-todo-subheading (arg)
  7285. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7286. Works for outline headings and for plain lists alike."
  7287. (interactive "P")
  7288. (org-insert-todo-heading arg)
  7289. (cond
  7290. ((org-at-heading-p) (org-do-demote))
  7291. ((org-at-item-p) (org-indent-item))))
  7292. ;;; Promotion and Demotion
  7293. (defvar org-after-demote-entry-hook nil
  7294. "Hook run after an entry has been demoted.
  7295. The cursor will be at the beginning of the entry.
  7296. When a subtree is being demoted, the hook will be called for each node.")
  7297. (defvar org-after-promote-entry-hook nil
  7298. "Hook run after an entry has been promoted.
  7299. The cursor will be at the beginning of the entry.
  7300. When a subtree is being promoted, the hook will be called for each node.")
  7301. (defun org-promote-subtree ()
  7302. "Promote the entire subtree.
  7303. See also `org-promote'."
  7304. (interactive)
  7305. (save-excursion
  7306. (org-with-limited-levels (org-map-tree 'org-promote)))
  7307. (org-fix-position-after-promote))
  7308. (defun org-demote-subtree ()
  7309. "Demote the entire subtree.
  7310. See `org-demote' and `org-promote'."
  7311. (interactive)
  7312. (save-excursion
  7313. (org-with-limited-levels (org-map-tree 'org-demote)))
  7314. (org-fix-position-after-promote))
  7315. (defun org-do-promote ()
  7316. "Promote the current heading higher up the tree.
  7317. If the region is active in `transient-mark-mode', promote all
  7318. headings in the region."
  7319. (interactive)
  7320. (save-excursion
  7321. (if (org-region-active-p)
  7322. (org-map-region 'org-promote (region-beginning) (region-end))
  7323. (org-promote)))
  7324. (org-fix-position-after-promote))
  7325. (defun org-do-demote ()
  7326. "Demote the current heading lower down the tree.
  7327. If the region is active in `transient-mark-mode', demote all
  7328. headings in the region."
  7329. (interactive)
  7330. (save-excursion
  7331. (if (org-region-active-p)
  7332. (org-map-region 'org-demote (region-beginning) (region-end))
  7333. (org-demote)))
  7334. (org-fix-position-after-promote))
  7335. (defun org-fix-position-after-promote ()
  7336. "Fix cursor position and indentation after demoting/promoting."
  7337. (let ((pos (point)))
  7338. (when (save-excursion
  7339. (beginning-of-line 1)
  7340. (looking-at org-todo-line-regexp)
  7341. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7342. (cond ((eobp) (insert " "))
  7343. ((eolp) (insert " "))
  7344. ((equal (char-after) ?\ ) (forward-char 1))))))
  7345. (defun org-current-level ()
  7346. "Return the level of the current entry, or nil if before the first headline.
  7347. The level is the number of stars at the beginning of the
  7348. headline. Use `org-reduced-level' to remove the effect of
  7349. `org-odd-levels'. Unlike to `org-outline-level', this function
  7350. ignores inlinetasks."
  7351. (let ((level (org-with-limited-levels (org-outline-level))))
  7352. (and (> level 0) level)))
  7353. (defun org-get-previous-line-level ()
  7354. "Return the outline depth of the last headline before the current line.
  7355. Returns 0 for the first headline in the buffer, and nil if before the
  7356. first headline."
  7357. (and (org-current-level)
  7358. (or (and (/= (line-beginning-position) (point-min))
  7359. (save-excursion (beginning-of-line 0) (org-current-level)))
  7360. 0)))
  7361. (defun org-reduced-level (l)
  7362. "Compute the effective level of a heading.
  7363. This takes into account the setting of `org-odd-levels-only'."
  7364. (cond
  7365. ((zerop l) 0)
  7366. (org-odd-levels-only (1+ (floor (/ l 2))))
  7367. (t l)))
  7368. (defun org-level-increment ()
  7369. "Return the number of stars that will be added or removed at a
  7370. time to headlines when structure editing, based on the value of
  7371. `org-odd-levels-only'."
  7372. (if org-odd-levels-only 2 1))
  7373. (defun org-get-valid-level (level &optional change)
  7374. "Rectify a level change under the influence of `org-odd-levels-only'
  7375. LEVEL is a current level, CHANGE is by how much the level should be
  7376. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7377. even level numbers will become the next higher odd number."
  7378. (if org-odd-levels-only
  7379. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7380. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7381. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7382. (max 1 (+ level (or change 0)))))
  7383. (defun org-promote ()
  7384. "Promote the current heading higher up the tree."
  7385. (org-with-wide-buffer
  7386. (org-back-to-heading t)
  7387. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7388. after-change-functions))
  7389. (level (save-match-data (funcall outline-level)))
  7390. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7391. (diff (abs (- level (length up-head) -1))))
  7392. (cond
  7393. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7394. (replace-match "# " nil t))
  7395. ((= level 1)
  7396. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7397. (t (replace-match up-head nil t)))
  7398. (unless (= level 1)
  7399. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7400. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7401. (run-hooks 'org-after-promote-entry-hook))))
  7402. (defun org-demote ()
  7403. "Demote the current heading lower down the tree."
  7404. (org-with-wide-buffer
  7405. (org-back-to-heading t)
  7406. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7407. after-change-functions))
  7408. (level (save-match-data (funcall outline-level)))
  7409. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7410. (diff (abs (- level (length down-head) -1))))
  7411. (replace-match down-head nil t)
  7412. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7413. (when org-adapt-indentation (org-fixup-indentation diff))
  7414. (run-hooks 'org-after-demote-entry-hook))))
  7415. (defun org-cycle-level ()
  7416. "Cycle the level of an empty headline through possible states.
  7417. This goes first to child, then to parent, level, then up the hierarchy.
  7418. After top level, it switches back to sibling level."
  7419. (interactive)
  7420. (let ((org-adapt-indentation nil))
  7421. (when (org-point-at-end-of-empty-headline)
  7422. (setq this-command 'org-cycle-level) ; Only needed for caching
  7423. (let ((cur-level (org-current-level))
  7424. (prev-level (org-get-previous-line-level)))
  7425. (cond
  7426. ;; If first headline in file, promote to top-level.
  7427. ((= prev-level 0)
  7428. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7429. do (org-do-promote)))
  7430. ;; If same level as prev, demote one.
  7431. ((= prev-level cur-level)
  7432. (org-do-demote))
  7433. ;; If parent is top-level, promote to top level if not already.
  7434. ((= prev-level 1)
  7435. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7436. do (org-do-promote)))
  7437. ;; If top-level, return to prev-level.
  7438. ((= cur-level 1)
  7439. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7440. do (org-do-demote)))
  7441. ;; If less than prev-level, promote one.
  7442. ((< cur-level prev-level)
  7443. (org-do-promote))
  7444. ;; If deeper than prev-level, promote until higher than
  7445. ;; prev-level.
  7446. ((> cur-level prev-level)
  7447. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7448. do (org-do-promote))))
  7449. t))))
  7450. (defun org-map-tree (fun)
  7451. "Call FUN for every heading underneath the current one."
  7452. (org-back-to-heading t)
  7453. (let ((level (funcall outline-level)))
  7454. (save-excursion
  7455. (funcall fun)
  7456. (while (and (progn
  7457. (outline-next-heading)
  7458. (> (funcall outline-level) level))
  7459. (not (eobp)))
  7460. (funcall fun)))))
  7461. (defun org-map-region (fun beg end)
  7462. "Call FUN for every heading between BEG and END."
  7463. (let ((org-ignore-region t))
  7464. (save-excursion
  7465. (setq end (copy-marker end))
  7466. (goto-char beg)
  7467. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7468. (< (point) end))
  7469. (funcall fun))
  7470. (while (and (progn
  7471. (outline-next-heading)
  7472. (< (point) end))
  7473. (not (eobp)))
  7474. (funcall fun)))))
  7475. (defun org-fixup-indentation (diff)
  7476. "Change the indentation in the current entry by DIFF.
  7477. DIFF is an integer. Indentation is done according to the
  7478. following rules:
  7479. - Planning information and property drawers are always indented
  7480. according to the new level of the headline;
  7481. - Footnote definitions and their contents are ignored;
  7482. - Inlinetasks' boundaries are not shifted;
  7483. - Empty lines are ignored;
  7484. - Other lines' indentation are shifted by DIFF columns, unless
  7485. it would introduce a structural change in the document, in
  7486. which case no shifting is done at all.
  7487. Assume point is at a heading or an inlinetask beginning."
  7488. (org-with-wide-buffer
  7489. (narrow-to-region (line-beginning-position)
  7490. (save-excursion
  7491. (if (org-with-limited-levels (org-at-heading-p))
  7492. (org-with-limited-levels (outline-next-heading))
  7493. (org-inlinetask-goto-end))
  7494. (point)))
  7495. (forward-line)
  7496. ;; Indent properly planning info and property drawer.
  7497. (when (looking-at-p org-planning-line-re)
  7498. (org-indent-line)
  7499. (forward-line))
  7500. (when (looking-at org-property-drawer-re)
  7501. (goto-char (match-end 0))
  7502. (forward-line)
  7503. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7504. (catch 'no-shift
  7505. (when (zerop diff) (throw 'no-shift nil))
  7506. ;; If DIFF is negative, first check if a shift is possible at all
  7507. ;; (e.g., it doesn't break structure). This can only happen if
  7508. ;; some contents are not properly indented.
  7509. (let ((case-fold-search t))
  7510. (when (< diff 0)
  7511. (let ((diff (- diff))
  7512. (forbidden-re (concat org-outline-regexp
  7513. "\\|"
  7514. (substring org-footnote-definition-re 1))))
  7515. (save-excursion
  7516. (while (not (eobp))
  7517. (cond
  7518. ((looking-at-p "[ \t]*$") (forward-line))
  7519. ((and (looking-at-p org-footnote-definition-re)
  7520. (let ((e (org-element-at-point)))
  7521. (and (eq (org-element-type e) 'footnote-definition)
  7522. (goto-char (org-element-property :end e))))))
  7523. ((looking-at-p org-outline-regexp) (forward-line))
  7524. ;; Give up if shifting would move before column 0 or
  7525. ;; if it would introduce a headline or a footnote
  7526. ;; definition.
  7527. (t
  7528. (skip-chars-forward " \t")
  7529. (let ((ind (current-column)))
  7530. (when (or (< ind diff)
  7531. (and (= ind diff) (looking-at-p forbidden-re)))
  7532. (throw 'no-shift nil)))
  7533. ;; Ignore contents of example blocks and source
  7534. ;; blocks if their indentation is meant to be
  7535. ;; preserved. Jump to block's closing line.
  7536. (beginning-of-line)
  7537. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7538. (let ((e (org-element-at-point)))
  7539. (and (memq (org-element-type e)
  7540. '(example-block src-block))
  7541. (or org-src-preserve-indentation
  7542. (org-element-property :preserve-indent e))
  7543. (goto-char (org-element-property :end e))
  7544. (progn (skip-chars-backward " \r\t\n")
  7545. (beginning-of-line)
  7546. t))))
  7547. (forward-line))))))))
  7548. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7549. ;; by DIFF. Also skip contents of source or example blocks
  7550. ;; when indentation is meant to be preserved.
  7551. (while (not (eobp))
  7552. (cond
  7553. ((and (looking-at-p org-footnote-definition-re)
  7554. (let ((e (org-element-at-point)))
  7555. (and (eq (org-element-type e) 'footnote-definition)
  7556. (goto-char (org-element-property :end e))))))
  7557. ((looking-at-p org-outline-regexp) (forward-line))
  7558. ((looking-at-p "[ \t]*$") (forward-line))
  7559. (t
  7560. (indent-line-to (+ (org-get-indentation) diff))
  7561. (beginning-of-line)
  7562. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7563. (let ((e (org-element-at-point)))
  7564. (and (memq (org-element-type e)
  7565. '(example-block src-block))
  7566. (or org-src-preserve-indentation
  7567. (org-element-property :preserve-indent e))
  7568. (goto-char (org-element-property :end e))
  7569. (progn (skip-chars-backward " \r\t\n")
  7570. (beginning-of-line)
  7571. t))))
  7572. (forward-line)))))))))
  7573. (defun org-convert-to-odd-levels ()
  7574. "Convert an Org file with all levels allowed to one with odd levels.
  7575. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7576. level 5 etc."
  7577. (interactive)
  7578. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7579. (let ((outline-level 'org-outline-level)
  7580. (org-odd-levels-only nil) n)
  7581. (save-excursion
  7582. (goto-char (point-min))
  7583. (while (re-search-forward "^\\*\\*+ " nil t)
  7584. (setq n (- (length (match-string 0)) 2))
  7585. (while (>= (setq n (1- n)) 0)
  7586. (org-demote))
  7587. (end-of-line 1))))))
  7588. (defun org-convert-to-oddeven-levels ()
  7589. "Convert an Org file with only odd levels to one with odd/even levels.
  7590. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7591. file contains a section with an even level, conversion would
  7592. destroy the structure of the file. An error is signaled in this
  7593. case."
  7594. (interactive)
  7595. (goto-char (point-min))
  7596. ;; First check if there are no even levels
  7597. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7598. (org-show-set-visibility 'canonical)
  7599. (error "Not all levels are odd in this file. Conversion not possible"))
  7600. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7601. (let ((outline-regexp org-outline-regexp)
  7602. (outline-level 'org-outline-level)
  7603. (org-odd-levels-only nil) n)
  7604. (save-excursion
  7605. (goto-char (point-min))
  7606. (while (re-search-forward "^\\*\\*+ " nil t)
  7607. (setq n (/ (1- (length (match-string 0))) 2))
  7608. (while (>= (setq n (1- n)) 0)
  7609. (org-promote))
  7610. (end-of-line 1))))))
  7611. (defun org-tr-level (n)
  7612. "Make N odd if required."
  7613. (if org-odd-levels-only (1+ (/ n 2)) n))
  7614. ;;; Vertical tree motion, cutting and pasting of subtrees
  7615. (defun org-move-subtree-up (&optional arg)
  7616. "Move the current subtree up past ARG headlines of the same level."
  7617. (interactive "p")
  7618. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7619. (defun org-move-subtree-down (&optional arg)
  7620. "Move the current subtree down past ARG headlines of the same level."
  7621. (interactive "p")
  7622. (setq arg (prefix-numeric-value arg))
  7623. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7624. 'org-get-last-sibling))
  7625. (ins-point (make-marker))
  7626. (cnt (abs arg))
  7627. (col (current-column))
  7628. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7629. ;; Select the tree
  7630. (org-back-to-heading)
  7631. (setq beg0 (point))
  7632. (save-excursion
  7633. (setq ne-beg (org-back-over-empty-lines))
  7634. (setq beg (point)))
  7635. (save-match-data
  7636. (save-excursion (outline-end-of-heading)
  7637. (setq folded (outline-invisible-p)))
  7638. (progn (org-end-of-subtree nil t)
  7639. (unless (eobp) (backward-char))))
  7640. (outline-next-heading)
  7641. (setq ne-end (org-back-over-empty-lines))
  7642. (setq end (point))
  7643. (goto-char beg0)
  7644. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7645. ;; include less whitespace
  7646. (save-excursion
  7647. (goto-char beg)
  7648. (forward-line (- ne-beg ne-end))
  7649. (setq beg (point))))
  7650. ;; Find insertion point, with error handling
  7651. (while (> cnt 0)
  7652. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7653. (progn (goto-char beg0)
  7654. (user-error "Cannot move past superior level or buffer limit")))
  7655. (setq cnt (1- cnt)))
  7656. (when (> arg 0)
  7657. ;; Moving forward - still need to move over subtree
  7658. (org-end-of-subtree t t)
  7659. (save-excursion
  7660. (org-back-over-empty-lines)
  7661. (or (bolp) (newline))))
  7662. (setq ne-ins (org-back-over-empty-lines))
  7663. (move-marker ins-point (point))
  7664. (setq txt (buffer-substring beg end))
  7665. (org-save-markers-in-region beg end)
  7666. (delete-region beg end)
  7667. (org-remove-empty-overlays-at beg)
  7668. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7669. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7670. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7671. (let ((bbb (point)))
  7672. (insert-before-markers txt)
  7673. (org-reinstall-markers-in-region bbb)
  7674. (move-marker ins-point bbb))
  7675. (or (bolp) (insert "\n"))
  7676. (setq ins-end (point))
  7677. (goto-char ins-point)
  7678. (org-skip-whitespace)
  7679. (when (and (< arg 0)
  7680. (org-first-sibling-p)
  7681. (> ne-ins ne-beg))
  7682. ;; Move whitespace back to beginning
  7683. (save-excursion
  7684. (goto-char ins-end)
  7685. (let ((kill-whole-line t))
  7686. (kill-line (- ne-ins ne-beg)) (point)))
  7687. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7688. (move-marker ins-point nil)
  7689. (if folded
  7690. (outline-hide-subtree)
  7691. (org-show-entry)
  7692. (org-show-children)
  7693. (org-cycle-hide-drawers 'children))
  7694. (org-clean-visibility-after-subtree-move)
  7695. ;; move back to the initial column we were at
  7696. (move-to-column col)))
  7697. (defvar org-subtree-clip ""
  7698. "Clipboard for cut and paste of subtrees.
  7699. This is actually only a copy of the kill, because we use the normal kill
  7700. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7701. (defvar org-subtree-clip-folded nil
  7702. "Was the last copied subtree folded?
  7703. This is used to fold the tree back after pasting.")
  7704. (defun org-cut-subtree (&optional n)
  7705. "Cut the current subtree into the clipboard.
  7706. With prefix arg N, cut this many sequential subtrees.
  7707. This is a short-hand for marking the subtree and then cutting it."
  7708. (interactive "p")
  7709. (org-copy-subtree n 'cut))
  7710. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7711. "Copy the current subtree it in the clipboard.
  7712. With prefix arg N, copy this many sequential subtrees.
  7713. This is a short-hand for marking the subtree and then copying it.
  7714. If CUT is non-nil, actually cut the subtree.
  7715. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7716. of some markers in the region, even if CUT is non-nil. This is
  7717. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7718. (interactive "p")
  7719. (let (beg end folded (beg0 (point)))
  7720. (if (called-interactively-p 'any)
  7721. (org-back-to-heading nil) ; take what looks like a subtree
  7722. (org-back-to-heading t)) ; take what is really there
  7723. (setq beg (point))
  7724. (skip-chars-forward " \t\r\n")
  7725. (save-match-data
  7726. (if nosubtrees
  7727. (outline-next-heading)
  7728. (save-excursion (outline-end-of-heading)
  7729. (setq folded (outline-invisible-p)))
  7730. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7731. (org-end-of-subtree t t)))
  7732. ;; Include the end of an inlinetask
  7733. (when (and (featurep 'org-inlinetask)
  7734. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7735. "END[ \t]*$")))
  7736. (end-of-line))
  7737. (setq end (point))
  7738. (goto-char beg0)
  7739. (when (> end beg)
  7740. (setq org-subtree-clip-folded folded)
  7741. (when (or cut force-store-markers)
  7742. (org-save-markers-in-region beg end))
  7743. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7744. (setq org-subtree-clip (current-kill 0))
  7745. (message "%s: Subtree(s) with %d characters"
  7746. (if cut "Cut" "Copied")
  7747. (length org-subtree-clip)))))
  7748. (defun org-paste-subtree (&optional level tree for-yank remove)
  7749. "Paste the clipboard as a subtree, with modification of headline level.
  7750. The entire subtree is promoted or demoted in order to match a new headline
  7751. level.
  7752. If the cursor is at the beginning of a headline, the same level as
  7753. that headline is used to paste the tree.
  7754. If not, the new level is derived from the *visible* headings
  7755. before and after the insertion point, and taken to be the inferior headline
  7756. level of the two. So if the previous visible heading is level 3 and the
  7757. next is level 4 (or vice versa), level 4 will be used for insertion.
  7758. This makes sure that the subtree remains an independent subtree and does
  7759. not swallow low level entries.
  7760. You can also force a different level, either by using a numeric prefix
  7761. argument, or by inserting the heading marker by hand. For example, if the
  7762. cursor is after \"*****\", then the tree will be shifted to level 5.
  7763. If optional TREE is given, use this text instead of the kill ring.
  7764. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7765. move back over whitespace before inserting, and move point to the end of
  7766. the inserted text when done.
  7767. When REMOVE is non-nil, remove the subtree from the clipboard."
  7768. (interactive "P")
  7769. (setq tree (or tree (and kill-ring (current-kill 0))))
  7770. (unless (org-kill-is-subtree-p tree)
  7771. (user-error "%s"
  7772. (substitute-command-keys
  7773. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7774. (org-with-limited-levels
  7775. (let* ((visp (not (outline-invisible-p)))
  7776. (txt tree)
  7777. (^re_ "\\(\\*+\\)[ \t]*")
  7778. (old-level (if (string-match org-outline-regexp-bol txt)
  7779. (- (match-end 0) (match-beginning 0) 1)
  7780. -1))
  7781. (force-level (cond (level (prefix-numeric-value level))
  7782. ((and (looking-at "[ \t]*$")
  7783. (string-match
  7784. "^\\*+$" (buffer-substring
  7785. (point-at-bol) (point))))
  7786. (- (match-end 0) (match-beginning 0)))
  7787. ((and (bolp)
  7788. (looking-at org-outline-regexp))
  7789. (- (match-end 0) (point) 1))))
  7790. (previous-level (save-excursion
  7791. (condition-case nil
  7792. (progn
  7793. (outline-previous-visible-heading 1)
  7794. (if (looking-at ^re_)
  7795. (- (match-end 0) (match-beginning 0) 1)
  7796. 1))
  7797. (error 1))))
  7798. (next-level (save-excursion
  7799. (condition-case nil
  7800. (progn
  7801. (or (looking-at org-outline-regexp)
  7802. (outline-next-visible-heading 1))
  7803. (if (looking-at ^re_)
  7804. (- (match-end 0) (match-beginning 0) 1)
  7805. 1))
  7806. (error 1))))
  7807. (new-level (or force-level (max previous-level next-level)))
  7808. (shift (if (or (= old-level -1)
  7809. (= new-level -1)
  7810. (= old-level new-level))
  7811. 0
  7812. (- new-level old-level)))
  7813. (delta (if (> shift 0) -1 1))
  7814. (func (if (> shift 0) 'org-demote 'org-promote))
  7815. (org-odd-levels-only nil)
  7816. beg end newend)
  7817. ;; Remove the forced level indicator
  7818. (when force-level
  7819. (delete-region (point-at-bol) (point)))
  7820. ;; Paste
  7821. (beginning-of-line (if (bolp) 1 2))
  7822. (setq beg (point))
  7823. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7824. (insert-before-markers txt)
  7825. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7826. (setq newend (point))
  7827. (org-reinstall-markers-in-region beg)
  7828. (setq end (point))
  7829. (goto-char beg)
  7830. (skip-chars-forward " \t\n\r")
  7831. (setq beg (point))
  7832. (when (and (outline-invisible-p) visp)
  7833. (save-excursion (outline-show-heading)))
  7834. ;; Shift if necessary
  7835. (unless (= shift 0)
  7836. (save-restriction
  7837. (narrow-to-region beg end)
  7838. (while (not (= shift 0))
  7839. (org-map-region func (point-min) (point-max))
  7840. (setq shift (+ delta shift)))
  7841. (goto-char (point-min))
  7842. (setq newend (point-max))))
  7843. (when (or (called-interactively-p 'interactive) for-yank)
  7844. (message "Clipboard pasted as level %d subtree" new-level))
  7845. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7846. kill-ring
  7847. (eq org-subtree-clip (current-kill 0))
  7848. org-subtree-clip-folded)
  7849. ;; The tree was folded before it was killed/copied
  7850. (outline-hide-subtree))
  7851. (and for-yank (goto-char newend))
  7852. (and remove (setq kill-ring (cdr kill-ring))))))
  7853. (defun org-kill-is-subtree-p (&optional txt)
  7854. "Check if the current kill is an outline subtree, or a set of trees.
  7855. Returns nil if kill does not start with a headline, or if the first
  7856. headline level is not the largest headline level in the tree.
  7857. So this will actually accept several entries of equal levels as well,
  7858. which is OK for `org-paste-subtree'.
  7859. If optional TXT is given, check this string instead of the current kill."
  7860. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7861. (re (org-get-limited-outline-regexp))
  7862. (^re (concat "^" re))
  7863. (start-level (and kill
  7864. (string-match
  7865. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7866. kill)
  7867. (- (match-end 2) (match-beginning 2) 1)))
  7868. (start (1+ (or (match-beginning 2) -1))))
  7869. (if (not start-level)
  7870. (progn
  7871. nil) ;; does not even start with a heading
  7872. (catch 'exit
  7873. (while (setq start (string-match ^re kill (1+ start)))
  7874. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7875. (throw 'exit nil)))
  7876. t))))
  7877. (defvar org-markers-to-move nil
  7878. "Markers that should be moved with a cut-and-paste operation.
  7879. Those markers are stored together with their positions relative to
  7880. the start of the region.")
  7881. (defun org-save-markers-in-region (beg end)
  7882. "Check markers in region.
  7883. If these markers are between BEG and END, record their position relative
  7884. to BEG, so that after moving the block of text, we can put the markers back
  7885. into place.
  7886. This function gets called just before an entry or tree gets cut from the
  7887. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7888. called immediately, to move the markers with the entries."
  7889. (setq org-markers-to-move nil)
  7890. (when (featurep 'org-clock)
  7891. (org-clock-save-markers-for-cut-and-paste beg end))
  7892. (when (featurep 'org-agenda)
  7893. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7894. (defun org-check-and-save-marker (marker beg end)
  7895. "Check if MARKER is between BEG and END.
  7896. If yes, remember the marker and the distance to BEG."
  7897. (when (and (marker-buffer marker)
  7898. (equal (marker-buffer marker) (current-buffer))
  7899. (>= marker beg) (< marker end))
  7900. (push (cons marker (- marker beg)) org-markers-to-move)))
  7901. (defun org-reinstall-markers-in-region (beg)
  7902. "Move all remembered markers to their position relative to BEG."
  7903. (dolist (x org-markers-to-move)
  7904. (move-marker (car x) (+ beg (cdr x))))
  7905. (setq org-markers-to-move nil))
  7906. (defun org-narrow-to-subtree ()
  7907. "Narrow buffer to the current subtree."
  7908. (interactive)
  7909. (save-excursion
  7910. (save-match-data
  7911. (org-with-limited-levels
  7912. (narrow-to-region
  7913. (progn (org-back-to-heading t) (point))
  7914. (progn (org-end-of-subtree t t)
  7915. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7916. (point)))))))
  7917. (defun org-narrow-to-block ()
  7918. "Narrow buffer to the current block."
  7919. (interactive)
  7920. (let* ((case-fold-search t)
  7921. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7922. "^[ \t]*#\\+end_.*")))
  7923. (if blockp
  7924. (narrow-to-region (car blockp) (cdr blockp))
  7925. (user-error "Not in a block"))))
  7926. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7927. "Clone the task (subtree) at point N times.
  7928. The clones will be inserted as siblings.
  7929. In interactive use, the user will be prompted for the number of
  7930. clones to be produced. If the entry has a timestamp, the user
  7931. will also be prompted for a time shift, which may be a repeater
  7932. as used in time stamps, for example `+3d'. To disable this,
  7933. you can call the function with a universal prefix argument.
  7934. When a valid repeater is given and the entry contains any time
  7935. stamps, the clones will become a sequence in time, with time
  7936. stamps in the subtree shifted for each clone produced. If SHIFT
  7937. is nil or the empty string, time stamps will be left alone. The
  7938. ID property of the original subtree is removed.
  7939. In each clone, all the CLOCK entries will be removed. This
  7940. prevents Org from considering that the clocked times overlap.
  7941. If the original subtree did contain time stamps with a repeater,
  7942. the following will happen:
  7943. - the repeater will be removed in each clone
  7944. - an additional clone will be produced, with the current, unshifted
  7945. date(s) in the entry.
  7946. - the original entry will be placed *after* all the clones, with
  7947. repeater intact.
  7948. - the start days in the repeater in the original entry will be shifted
  7949. to past the last clone.
  7950. In this way you can spell out a number of instances of a repeating task,
  7951. and still retain the repeater to cover future instances of the task.
  7952. As described above, N+1 clones are produced when the original
  7953. subtree has a repeater. Setting N to 0, then, can be used to
  7954. remove the repeater from a subtree and create a shifted clone
  7955. with the original repeater."
  7956. (interactive "nNumber of clones to produce: ")
  7957. (let ((shift
  7958. (or shift
  7959. (if (and (not (equal current-prefix-arg '(4)))
  7960. (save-excursion
  7961. (re-search-forward org-ts-regexp-both
  7962. (save-excursion
  7963. (org-end-of-subtree t)
  7964. (point)) t)))
  7965. (read-from-minibuffer
  7966. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7967. ""))) ;; No time shift
  7968. (n-no-remove -1)
  7969. (drawer-re org-drawer-regexp)
  7970. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7971. beg end template task idprop
  7972. shift-n shift-what doshift nmin nmax)
  7973. (unless (wholenump n)
  7974. (user-error "Invalid number of replications %s" n))
  7975. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7976. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7977. shift)))
  7978. (user-error "Invalid shift specification %s" shift))
  7979. (when doshift
  7980. (setq shift-n (string-to-number (match-string 1 shift))
  7981. shift-what (cdr (assoc (match-string 2 shift)
  7982. '(("d" . day) ("w" . week)
  7983. ("m" . month) ("y" . year))))))
  7984. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  7985. (setq nmin 1 nmax n)
  7986. (org-back-to-heading t)
  7987. (setq beg (point))
  7988. (setq idprop (org-entry-get nil "ID"))
  7989. (org-end-of-subtree t t)
  7990. (or (bolp) (insert "\n"))
  7991. (setq end (point))
  7992. (setq template (buffer-substring beg end))
  7993. (when (and doshift
  7994. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  7995. (delete-region beg end)
  7996. (setq end beg)
  7997. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  7998. (goto-char end)
  7999. (cl-loop for n from nmin to nmax do
  8000. ;; prepare clone
  8001. (with-temp-buffer
  8002. (insert template)
  8003. (org-mode)
  8004. (goto-char (point-min))
  8005. (org-show-subtree)
  8006. (and idprop (if org-clone-delete-id
  8007. (org-entry-delete nil "ID")
  8008. (org-id-get-create t)))
  8009. (unless (= n 0)
  8010. (while (re-search-forward org-clock-re nil t)
  8011. (kill-whole-line))
  8012. (goto-char (point-min))
  8013. (while (re-search-forward drawer-re nil t)
  8014. (org-remove-empty-drawer-at (point))))
  8015. (goto-char (point-min))
  8016. (when doshift
  8017. (while (re-search-forward org-ts-regexp-both nil t)
  8018. (org-timestamp-change (* n shift-n) shift-what))
  8019. (unless (= n n-no-remove)
  8020. (goto-char (point-min))
  8021. (while (re-search-forward org-ts-regexp nil t)
  8022. (save-excursion
  8023. (goto-char (match-beginning 0))
  8024. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8025. (delete-region (match-beginning 1) (match-end 1)))))))
  8026. (setq task (buffer-string)))
  8027. (insert task))
  8028. (goto-char beg)))
  8029. ;;; Outline Sorting
  8030. (defun org-sort (with-case)
  8031. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8032. Optional argument WITH-CASE means sort case-sensitively."
  8033. (interactive "P")
  8034. (cond
  8035. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8036. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8037. (t
  8038. (org-call-with-arg 'org-sort-entries with-case))))
  8039. (defun org-sort-remove-invisible (s)
  8040. "Remove invisible links from string S."
  8041. (remove-text-properties 0 (length s) org-rm-props s)
  8042. (while (string-match org-bracket-link-regexp s)
  8043. (setq s (replace-match (if (match-end 2)
  8044. (match-string 3 s)
  8045. (match-string 1 s))
  8046. t t s)))
  8047. (let ((st (format " %s " s)))
  8048. (while (string-match org-emph-re st)
  8049. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8050. (setq s (substring st 1 -1)))
  8051. s)
  8052. (defvar org-priority-regexp) ; defined later in the file
  8053. (defvar org-after-sorting-entries-or-items-hook nil
  8054. "Hook that is run after a bunch of entries or items have been sorted.
  8055. When children are sorted, the cursor is in the parent line when this
  8056. hook gets called. When a region or a plain list is sorted, the cursor
  8057. will be in the first entry of the sorted region/list.")
  8058. (defun org-sort-entries
  8059. (&optional with-case sorting-type getkey-func compare-func property)
  8060. "Sort entries on a certain level of an outline tree.
  8061. If there is an active region, the entries in the region are sorted.
  8062. Else, if the cursor is before the first entry, sort the top-level items.
  8063. Else, the children of the entry at point are sorted.
  8064. Sorting can be alphabetically, numerically, by date/time as given by
  8065. a time stamp, by a property, by priority order, or by a custom function.
  8066. The command prompts for the sorting type unless it has been given to the
  8067. function through the SORTING-TYPE argument, which needs to be a character,
  8068. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8069. the precise meaning of each character:
  8070. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8071. c By creation time, which is assumed to be the first inactive time stamp
  8072. at the beginning of a line.
  8073. d By deadline date/time.
  8074. k By clocking time.
  8075. n Numerically, by converting the beginning of the entry/item to a number.
  8076. o By order of TODO keywords.
  8077. p By priority according to the cookie.
  8078. r By the value of a property.
  8079. s By scheduled date/time.
  8080. t By date/time, either the first active time stamp in the entry, or, if
  8081. none exist, by the first inactive one.
  8082. Capital letters will reverse the sort order.
  8083. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8084. called with point at the beginning of the record. It must return either
  8085. a string or a number that should serve as the sorting key for that record.
  8086. Comparing entries ignores case by default. However, with an optional argument
  8087. WITH-CASE, the sorting considers case as well.
  8088. Sorting is done against the visible part of the headlines, it ignores hidden
  8089. links.
  8090. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8091. (interactive "P")
  8092. (let ((case-func (if with-case 'identity 'downcase))
  8093. (cmstr
  8094. ;; The clock marker is lost when using `sort-subr', let's
  8095. ;; store the clocking string.
  8096. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8097. (save-excursion
  8098. (goto-char org-clock-marker)
  8099. (buffer-substring-no-properties (line-beginning-position)
  8100. (point)))))
  8101. start beg end stars re re2
  8102. txt what tmp)
  8103. ;; Find beginning and end of region to sort
  8104. (cond
  8105. ((org-region-active-p)
  8106. ;; we will sort the region
  8107. (setq end (region-end)
  8108. what "region")
  8109. (goto-char (region-beginning))
  8110. (unless (org-at-heading-p) (outline-next-heading))
  8111. (setq start (point)))
  8112. ((or (org-at-heading-p)
  8113. (ignore-errors (progn (org-back-to-heading) t)))
  8114. ;; we will sort the children of the current headline
  8115. (org-back-to-heading)
  8116. (setq start (point)
  8117. end (progn (org-end-of-subtree t t)
  8118. (or (bolp) (insert "\n"))
  8119. (when (>= (org-back-over-empty-lines) 1)
  8120. (forward-line 1))
  8121. (point))
  8122. what "children")
  8123. (goto-char start)
  8124. (outline-show-subtree)
  8125. (outline-next-heading))
  8126. (t
  8127. ;; we will sort the top-level entries in this file
  8128. (goto-char (point-min))
  8129. (or (org-at-heading-p) (outline-next-heading))
  8130. (setq start (point))
  8131. (goto-char (point-max))
  8132. (beginning-of-line 1)
  8133. (when (looking-at ".*?\\S-")
  8134. ;; File ends in a non-white line
  8135. (end-of-line 1)
  8136. (insert "\n"))
  8137. (setq end (point-max))
  8138. (setq what "top-level")
  8139. (goto-char start)
  8140. (outline-show-all)))
  8141. (setq beg (point))
  8142. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8143. (looking-at "\\(\\*+\\)")
  8144. (setq stars (match-string 1)
  8145. re (concat "^" (regexp-quote stars) " +")
  8146. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8147. txt (buffer-substring beg end))
  8148. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8149. (when (and (not (equal stars "*")) (string-match re2 txt))
  8150. (user-error "Region to sort contains a level above the first entry"))
  8151. (unless sorting-type
  8152. (message
  8153. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8154. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8155. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8156. what)
  8157. (setq sorting-type (read-char-exclusive))
  8158. (unless getkey-func
  8159. (and (= (downcase sorting-type) ?f)
  8160. (setq getkey-func
  8161. (completing-read "Sort using function: "
  8162. obarray 'fboundp t nil nil))
  8163. (setq getkey-func (intern getkey-func))))
  8164. (and (= (downcase sorting-type) ?r)
  8165. (not property)
  8166. (setq property
  8167. (completing-read "Property: "
  8168. (mapcar #'list (org-buffer-property-keys t))
  8169. nil t))))
  8170. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8171. (message "Sorting entries...")
  8172. (save-restriction
  8173. (narrow-to-region start end)
  8174. (let ((dcst (downcase sorting-type))
  8175. (case-fold-search nil)
  8176. (now (current-time)))
  8177. (sort-subr
  8178. (/= dcst sorting-type)
  8179. ;; This function moves to the beginning character of the "record" to
  8180. ;; be sorted.
  8181. (lambda nil
  8182. (if (re-search-forward re nil t)
  8183. (goto-char (match-beginning 0))
  8184. (goto-char (point-max))))
  8185. ;; This function moves to the last character of the "record" being
  8186. ;; sorted.
  8187. (lambda nil
  8188. (save-match-data
  8189. (condition-case nil
  8190. (outline-forward-same-level 1)
  8191. (error
  8192. (goto-char (point-max))))))
  8193. ;; This function returns the value that gets sorted against.
  8194. (lambda nil
  8195. (cond
  8196. ((= dcst ?n)
  8197. (if (looking-at org-complex-heading-regexp)
  8198. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8199. nil))
  8200. ((= dcst ?a)
  8201. (if (looking-at org-complex-heading-regexp)
  8202. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8203. nil))
  8204. ((= dcst ?k)
  8205. (or (get-text-property (point) :org-clock-minutes) 0))
  8206. ((= dcst ?t)
  8207. (let ((end (save-excursion (outline-next-heading) (point))))
  8208. (if (or (re-search-forward org-ts-regexp end t)
  8209. (re-search-forward org-ts-regexp-both end t))
  8210. (org-time-string-to-seconds (match-string 0))
  8211. (float-time now))))
  8212. ((= dcst ?c)
  8213. (let ((end (save-excursion (outline-next-heading) (point))))
  8214. (if (re-search-forward
  8215. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8216. end t)
  8217. (org-time-string-to-seconds (match-string 0))
  8218. (float-time now))))
  8219. ((= dcst ?s)
  8220. (let ((end (save-excursion (outline-next-heading) (point))))
  8221. (if (re-search-forward org-scheduled-time-regexp end t)
  8222. (org-time-string-to-seconds (match-string 1))
  8223. (float-time now))))
  8224. ((= dcst ?d)
  8225. (let ((end (save-excursion (outline-next-heading) (point))))
  8226. (if (re-search-forward org-deadline-time-regexp end t)
  8227. (org-time-string-to-seconds (match-string 1))
  8228. (float-time now))))
  8229. ((= dcst ?p)
  8230. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8231. (string-to-char (match-string 2))
  8232. org-default-priority))
  8233. ((= dcst ?r)
  8234. (or (org-entry-get nil property) ""))
  8235. ((= dcst ?o)
  8236. (when (looking-at org-complex-heading-regexp)
  8237. (let* ((m (match-string 2))
  8238. (s (if (member m org-done-keywords) '- '+)))
  8239. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8240. ((= dcst ?f)
  8241. (if getkey-func
  8242. (progn
  8243. (setq tmp (funcall getkey-func))
  8244. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8245. tmp)
  8246. (error "Invalid key function `%s'" getkey-func)))
  8247. (t (error "Invalid sorting type `%c'" sorting-type))))
  8248. nil
  8249. (cond
  8250. ((= dcst ?a) 'string<)
  8251. ((= dcst ?f) compare-func)
  8252. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8253. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8254. ;; Reset the clock marker if needed
  8255. (when cmstr
  8256. (save-excursion
  8257. (goto-char start)
  8258. (search-forward cmstr nil t)
  8259. (move-marker org-clock-marker (point))))
  8260. (message "Sorting entries...done")))
  8261. ;;; The orgstruct minor mode
  8262. ;; Define a minor mode which can be used in other modes in order to
  8263. ;; integrate the Org mode structure editing commands.
  8264. ;; This is really a hack, because the Org mode structure commands use
  8265. ;; keys which normally belong to the major mode. Here is how it
  8266. ;; works: The minor mode defines all the keys necessary to operate the
  8267. ;; structure commands, but wraps the commands into a function which
  8268. ;; tests if the cursor is currently at a headline or a plain list
  8269. ;; item. If that is the case, the structure command is used,
  8270. ;; temporarily setting many Org mode variables like regular
  8271. ;; expressions for filling etc. However, when any of those keys is
  8272. ;; used at a different location, function uses `key-binding' to look
  8273. ;; up if the key has an associated command in another currently active
  8274. ;; keymap (minor modes, major mode, global), and executes that
  8275. ;; command. There might be problems if any of the keys is otherwise
  8276. ;; used as a prefix key.
  8277. (defcustom orgstruct-heading-prefix-regexp ""
  8278. "Regexp that matches the custom prefix of Org headlines in
  8279. orgstruct(++)-mode."
  8280. :group 'org
  8281. :version "24.4"
  8282. :package-version '(Org . "8.3")
  8283. :type 'regexp)
  8284. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8285. (defcustom orgstruct-setup-hook nil
  8286. "Hook run after orgstruct-mode-map is filled."
  8287. :group 'org
  8288. :version "24.4"
  8289. :package-version '(Org . "8.0")
  8290. :type 'hook)
  8291. (defvar orgstruct-initialized nil)
  8292. (defvar org-local-vars nil
  8293. "List of local variables, for use by `orgstruct-mode'.")
  8294. ;;;###autoload
  8295. (define-minor-mode orgstruct-mode
  8296. "Toggle the minor mode `orgstruct-mode'.
  8297. This mode is for using Org mode structure commands in other
  8298. modes. The following keys behave as if Org mode were active, if
  8299. the cursor is on a headline, or on a plain list item (both as
  8300. defined by Org-mode)."
  8301. nil " OrgStruct" (make-sparse-keymap)
  8302. (funcall (if orgstruct-mode
  8303. 'add-to-invisibility-spec
  8304. 'remove-from-invisibility-spec)
  8305. '(outline . t))
  8306. (when orgstruct-mode
  8307. (org-load-modules-maybe)
  8308. (unless orgstruct-initialized
  8309. (orgstruct-setup)
  8310. (setq orgstruct-initialized t))))
  8311. ;;;###autoload
  8312. (defun turn-on-orgstruct ()
  8313. "Unconditionally turn on `orgstruct-mode'."
  8314. (orgstruct-mode 1))
  8315. (defvar-local orgstruct-is-++ nil
  8316. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8317. (defvar-local org-fb-vars nil)
  8318. (defun orgstruct++-mode (&optional arg)
  8319. "Toggle `orgstruct-mode', the enhanced version of it.
  8320. In addition to setting orgstruct-mode, this also exports all
  8321. indentation and autofilling variables from Org mode into the
  8322. buffer. It will also recognize item context in multiline items."
  8323. (interactive "P")
  8324. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8325. (if (< arg 1)
  8326. (progn (orgstruct-mode -1)
  8327. (dolist (v org-fb-vars)
  8328. (set (make-local-variable (car v))
  8329. (if (eq (car-safe (cadr v)) 'quote)
  8330. (cl-cadadr v)
  8331. (nth 1 v)))))
  8332. (orgstruct-mode 1)
  8333. (setq org-fb-vars nil)
  8334. (unless org-local-vars
  8335. (setq org-local-vars (org-get-local-variables)))
  8336. (let (var val)
  8337. (dolist (x org-local-vars)
  8338. (when (string-match
  8339. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8340. \\|fill-prefix\\|indent-\\)"
  8341. (symbol-name (car x)))
  8342. (setq var (car x) val (nth 1 x))
  8343. (push (list var `(quote ,(eval var))) org-fb-vars)
  8344. (set (make-local-variable var)
  8345. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8346. (setq-local orgstruct-is-++ t))))
  8347. ;;;###autoload
  8348. (defun turn-on-orgstruct++ ()
  8349. "Unconditionally turn on `orgstruct++-mode'."
  8350. (orgstruct++-mode 1))
  8351. (defun orgstruct-error ()
  8352. "Error when there is no default binding for a structure key."
  8353. (interactive)
  8354. (funcall (if (fboundp 'user-error)
  8355. 'user-error
  8356. 'error)
  8357. "This key has no function outside structure elements"))
  8358. (defun orgstruct-setup ()
  8359. "Setup orgstruct keymap."
  8360. (dolist (cell '((org-demote . t)
  8361. (org-metaleft . t)
  8362. (org-metaright . t)
  8363. (org-promote . t)
  8364. (org-shiftmetaleft . t)
  8365. (org-shiftmetaright . t)
  8366. org-backward-element
  8367. org-backward-heading-same-level
  8368. org-ctrl-c-ret
  8369. org-ctrl-c-minus
  8370. org-ctrl-c-star
  8371. org-cycle
  8372. org-force-cycle-archived
  8373. org-forward-heading-same-level
  8374. org-insert-heading
  8375. org-insert-heading-respect-content
  8376. org-kill-note-or-show-branches
  8377. org-mark-subtree
  8378. org-meta-return
  8379. org-metadown
  8380. org-metaup
  8381. org-narrow-to-subtree
  8382. org-promote-subtree
  8383. org-reveal
  8384. org-shiftdown
  8385. org-shiftleft
  8386. org-shiftmetadown
  8387. org-shiftmetaup
  8388. org-shiftright
  8389. org-shifttab
  8390. org-shifttab
  8391. org-shiftup
  8392. org-show-children
  8393. org-show-subtree
  8394. org-sort
  8395. org-up-element
  8396. outline-demote
  8397. outline-next-visible-heading
  8398. outline-previous-visible-heading
  8399. outline-promote
  8400. outline-up-heading))
  8401. (let ((f (or (car-safe cell) cell))
  8402. (disable-when-heading-prefix (cdr-safe cell)))
  8403. (when (fboundp f)
  8404. (let ((new-bindings))
  8405. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8406. (where-is-internal f outline-mode-map)))
  8407. (push binding new-bindings)
  8408. ;; TODO use local-function-key-map
  8409. (dolist (rep '(("<tab>" . "TAB")
  8410. ("<return>" . "RET")
  8411. ("<escape>" . "ESC")
  8412. ("<delete>" . "DEL")))
  8413. (setq binding (read-kbd-macro
  8414. (let ((case-fold-search))
  8415. (replace-regexp-in-string
  8416. (regexp-quote (cdr rep))
  8417. (car rep)
  8418. (key-description binding)))))
  8419. (cl-pushnew binding new-bindings :test 'equal)))
  8420. (dolist (binding new-bindings)
  8421. (let ((key (lookup-key orgstruct-mode-map binding)))
  8422. (when (or (not key) (numberp key))
  8423. (ignore-errors
  8424. (org-defkey orgstruct-mode-map
  8425. binding
  8426. (orgstruct-make-binding
  8427. f binding disable-when-heading-prefix))))))))))
  8428. (run-hooks 'orgstruct-setup-hook))
  8429. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8430. "Create a function for binding in the structure minor mode.
  8431. FUN is the command to call inside a table. KEY is the key that
  8432. should be checked in for a command to execute outside of tables.
  8433. Non-nil `disable-when-heading-prefix' means to disable the command
  8434. if `orgstruct-heading-prefix-regexp' is not empty."
  8435. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8436. (let ((nname name)
  8437. (i 0))
  8438. (while (fboundp (intern nname))
  8439. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8440. (setq name (intern nname)))
  8441. (eval
  8442. (let ((bindings '((org-heading-regexp
  8443. (concat "^"
  8444. orgstruct-heading-prefix-regexp
  8445. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8446. (org-outline-regexp
  8447. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8448. (org-outline-regexp-bol
  8449. (concat "^" org-outline-regexp))
  8450. (outline-regexp org-outline-regexp)
  8451. (outline-heading-end-regexp "\n")
  8452. (outline-level 'org-outline-level)
  8453. (outline-heading-alist))))
  8454. `(defun ,name (arg)
  8455. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8456. "Outside of structure, run the binding of `"
  8457. (key-description key) "'."
  8458. (when disable-when-heading-prefix
  8459. (concat
  8460. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8461. "back to the default binding due to limitations of Org's implementation of\n"
  8462. "`" (symbol-name fun) "'.")))
  8463. (interactive "p")
  8464. (let* ((disable
  8465. ,(and disable-when-heading-prefix
  8466. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8467. (fallback
  8468. (or disable
  8469. (not
  8470. (let* ,bindings
  8471. (org-context-p 'headline 'item
  8472. ,(when (memq fun
  8473. '(org-insert-heading
  8474. org-insert-heading-respect-content
  8475. org-meta-return))
  8476. '(when orgstruct-is-++
  8477. 'item-body))))))))
  8478. (if fallback
  8479. (let* ((orgstruct-mode)
  8480. (binding
  8481. (let ((key ,key))
  8482. (catch 'exit
  8483. (dolist
  8484. (rep
  8485. '(nil
  8486. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8487. ("<\\([^>]*\\)return>" . "\\1RET")
  8488. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8489. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8490. nil)
  8491. (when rep
  8492. (setq key (read-kbd-macro
  8493. (let ((case-fold-search))
  8494. (replace-regexp-in-string
  8495. (car rep)
  8496. (cdr rep)
  8497. (key-description key))))))
  8498. (when (key-binding key)
  8499. (throw 'exit (key-binding key))))))))
  8500. (if (keymapp binding)
  8501. (org-set-transient-map binding)
  8502. (let ((func (or binding
  8503. (unless disable
  8504. 'orgstruct-error))))
  8505. (when func
  8506. (call-interactively func)))))
  8507. (org-run-like-in-org-mode
  8508. (lambda ()
  8509. (interactive)
  8510. (let* ,bindings
  8511. (call-interactively ',fun)))))))))
  8512. name))
  8513. (defun org-contextualize-keys (alist contexts)
  8514. "Return valid elements in ALIST depending on CONTEXTS.
  8515. `org-agenda-custom-commands' or `org-capture-templates' are the
  8516. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8517. or `org-capture-templates-contexts' are the associated contexts
  8518. definitions."
  8519. (let ((contexts
  8520. ;; normalize contexts
  8521. (mapcar
  8522. (lambda(c) (cond ((listp (cadr c))
  8523. (list (car c) (car c) (nth 1 c)))
  8524. ((string= "" (cadr c))
  8525. (list (car c) (car c) (nth 2 c)))
  8526. (t c)))
  8527. contexts))
  8528. (a alist) r s)
  8529. ;; loop over all commands or templates
  8530. (dolist (c a)
  8531. (let (vrules repl)
  8532. (cond
  8533. ((not (assoc (car c) contexts))
  8534. (push c r))
  8535. ((and (assoc (car c) contexts)
  8536. (setq vrules (org-contextualize-validate-key
  8537. (car c) contexts)))
  8538. (mapc (lambda (vr)
  8539. (unless (equal (car vr) (cadr vr))
  8540. (setq repl vr)))
  8541. vrules)
  8542. (if (not repl) (push c r)
  8543. (push (cadr repl) s)
  8544. (push
  8545. (cons (car c)
  8546. (cdr (or (assoc (cadr repl) alist)
  8547. (error "Undefined key `%s' as contextual replacement for `%s'"
  8548. (cadr repl) (car c)))))
  8549. r))))))
  8550. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8551. (delq
  8552. nil
  8553. (delete-dups
  8554. (mapcar (lambda (x)
  8555. (let ((tpl (car x)))
  8556. (unless (delq
  8557. nil
  8558. (mapcar (lambda (y)
  8559. (equal y tpl))
  8560. s))
  8561. x)))
  8562. (reverse r))))))
  8563. (defun org-contextualize-validate-key (key contexts)
  8564. "Check CONTEXTS for agenda or capture KEY."
  8565. (let (res)
  8566. (dolist (r contexts)
  8567. (dolist (rr (car (last r)))
  8568. (when
  8569. (and (equal key (car r))
  8570. (if (functionp rr) (funcall rr)
  8571. (or (and (eq (car rr) 'in-file)
  8572. (buffer-file-name)
  8573. (string-match (cdr rr) (buffer-file-name)))
  8574. (and (eq (car rr) 'in-mode)
  8575. (string-match (cdr rr) (symbol-name major-mode)))
  8576. (and (eq (car rr) 'in-buffer)
  8577. (string-match (cdr rr) (buffer-name)))
  8578. (when (and (eq (car rr) 'not-in-file)
  8579. (buffer-file-name))
  8580. (not (string-match (cdr rr) (buffer-file-name))))
  8581. (when (eq (car rr) 'not-in-mode)
  8582. (not (string-match (cdr rr) (symbol-name major-mode))))
  8583. (when (eq (car rr) 'not-in-buffer)
  8584. (not (string-match (cdr rr) (buffer-name)))))))
  8585. (push r res))))
  8586. (delete-dups (delq nil res))))
  8587. (defun org-context-p (&rest contexts)
  8588. "Check if local context is any of CONTEXTS.
  8589. Possible values in the list of contexts are `table', `headline', and `item'."
  8590. (let ((pos (point)))
  8591. (goto-char (point-at-bol))
  8592. (prog1 (or (and (memq 'table contexts)
  8593. (looking-at "[ \t]*|"))
  8594. (and (memq 'headline contexts)
  8595. (looking-at org-outline-regexp))
  8596. (and (memq 'item contexts)
  8597. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8598. (and (memq 'item-body contexts)
  8599. (org-in-item-p)))
  8600. (goto-char pos))))
  8601. (defconst org-unique-local-variables
  8602. '(org-element--cache
  8603. org-element--cache-objects
  8604. org-element--cache-sync-keys
  8605. org-element--cache-sync-requests
  8606. org-element--cache-sync-timer)
  8607. "List of local variables that cannot be transferred to another buffer.")
  8608. (defun org-get-local-variables ()
  8609. "Return a list of all local variables in an Org mode buffer."
  8610. (delq nil
  8611. (mapcar
  8612. (lambda (x)
  8613. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8614. (name (car binding)))
  8615. (and (not (get name 'org-state))
  8616. (not (memq name org-unique-local-variables))
  8617. (string-match-p
  8618. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8619. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8620. (symbol-name name))
  8621. binding)))
  8622. (with-temp-buffer
  8623. (org-mode)
  8624. (buffer-local-variables)))))
  8625. (defun org-clone-local-variables (from-buffer &optional regexp)
  8626. "Clone local variables from FROM-BUFFER.
  8627. Optional argument REGEXP selects variables to clone."
  8628. (dolist (pair (buffer-local-variables from-buffer))
  8629. (let ((name (car pair)))
  8630. (when (and (symbolp name)
  8631. (not (memq name org-unique-local-variables))
  8632. (or (null regexp) (string-match regexp (symbol-name name))))
  8633. (set (make-local-variable name) (cdr pair))))))
  8634. ;;;###autoload
  8635. (defun org-run-like-in-org-mode (cmd)
  8636. "Run a command, pretending that the current buffer is in Org-mode.
  8637. This will temporarily bind local variables that are typically bound in
  8638. Org mode to the values they have in Org-mode, and then interactively
  8639. call CMD."
  8640. (org-load-modules-maybe)
  8641. (unless org-local-vars
  8642. (setq org-local-vars (org-get-local-variables)))
  8643. (let (binds)
  8644. (dolist (var org-local-vars)
  8645. (when (or (not (boundp (car var)))
  8646. (eq (symbol-value (car var))
  8647. (default-value (car var))))
  8648. (push (list (car var) `(quote ,(cadr var))) binds)))
  8649. (eval `(let ,binds
  8650. (call-interactively (quote ,cmd))))))
  8651. (defun org-get-category (&optional pos force-refresh)
  8652. "Get the category applying to position POS."
  8653. (save-match-data
  8654. (when force-refresh (org-refresh-category-properties))
  8655. (let ((pos (or pos (point))))
  8656. (or (get-text-property pos 'org-category)
  8657. (progn (org-refresh-category-properties)
  8658. (get-text-property pos 'org-category))))))
  8659. ;;; Refresh properties
  8660. (defun org-refresh-properties (dprop tprop)
  8661. "Refresh buffer text properties.
  8662. DPROP is the drawer property and TPROP is either the
  8663. corresponding text property to set, or an alist with each element
  8664. being a text property (as a symbol) and a function to apply to
  8665. the value of the drawer property."
  8666. (let ((case-fold-search t)
  8667. (inhibit-read-only t))
  8668. (org-with-silent-modifications
  8669. (org-with-wide-buffer
  8670. (goto-char (point-min))
  8671. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8672. (org-refresh-property tprop (match-string-no-properties 1)))))))
  8673. (defun org-refresh-property (tprop p)
  8674. "Refresh the buffer text property TPROP from the drawer property P.
  8675. The refresh happens only for the current tree (not subtree)."
  8676. (unless (org-before-first-heading-p)
  8677. (save-excursion
  8678. (org-back-to-heading t)
  8679. (if (symbolp tprop)
  8680. ;; TPROP is a text property symbol
  8681. (put-text-property
  8682. (point) (or (outline-next-heading) (point-max)) tprop p)
  8683. ;; TPROP is an alist with (properties . function) elements
  8684. (dolist (al tprop)
  8685. (save-excursion
  8686. (put-text-property
  8687. (line-beginning-position) (or (outline-next-heading) (point-max))
  8688. (car al)
  8689. (funcall (cdr al) p))))))))
  8690. (defun org-refresh-category-properties ()
  8691. "Refresh category text properties in the buffer."
  8692. (let ((case-fold-search t)
  8693. (inhibit-read-only t)
  8694. (default-category
  8695. (cond ((null org-category)
  8696. (if buffer-file-name
  8697. (file-name-sans-extension
  8698. (file-name-nondirectory buffer-file-name))
  8699. "???"))
  8700. ((symbolp org-category) (symbol-name org-category))
  8701. (t org-category))))
  8702. (org-with-silent-modifications
  8703. (org-with-wide-buffer
  8704. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8705. ;; This is the default category for the buffer. If none is
  8706. ;; found, fall-back to `org-category' or buffer file name.
  8707. (put-text-property
  8708. (point-min) (point-max)
  8709. 'org-category
  8710. (catch 'buffer-category
  8711. (goto-char (point-max))
  8712. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8713. (let ((element (org-element-at-point)))
  8714. (when (eq (org-element-type element) 'keyword)
  8715. (throw 'buffer-category
  8716. (org-element-property :value element)))))
  8717. default-category))
  8718. ;; Set sub-tree specific categories.
  8719. (goto-char (point-min))
  8720. (let ((regexp (org-re-property "CATEGORY")))
  8721. (while (re-search-forward regexp nil t)
  8722. (let ((value (match-string-no-properties 3)))
  8723. (when (org-at-property-p)
  8724. (put-text-property
  8725. (save-excursion (org-back-to-heading t) (point))
  8726. (save-excursion (org-end-of-subtree t t) (point))
  8727. 'org-category
  8728. value)))))))))
  8729. (defun org-refresh-stats-properties ()
  8730. "Refresh stats text properties in the buffer."
  8731. (let (stats)
  8732. (org-with-silent-modifications
  8733. (org-with-wide-buffer
  8734. (goto-char (point-min))
  8735. (while (re-search-forward
  8736. (concat org-outline-regexp-bol ".*"
  8737. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8738. nil t)
  8739. (setq stats (cond ((equal (match-string 3) "0") 0)
  8740. ((match-string 2)
  8741. (/ (* (string-to-number (match-string 2)) 100)
  8742. (string-to-number (match-string 3))))
  8743. (t (string-to-number (match-string 1)))))
  8744. (org-back-to-heading t)
  8745. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8746. 'org-stats stats))))))
  8747. (defun org-refresh-effort-properties ()
  8748. "Refresh effort properties"
  8749. (org-refresh-properties
  8750. org-effort-property
  8751. '((effort . identity)
  8752. (effort-minutes . org-duration-string-to-minutes))))
  8753. ;;;; Link Stuff
  8754. ;;; Link abbreviations
  8755. (defun org-link-expand-abbrev (link)
  8756. "Apply replacements as defined in `org-link-abbrev-alist'."
  8757. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8758. (let* ((key (match-string 1 link))
  8759. (as (or (assoc key org-link-abbrev-alist-local)
  8760. (assoc key org-link-abbrev-alist)))
  8761. (tag (and (match-end 2) (match-string 3 link)))
  8762. rpl)
  8763. (if (not as)
  8764. link
  8765. (setq rpl (cdr as))
  8766. (cond
  8767. ((symbolp rpl) (funcall rpl tag))
  8768. ((string-match "%(\\([^)]+\\))" rpl)
  8769. (replace-match
  8770. (save-match-data
  8771. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8772. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8773. ((string-match "%h" rpl)
  8774. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8775. (t (concat rpl tag)))))
  8776. link))
  8777. ;;; Storing and inserting links
  8778. (defvar org-insert-link-history nil
  8779. "Minibuffer history for links inserted with `org-insert-link'.")
  8780. (defvar org-stored-links nil
  8781. "Contains the links stored with `org-store-link'.")
  8782. (defvar org-store-link-plist nil
  8783. "Plist with info about the most recently link created with `org-store-link'.")
  8784. (defun org-store-link-functions ()
  8785. "Return a list of functions that are called to create and store a link.
  8786. The functions defined in the :store property of
  8787. `org-link-parameters'.
  8788. Each function will be called in turn until one returns a non-nil
  8789. value. Each function should check if it is responsible for
  8790. creating this link (for example by looking at the major mode).
  8791. If not, it must exit and return nil. If yes, it should return
  8792. a non-nil value after calling `org-store-link-props' with a list
  8793. of properties and values. Special properties are:
  8794. :type The link prefix, like \"http\". This must be given.
  8795. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8796. This is obligatory as well.
  8797. :description Optional default description for the second pair
  8798. of brackets in an Org mode link. The user can still change
  8799. this when inserting this link into an Org mode buffer.
  8800. In addition to these, any additional properties can be specified
  8801. and then used in capture templates."
  8802. (cl-loop for link in org-link-parameters
  8803. with store-func
  8804. do (setq store-func (org-link-get-parameter (car link) :store))
  8805. if store-func
  8806. collect store-func))
  8807. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8808. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8809. ;;;###autoload
  8810. (defun org-store-link (arg)
  8811. "\\<org-mode-map>Store an org-link to the current location.
  8812. This link is added to `org-stored-links' and can later be inserted
  8813. into an Org buffer with \\[org-insert-link].
  8814. For some link types, a prefix ARG is interpreted.
  8815. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8816. For file links, ARG negates `org-context-in-file-links'.
  8817. A double prefix ARG force skipping storing functions that are not
  8818. part of Org's core.
  8819. A triple prefix ARG force storing a link for each line in the
  8820. active region."
  8821. (interactive "P")
  8822. (org-load-modules-maybe)
  8823. (if (and (equal arg '(64)) (org-region-active-p))
  8824. (save-excursion
  8825. (let ((end (region-end)))
  8826. (goto-char (region-beginning))
  8827. (set-mark (point))
  8828. (while (< (point-at-eol) end)
  8829. (move-end-of-line 1) (activate-mark)
  8830. (let (current-prefix-arg)
  8831. (call-interactively 'org-store-link))
  8832. (move-beginning-of-line 2)
  8833. (set-mark (point)))))
  8834. (setq org-store-link-plist nil)
  8835. (let (link cpltxt desc description search
  8836. txt custom-id agenda-link sfuns sfunsn)
  8837. (cond
  8838. ;; Store a link using an external link type
  8839. ((and (not (equal arg '(16)))
  8840. (setq sfuns
  8841. (delq
  8842. nil (mapcar (lambda (f)
  8843. (let (fs) (if (funcall f) (push f fs))))
  8844. (org-store-link-functions)))
  8845. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8846. (or (and (cdr sfuns)
  8847. (funcall (intern
  8848. (completing-read
  8849. "Which function for creating the link? "
  8850. sfunsn nil t (car sfunsn)))))
  8851. (funcall (caar sfuns)))
  8852. (setq link (plist-get org-store-link-plist :link)
  8853. desc (or (plist-get org-store-link-plist
  8854. :description)
  8855. link))))
  8856. ;; Store a link from a source code buffer.
  8857. ((org-src-edit-buffer-p)
  8858. (let ((coderef-format (org-src-coderef-format)))
  8859. (cond ((save-excursion
  8860. (beginning-of-line)
  8861. (looking-at (org-src-coderef-regexp coderef-format)))
  8862. (setq link (format "(%s)" (match-string-no-properties 3))))
  8863. ((called-interactively-p 'any)
  8864. (let ((label (read-string "Code line label: ")))
  8865. (end-of-line)
  8866. (setq link (format coderef-format label))
  8867. (let ((gc (- 79 (length link))))
  8868. (if (< (current-column) gc)
  8869. (org-move-to-column gc t)
  8870. (insert " ")))
  8871. (insert link)
  8872. (setq link (concat "(" label ")"))
  8873. (setq desc nil)))
  8874. (t (setq link nil)))))
  8875. ;; We are in the agenda, link to referenced location
  8876. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8877. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8878. (get-text-property (point) 'org-marker))))
  8879. (when m
  8880. (org-with-point-at m
  8881. (setq agenda-link
  8882. (if (called-interactively-p 'any)
  8883. (call-interactively 'org-store-link)
  8884. (org-store-link nil)))))))
  8885. ((eq major-mode 'calendar-mode)
  8886. (let ((cd (calendar-cursor-to-date)))
  8887. (setq link
  8888. (format-time-string
  8889. (car org-time-stamp-formats)
  8890. (apply 'encode-time
  8891. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8892. nil nil nil))))
  8893. (org-store-link-props :type "calendar" :date cd)))
  8894. ((eq major-mode 'help-mode)
  8895. (setq link (concat "help:" (save-excursion
  8896. (goto-char (point-min))
  8897. (looking-at "^[^ ]+")
  8898. (match-string 0))))
  8899. (org-store-link-props :type "help"))
  8900. ((eq major-mode 'w3-mode)
  8901. (setq cpltxt (if (and (buffer-name)
  8902. (not (string-match "Untitled" (buffer-name))))
  8903. (buffer-name)
  8904. (url-view-url t))
  8905. link (url-view-url t))
  8906. (org-store-link-props :type "w3" :url (url-view-url t)))
  8907. ((eq major-mode 'image-mode)
  8908. (setq cpltxt (concat "file:"
  8909. (abbreviate-file-name buffer-file-name))
  8910. link cpltxt)
  8911. (org-store-link-props :type "image" :file buffer-file-name))
  8912. ;; In dired, store a link to the file of the current line
  8913. ((derived-mode-p 'dired-mode)
  8914. (let ((file (dired-get-filename nil t)))
  8915. (setq file (if file
  8916. (abbreviate-file-name
  8917. (expand-file-name (dired-get-filename nil t)))
  8918. ;; otherwise, no file so use current directory.
  8919. default-directory))
  8920. (setq cpltxt (concat "file:" file)
  8921. link cpltxt)))
  8922. ((setq search (run-hook-with-args-until-success
  8923. 'org-create-file-search-functions))
  8924. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8925. "::" search))
  8926. (setq cpltxt (or description link)))
  8927. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8928. (org-with-limited-levels
  8929. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8930. (cond
  8931. ;; Store a link using the target at point
  8932. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8933. (setq cpltxt
  8934. (concat "file:"
  8935. (abbreviate-file-name
  8936. (buffer-file-name (buffer-base-buffer)))
  8937. "::" (match-string 1))
  8938. link cpltxt))
  8939. ((and (featurep 'org-id)
  8940. (or (eq org-id-link-to-org-use-id t)
  8941. (and (called-interactively-p 'any)
  8942. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8943. (and (eq org-id-link-to-org-use-id
  8944. 'create-if-interactive-and-no-custom-id)
  8945. (not custom-id))))
  8946. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8947. ;; Store a link using the ID at point
  8948. (setq link (condition-case nil
  8949. (prog1 (org-id-store-link)
  8950. (setq desc (or (plist-get org-store-link-plist
  8951. :description)
  8952. "")))
  8953. (error
  8954. ;; Probably before first headline, link only to file
  8955. (concat "file:"
  8956. (abbreviate-file-name
  8957. (buffer-file-name (buffer-base-buffer))))))))
  8958. (t
  8959. ;; Just link to current headline
  8960. (setq cpltxt (concat "file:"
  8961. (abbreviate-file-name
  8962. (buffer-file-name (buffer-base-buffer)))))
  8963. ;; Add a context search string
  8964. (when (org-xor org-context-in-file-links arg)
  8965. (let* ((element (org-element-at-point))
  8966. (name (org-element-property :name element)))
  8967. (setq txt (cond
  8968. ((org-at-heading-p) nil)
  8969. (name)
  8970. ((org-region-active-p)
  8971. (buffer-substring (region-beginning) (region-end)))))
  8972. (when (or (null txt) (string-match "\\S-" txt))
  8973. (setq cpltxt
  8974. (concat cpltxt "::"
  8975. (condition-case nil
  8976. (org-make-org-heading-search-string txt)
  8977. (error "")))
  8978. desc (or name
  8979. (nth 4 (ignore-errors (org-heading-components)))
  8980. "NONE")))))
  8981. (when (string-match "::\\'" cpltxt)
  8982. (setq cpltxt (substring cpltxt 0 -2)))
  8983. (setq link cpltxt)))))
  8984. ((buffer-file-name (buffer-base-buffer))
  8985. ;; Just link to this file here.
  8986. (setq cpltxt (concat "file:"
  8987. (abbreviate-file-name
  8988. (buffer-file-name (buffer-base-buffer)))))
  8989. ;; Add a context string.
  8990. (when (org-xor org-context-in-file-links arg)
  8991. (setq txt (if (org-region-active-p)
  8992. (buffer-substring (region-beginning) (region-end))
  8993. (buffer-substring (point-at-bol) (point-at-eol))))
  8994. ;; Only use search option if there is some text.
  8995. (when (string-match "\\S-" txt)
  8996. (setq cpltxt
  8997. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8998. desc "NONE")))
  8999. (setq link cpltxt))
  9000. ((called-interactively-p 'interactive)
  9001. (user-error "No method for storing a link from this buffer"))
  9002. (t (setq link nil)))
  9003. ;; We're done setting link and desc, clean up
  9004. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9005. (setq link (or link cpltxt)
  9006. desc (or desc cpltxt))
  9007. (cond ((not desc))
  9008. ((equal desc "NONE") (setq desc nil))
  9009. (t (setq desc
  9010. (replace-regexp-in-string
  9011. org-bracket-link-analytic-regexp
  9012. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9013. desc))))
  9014. ;; Return the link
  9015. (if (not (and (or (called-interactively-p 'any)
  9016. executing-kbd-macro)
  9017. link))
  9018. (or agenda-link (and link (org-make-link-string link desc)))
  9019. (push (list link desc) org-stored-links)
  9020. (message "Stored: %s" (or desc link))
  9021. (when custom-id
  9022. (setq link (concat "file:" (abbreviate-file-name
  9023. (buffer-file-name)) "::#" custom-id))
  9024. (push (list link desc) org-stored-links))
  9025. (car org-stored-links)))))
  9026. (defun org-store-link-props (&rest plist)
  9027. "Store link properties, extract names, addresses and dates."
  9028. (let ((x (plist-get plist :from)))
  9029. (when x
  9030. (let ((adr (mail-extract-address-components x)))
  9031. (setq plist (plist-put plist :fromname (car adr)))
  9032. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9033. (let ((x (plist-get plist :to)))
  9034. (when x
  9035. (let ((adr (mail-extract-address-components x)))
  9036. (setq plist (plist-put plist :toname (car adr)))
  9037. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9038. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9039. (when x
  9040. (setq plist (plist-put plist :date-timestamp
  9041. (format-time-string
  9042. (org-time-stamp-format t) x)))
  9043. (setq plist (plist-put plist :date-timestamp-inactive
  9044. (format-time-string
  9045. (org-time-stamp-format t t) x)))))
  9046. (let ((from (plist-get plist :from))
  9047. (to (plist-get plist :to)))
  9048. (when (and from to org-from-is-user-regexp)
  9049. (setq plist
  9050. (plist-put plist :fromto
  9051. (if (string-match org-from-is-user-regexp from)
  9052. (concat "to %t")
  9053. (concat "from %f"))))))
  9054. (setq org-store-link-plist plist))
  9055. (defun org-add-link-props (&rest plist)
  9056. "Add these properties to the link property list."
  9057. (let (key value)
  9058. (while plist
  9059. (setq key (pop plist) value (pop plist))
  9060. (setq org-store-link-plist
  9061. (plist-put org-store-link-plist key value)))))
  9062. (defun org-email-link-description (&optional fmt)
  9063. "Return the description part of an email link.
  9064. This takes information from `org-store-link-plist' and formats it
  9065. according to FMT (default from `org-email-link-description-format')."
  9066. (setq fmt (or fmt org-email-link-description-format))
  9067. (let* ((p org-store-link-plist)
  9068. (to (plist-get p :toaddress))
  9069. (from (plist-get p :fromaddress))
  9070. (table
  9071. (list
  9072. (cons "%c" (plist-get p :fromto))
  9073. (cons "%F" (plist-get p :from))
  9074. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9075. (cons "%T" (plist-get p :to))
  9076. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9077. (cons "%s" (plist-get p :subject))
  9078. (cons "%d" (plist-get p :date))
  9079. (cons "%m" (plist-get p :message-id)))))
  9080. (when (string-match "%c" fmt)
  9081. ;; Check if the user wrote this message
  9082. (if (and org-from-is-user-regexp from to
  9083. (save-match-data (string-match org-from-is-user-regexp from)))
  9084. (setq fmt (replace-match "to %t" t t fmt))
  9085. (setq fmt (replace-match "from %f" t t fmt))))
  9086. (org-replace-escapes fmt table)))
  9087. (defun org-make-org-heading-search-string (&optional string)
  9088. "Make search string for the current headline or STRING."
  9089. (let ((s (or string
  9090. (and (derived-mode-p 'org-mode)
  9091. (save-excursion
  9092. (org-back-to-heading t)
  9093. (org-element-property :raw-value (org-element-at-point))))))
  9094. (lines org-context-in-file-links))
  9095. (or string (setq s (concat "*" s))) ; Add * for headlines
  9096. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9097. (when (and string (integerp lines) (> lines 0))
  9098. (let ((slines (org-split-string s "\n")))
  9099. (when (< lines (length slines))
  9100. (setq s (mapconcat
  9101. 'identity
  9102. (reverse (nthcdr (- (length slines) lines)
  9103. (reverse slines))) "\n")))))
  9104. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9105. (defun org-make-link-string (link &optional description)
  9106. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9107. (unless (org-string-nw-p link) (error "Empty link"))
  9108. (let ((uri (cond ((string-match org-link-types-re link)
  9109. (concat (match-string 1 link)
  9110. (org-link-escape (substring link (match-end 1)))))
  9111. ;; For readability, url-encode internal links only
  9112. ;; when absolutely needed (i.e, when they contain
  9113. ;; square brackets). File links however, are
  9114. ;; encoded since, e.g., spaces are significant.
  9115. ((or (file-name-absolute-p link)
  9116. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9117. (org-link-escape link))
  9118. (t link)))
  9119. (description
  9120. (and (org-string-nw-p description)
  9121. ;; Remove brackets from description, as they are fatal.
  9122. (replace-regexp-in-string
  9123. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9124. (org-trim description)))))
  9125. (format "[[%s]%s]"
  9126. uri
  9127. (if description (format "[%s]" description) ""))))
  9128. (defconst org-link-escape-chars
  9129. ;;%20 %5B %5D %25
  9130. '(?\s ?\[ ?\] ?%)
  9131. "List of characters that should be escaped in a link when stored to Org.
  9132. This is the list that is used for internal purposes.")
  9133. (defun org-link-escape (text &optional table merge)
  9134. "Return percent escaped representation of TEXT.
  9135. TEXT is a string with the text to escape.
  9136. Optional argument TABLE is a list with characters that should be
  9137. escaped. When nil, `org-link-escape-chars' is used.
  9138. If optional argument MERGE is set, merge TABLE into
  9139. `org-link-escape-chars'."
  9140. (let ((characters-to-encode
  9141. (cond ((null table) org-link-escape-chars)
  9142. (merge (append org-link-escape-chars table))
  9143. (t table))))
  9144. (mapconcat
  9145. (lambda (c)
  9146. (if (or (memq c characters-to-encode)
  9147. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9148. (mapconcat (lambda (e) (format "%%%.2X" e))
  9149. (or (encode-coding-char c 'utf-8)
  9150. (error "Unable to percent escape character: %c" c))
  9151. "")
  9152. (char-to-string c)))
  9153. text "")))
  9154. (defun org-link-unescape (str)
  9155. "Unhex hexified Unicode parts in string STR.
  9156. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9157. reciprocal of `org-link-escape', which see."
  9158. (if (org-string-nw-p str)
  9159. (replace-regexp-in-string
  9160. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9161. str))
  9162. (defun org-link-unescape-compound (hex)
  9163. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9164. Note: this function also decodes single byte encodings like
  9165. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9166. (save-match-data
  9167. (let* ((bytes (cdr (split-string hex "%")))
  9168. (ret "")
  9169. (eat 0)
  9170. (sum 0))
  9171. (while bytes
  9172. (let* ((val (string-to-number (pop bytes) 16))
  9173. (shift-xor
  9174. (if (= 0 eat)
  9175. (cond
  9176. ((>= val 252) (cons 6 252))
  9177. ((>= val 248) (cons 5 248))
  9178. ((>= val 240) (cons 4 240))
  9179. ((>= val 224) (cons 3 224))
  9180. ((>= val 192) (cons 2 192))
  9181. (t (cons 0 0)))
  9182. (cons 6 128))))
  9183. (when (>= val 192) (setq eat (car shift-xor)))
  9184. (setq val (logxor val (cdr shift-xor)))
  9185. (setq sum (+ (lsh sum (car shift-xor)) val))
  9186. (when (> eat 0) (setq eat (- eat 1)))
  9187. (cond
  9188. ((= 0 eat) ;multi byte
  9189. (setq ret (concat ret (char-to-string sum)))
  9190. (setq sum 0))
  9191. ((not bytes) ; single byte(s)
  9192. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9193. ret)))
  9194. (defun org-link-unescape-single-byte-sequence (hex)
  9195. "Unhexify hex-encoded single byte character sequences."
  9196. (mapconcat (lambda (byte)
  9197. (char-to-string (string-to-number byte 16)))
  9198. (cdr (split-string hex "%")) ""))
  9199. (defun org-xor (a b)
  9200. "Exclusive or."
  9201. (if a (not b) b))
  9202. (defun org-fixup-message-id-for-http (s)
  9203. "Replace special characters in a message id, so it can be used in an http query."
  9204. (when (string-match "%" s)
  9205. (setq s (mapconcat (lambda (c)
  9206. (if (eq c ?%)
  9207. "%25"
  9208. (char-to-string c)))
  9209. s "")))
  9210. (while (string-match "<" s)
  9211. (setq s (replace-match "%3C" t t s)))
  9212. (while (string-match ">" s)
  9213. (setq s (replace-match "%3E" t t s)))
  9214. (while (string-match "@" s)
  9215. (setq s (replace-match "%40" t t s)))
  9216. s)
  9217. (defun org-link-prettify (link)
  9218. "Return a human-readable representation of LINK.
  9219. The car of LINK must be a raw link.
  9220. The cdr of LINK must be either a link description or nil."
  9221. (let ((desc (or (cadr link) "<no description>")))
  9222. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9223. "<" (car link) ">")))
  9224. ;;;###autoload
  9225. (defun org-insert-link-global ()
  9226. "Insert a link like Org mode does.
  9227. This command can be called in any mode to insert a link in Org syntax."
  9228. (interactive)
  9229. (org-load-modules-maybe)
  9230. (org-run-like-in-org-mode 'org-insert-link))
  9231. (defun org-insert-all-links (arg &optional pre post)
  9232. "Insert all links in `org-stored-links'.
  9233. When a universal prefix, do not delete the links from `org-stored-links'.
  9234. When `ARG' is a number, insert the last N link(s).
  9235. `PRE' and `POST' are optional arguments to define a string to
  9236. prepend or to append."
  9237. (interactive "P")
  9238. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9239. (links (copy-sequence org-stored-links))
  9240. (pr (or pre "- "))
  9241. (po (or post "\n"))
  9242. (cnt 1) l)
  9243. (if (null org-stored-links)
  9244. (message "No link to insert")
  9245. (while (and (or (listp arg) (>= arg cnt))
  9246. (setq l (if (listp arg)
  9247. (pop links)
  9248. (pop org-stored-links))))
  9249. (setq cnt (1+ cnt))
  9250. (insert pr)
  9251. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9252. (insert po)))))
  9253. (defun org-insert-last-stored-link (arg)
  9254. "Insert the last link stored in `org-stored-links'."
  9255. (interactive "p")
  9256. (org-insert-all-links arg "" "\n"))
  9257. (defun org-link-fontify-links-to-this-file ()
  9258. "Fontify links to the current file in `org-stored-links'."
  9259. (let ((f (buffer-file-name)) a b)
  9260. (setq a (mapcar (lambda(l)
  9261. (let ((ll (car l)))
  9262. (when (and (string-match "^file:\\(.+\\)::" ll)
  9263. (equal f (expand-file-name (match-string 1 ll))))
  9264. ll)))
  9265. org-stored-links))
  9266. (when (featurep 'org-id)
  9267. (setq b (mapcar (lambda(l)
  9268. (let ((ll (car l)))
  9269. (when (and (string-match "^id:\\(.+\\)$" ll)
  9270. (equal f (expand-file-name
  9271. (or (org-id-find-id-file
  9272. (match-string 1 ll)) ""))))
  9273. ll)))
  9274. org-stored-links)))
  9275. (mapcar (lambda(l)
  9276. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9277. (delq nil (append a b)))))
  9278. (defvar org--links-history nil)
  9279. (defun org-insert-link (&optional complete-file link-location default-description)
  9280. "Insert a link. At the prompt, enter the link.
  9281. Completion can be used to insert any of the link protocol prefixes like
  9282. http or ftp in use.
  9283. The history can be used to select a link previously stored with
  9284. `org-store-link'. When the empty string is entered (i.e. if you just
  9285. press RET at the prompt), the link defaults to the most recently
  9286. stored link. As SPC triggers completion in the minibuffer, you need to
  9287. use M-SPC or C-q SPC to force the insertion of a space character.
  9288. You will also be prompted for a description, and if one is given, it will
  9289. be displayed in the buffer instead of the link.
  9290. If there is already a link at point, this command will allow you to edit link
  9291. and description parts.
  9292. With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
  9293. be selected using completion. The path to the file will be relative to the
  9294. current directory if the file is in the current directory or a subdirectory.
  9295. Otherwise, the link will be the absolute path as completed in the minibuffer
  9296. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9297. option `org-link-file-path-type'.
  9298. With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
  9299. the current directory or below.
  9300. With three \\[universal-argument] prefixes, negate the meaning of
  9301. `org-keep-stored-link-after-insertion'.
  9302. If `org-make-link-description-function' is non-nil, this function will be
  9303. called with the link target, and the result will be the default
  9304. link description.
  9305. If the LINK-LOCATION parameter is non-nil, this value will be
  9306. used as the link location instead of reading one interactively.
  9307. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9308. be used as the default description."
  9309. (interactive "P")
  9310. (let* ((wcf (current-window-configuration))
  9311. (origbuf (current-buffer))
  9312. (region (when (org-region-active-p)
  9313. (buffer-substring (region-beginning) (region-end))))
  9314. (remove (and region (list (region-beginning) (region-end))))
  9315. (desc region)
  9316. (link link-location)
  9317. (abbrevs org-link-abbrev-alist-local)
  9318. entry all-prefixes auto-desc)
  9319. (cond
  9320. (link-location) ; specified by arg, just use it.
  9321. ((org-in-regexp org-bracket-link-regexp 1)
  9322. ;; We do have a link at point, and we are going to edit it.
  9323. (setq remove (list (match-beginning 0) (match-end 0)))
  9324. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9325. (setq link (read-string "Link: "
  9326. (org-link-unescape
  9327. (match-string-no-properties 1)))))
  9328. ((or (org-in-regexp org-angle-link-re)
  9329. (org-in-regexp org-plain-link-re))
  9330. ;; Convert to bracket link
  9331. (setq remove (list (match-beginning 0) (match-end 0))
  9332. link (read-string "Link: "
  9333. (org-unbracket-string "<" ">" (match-string 0)))))
  9334. ((member complete-file '((4) (16)))
  9335. ;; Completing read for file names.
  9336. (setq link (org-file-complete-link complete-file)))
  9337. (t
  9338. ;; Read link, with completion for stored links.
  9339. (org-link-fontify-links-to-this-file)
  9340. (org-switch-to-buffer-other-window "*Org Links*")
  9341. (with-current-buffer "*Org Links*"
  9342. (erase-buffer)
  9343. (insert "Insert a link.
  9344. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9345. (when org-stored-links
  9346. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9347. (insert (mapconcat 'org-link-prettify
  9348. (reverse org-stored-links) "\n")))
  9349. (goto-char (point-min)))
  9350. (let ((cw (selected-window)))
  9351. (select-window (get-buffer-window "*Org Links*" 'visible))
  9352. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9353. (unless (pos-visible-in-window-p (point-max))
  9354. (org-fit-window-to-buffer))
  9355. (and (window-live-p cw) (select-window cw)))
  9356. (setq all-prefixes (append (mapcar 'car abbrevs)
  9357. (mapcar 'car org-link-abbrev-alist)
  9358. (org-link-types)))
  9359. (unwind-protect
  9360. ;; Fake a link history, containing the stored links.
  9361. (let ((org--links-history
  9362. (append (mapcar #'car org-stored-links)
  9363. org-insert-link-history)))
  9364. (setq link
  9365. (org-completing-read
  9366. "Link: "
  9367. (append
  9368. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9369. (mapcar #'car org-stored-links))
  9370. nil nil nil
  9371. 'org--links-history
  9372. (caar org-stored-links)))
  9373. (unless (org-string-nw-p link) (user-error "No link selected"))
  9374. (dolist (l org-stored-links)
  9375. (when (equal link (cadr l))
  9376. (setq link (car l))
  9377. (setq auto-desc t)))
  9378. (when (or (member link all-prefixes)
  9379. (and (equal ":" (substring link -1))
  9380. (member (substring link 0 -1) all-prefixes)
  9381. (setq link (substring link 0 -1))))
  9382. (setq link (with-current-buffer origbuf
  9383. (org-link-try-special-completion link)))))
  9384. (set-window-configuration wcf)
  9385. (kill-buffer "*Org Links*"))
  9386. (setq entry (assoc link org-stored-links))
  9387. (or entry (push link org-insert-link-history))
  9388. (setq desc (or desc (nth 1 entry)))))
  9389. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9390. (not org-keep-stored-link-after-insertion))
  9391. (setq org-stored-links (delq (assoc link org-stored-links)
  9392. org-stored-links)))
  9393. (when (and (string-match org-plain-link-re link)
  9394. (not (string-match org-ts-regexp link)))
  9395. ;; URL-like link, normalize the use of angular brackets.
  9396. (setq link (org-unbracket-string "<" ">" link)))
  9397. ;; Check if we are linking to the current file with a search
  9398. ;; option If yes, simplify the link by using only the search
  9399. ;; option.
  9400. (when (and buffer-file-name
  9401. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9402. (let* ((path (match-string 1 link))
  9403. (case-fold-search nil)
  9404. (search (match-string 2 link)))
  9405. (save-match-data
  9406. (when (equal (file-truename buffer-file-name) (file-truename path))
  9407. ;; We are linking to this same file, with a search option
  9408. (setq link search)))))
  9409. ;; Check if we can/should use a relative path. If yes, simplify the link
  9410. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9411. (let* ((type (match-string 1 link))
  9412. (path (match-string 2 link))
  9413. (origpath path)
  9414. (case-fold-search nil))
  9415. (cond
  9416. ((or (eq org-link-file-path-type 'absolute)
  9417. (equal complete-file '(16)))
  9418. (setq path (abbreviate-file-name (expand-file-name path))))
  9419. ((eq org-link-file-path-type 'noabbrev)
  9420. (setq path (expand-file-name path)))
  9421. ((eq org-link-file-path-type 'relative)
  9422. (setq path (file-relative-name path)))
  9423. (t
  9424. (save-match-data
  9425. (if (string-match (concat "^" (regexp-quote
  9426. (expand-file-name
  9427. (file-name-as-directory
  9428. default-directory))))
  9429. (expand-file-name path))
  9430. ;; We are linking a file with relative path name.
  9431. (setq path (substring (expand-file-name path)
  9432. (match-end 0)))
  9433. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9434. (setq link (concat type path))
  9435. (when (equal desc origpath)
  9436. (setq desc path))))
  9437. (if org-make-link-description-function
  9438. (setq desc
  9439. (or (condition-case nil
  9440. (funcall org-make-link-description-function link desc)
  9441. (error (progn (message "Can't get link description from `%s'"
  9442. (symbol-name org-make-link-description-function))
  9443. (sit-for 2) nil)))
  9444. (read-string "Description: " default-description)))
  9445. (if default-description (setq desc default-description)
  9446. (setq desc (or (and auto-desc desc)
  9447. (read-string "Description: " desc)))))
  9448. (unless (string-match "\\S-" desc) (setq desc nil))
  9449. (when remove (apply 'delete-region remove))
  9450. (insert (org-make-link-string link desc))
  9451. ;; Redisplay so as the new link has proper invisible characters.
  9452. (sit-for 0)))
  9453. (defun org-link-try-special-completion (type)
  9454. "If there is completion support for link type TYPE, offer it."
  9455. (let ((fun (org-link-get-parameter type :complete)))
  9456. (if (functionp fun)
  9457. (funcall fun)
  9458. (read-string "Link (no completion support): " (concat type ":")))))
  9459. (defun org-file-complete-link (&optional arg)
  9460. "Create a file link using completion."
  9461. (let ((file (read-file-name "File: "))
  9462. (pwd (file-name-as-directory (expand-file-name ".")))
  9463. (pwd1 (file-name-as-directory (abbreviate-file-name
  9464. (expand-file-name ".")))))
  9465. (cond ((equal arg '(16))
  9466. (concat "file:"
  9467. (abbreviate-file-name (expand-file-name file))))
  9468. ((string-match
  9469. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9470. (concat "file:" (match-string 1 file)))
  9471. ((string-match
  9472. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9473. (expand-file-name file))
  9474. (concat "file:"
  9475. (match-string 1 (expand-file-name file))))
  9476. (t (concat "file:" file)))))
  9477. (defun org-completing-read (&rest args)
  9478. "Completing-read with SPACE being a normal character."
  9479. (let ((enable-recursive-minibuffers t)
  9480. (minibuffer-local-completion-map
  9481. (copy-keymap minibuffer-local-completion-map)))
  9482. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9483. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9484. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9485. 'org-time-stamp-inactive)
  9486. (apply #'completing-read args)))
  9487. ;;; Opening/following a link
  9488. (defvar org-link-search-failed nil)
  9489. (defvar org-open-link-functions nil
  9490. "Hook for functions finding a plain text link.
  9491. These functions must take a single argument, the link content.
  9492. They will be called for links that look like [[link text][description]]
  9493. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9494. like a filename (e.g. \"./blue.png\").
  9495. These functions will be called *before* Org attempts to resolve the
  9496. link by doing text searches in the current buffer - so if you want a
  9497. link \"[[target]]\" to still find \"<<target>>\", your function should
  9498. handle this as a special case.
  9499. When the function does handle the link, it must return a non-nil value.
  9500. If it decides that it is not responsible for this link, it must return
  9501. nil to indicate that that Org can continue with other options like
  9502. exact and fuzzy text search.")
  9503. (defun org-next-link (&optional search-backward)
  9504. "Move forward to the next link.
  9505. If the link is in hidden text, expose it."
  9506. (interactive "P")
  9507. (when (and org-link-search-failed (eq this-command last-command))
  9508. (goto-char (point-min))
  9509. (message "Link search wrapped back to beginning of buffer"))
  9510. (setq org-link-search-failed nil)
  9511. (let* ((pos (point))
  9512. (ct (org-context))
  9513. (a (assq :link ct))
  9514. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9515. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9516. ((looking-at org-any-link-re)
  9517. ;; Don't stay stuck at link without an org-link face
  9518. (forward-char (if search-backward -1 1))))
  9519. (if (funcall srch-fun org-any-link-re nil t)
  9520. (progn
  9521. (goto-char (match-beginning 0))
  9522. (when (outline-invisible-p) (org-show-context)))
  9523. (goto-char pos)
  9524. (setq org-link-search-failed t)
  9525. (message "No further link found"))))
  9526. (defun org-previous-link ()
  9527. "Move backward to the previous link.
  9528. If the link is in hidden text, expose it."
  9529. (interactive)
  9530. (funcall 'org-next-link t))
  9531. (defun org-translate-link (s)
  9532. "Translate a link string if a translation function has been defined."
  9533. (with-temp-buffer
  9534. (insert (org-trim s))
  9535. (org-trim (org-element-interpret-data (org-element-context)))))
  9536. (defun org-translate-link-from-planner (type path)
  9537. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9538. This is still an experimental function, your mileage may vary."
  9539. (cond
  9540. ((member type '("http" "https" "news" "ftp"))
  9541. ;; standard Internet links are the same.
  9542. nil)
  9543. ((and (equal type "irc") (string-match "^//" path))
  9544. ;; Planner has two / at the beginning of an irc link, we have 1.
  9545. ;; We should have zero, actually....
  9546. (setq path (substring path 1)))
  9547. ((and (equal type "lisp") (string-match "^/" path))
  9548. ;; Planner has a slash, we do not.
  9549. (setq type "elisp" path (substring path 1)))
  9550. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9551. ;; A typical message link. Planner has the id after the final slash,
  9552. ;; we separate it with a hash mark
  9553. (setq path (concat (match-string 1 path) "#"
  9554. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9555. (cons type path))
  9556. (defun org-find-file-at-mouse (ev)
  9557. "Open file link or URL at mouse."
  9558. (interactive "e")
  9559. (mouse-set-point ev)
  9560. (org-open-at-point 'in-emacs))
  9561. (defun org-open-at-mouse (ev)
  9562. "Open file link or URL at mouse.
  9563. See the docstring of `org-open-file' for details."
  9564. (interactive "e")
  9565. (mouse-set-point ev)
  9566. (when (eq major-mode 'org-agenda-mode)
  9567. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9568. (org-open-at-point))
  9569. (defvar org-window-config-before-follow-link nil
  9570. "The window configuration before following a link.
  9571. This is saved in case the need arises to restore it.")
  9572. ;;;###autoload
  9573. (defun org-open-at-point-global ()
  9574. "Follow a link or time-stamp like Org mode does.
  9575. This command can be called in any mode to follow an external link
  9576. or a time-stamp that has Org mode syntax. Its behavior is
  9577. undefined when called on internal links (e.g., fuzzy links).
  9578. Raise an error when there is nothing to follow. "
  9579. (interactive)
  9580. (cond ((org-in-regexp org-any-link-re)
  9581. (org-open-link-from-string (match-string-no-properties 0)))
  9582. ((or (org-in-regexp org-ts-regexp-both nil t)
  9583. (org-in-regexp org-tsr-regexp-both nil t))
  9584. (org-follow-timestamp-link))
  9585. (t (user-error "No link found"))))
  9586. ;;;###autoload
  9587. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9588. "Open a link in the string S, as if it was in Org-mode."
  9589. (interactive "sLink: \nP")
  9590. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9591. (with-temp-buffer
  9592. (let ((org-inhibit-startup (not reference-buffer)))
  9593. (org-mode)
  9594. (insert s)
  9595. (goto-char (point-min))
  9596. (when reference-buffer
  9597. (setq org-link-abbrev-alist-local
  9598. (with-current-buffer reference-buffer
  9599. org-link-abbrev-alist-local)))
  9600. (org-open-at-point arg reference-buffer)))))
  9601. (defvar org-open-at-point-functions nil
  9602. "Hook that is run when following a link at point.
  9603. Functions in this hook must return t if they identify and follow
  9604. a link at point. If they don't find anything interesting at point,
  9605. they must return nil.")
  9606. (defvar org-link-search-inhibit-query nil)
  9607. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9608. (defun org--open-doi-link (path)
  9609. "Open a \"doi\" type link.
  9610. PATH is a the path to search for, as a string."
  9611. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9612. (defun org--open-elisp-link (path)
  9613. "Open a \"elisp\" type link.
  9614. PATH is the sexp to evaluate, as a string."
  9615. (let ((cmd path))
  9616. (if (or (and (org-string-nw-p
  9617. org-confirm-elisp-link-not-regexp)
  9618. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9619. (not org-confirm-elisp-link-function)
  9620. (funcall org-confirm-elisp-link-function
  9621. (format "Execute \"%s\" as elisp? "
  9622. (org-add-props cmd nil 'face 'org-warning))))
  9623. (message "%s => %s" cmd
  9624. (if (eq (string-to-char cmd) ?\()
  9625. (eval (read cmd))
  9626. (call-interactively (read cmd))))
  9627. (user-error "Abort"))))
  9628. (defun org--open-help-link (path)
  9629. "Open a \"help\" type link.
  9630. PATH is a symbol name, as a string."
  9631. (pcase (intern path)
  9632. ((and (pred fboundp) variable) (describe-function variable))
  9633. ((and (pred boundp) function) (describe-variable function))
  9634. (name (user-error "Unknown function or variable: %s" name))))
  9635. (defun org--open-shell-link (path)
  9636. "Open a \"shell\" type link.
  9637. PATH is the command to execute, as a string."
  9638. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9639. (cmd path))
  9640. (if (or (and (org-string-nw-p
  9641. org-confirm-shell-link-not-regexp)
  9642. (string-match
  9643. org-confirm-shell-link-not-regexp cmd))
  9644. (not org-confirm-shell-link-function)
  9645. (funcall org-confirm-shell-link-function
  9646. (format "Execute \"%s\" in shell? "
  9647. (org-add-props cmd nil
  9648. 'face 'org-warning))))
  9649. (progn
  9650. (message "Executing %s" cmd)
  9651. (shell-command cmd buf)
  9652. (when (featurep 'midnight)
  9653. (setq clean-buffer-list-kill-buffer-names
  9654. (cons (buffer-name buf)
  9655. clean-buffer-list-kill-buffer-names))))
  9656. (user-error "Abort"))))
  9657. (defun org-open-at-point (&optional arg reference-buffer)
  9658. "Open link, timestamp, footnote or tags at point.
  9659. When point is on a link, follow it. Normally, files will be
  9660. opened by an appropriate application. If the optional prefix
  9661. argument ARG is non-nil, Emacs will visit the file. With
  9662. a double prefix argument, try to open outside of Emacs, in the
  9663. application the system uses for this file type.
  9664. When point is on a timestamp, open the agenda at the day
  9665. specified.
  9666. When point is a footnote definition, move to the first reference
  9667. found. If it is on a reference, move to the associated
  9668. definition.
  9669. When point is on a headline, display a list of every link in the
  9670. entry, so it is possible to pick one, or all, of them. If point
  9671. is on a tag, call `org-tags-view' instead.
  9672. When optional argument REFERENCE-BUFFER is non-nil, it should
  9673. specify a buffer from where the link search should happen. This
  9674. is used internally by `org-open-link-from-string'.
  9675. On top of syntactically correct links, this function will open
  9676. the link at point in comments or comment blocks and the first
  9677. link in a property drawer line."
  9678. (interactive "P")
  9679. ;; On a code block, open block's results.
  9680. (unless (call-interactively 'org-babel-open-src-block-result)
  9681. (org-load-modules-maybe)
  9682. (setq org-window-config-before-follow-link (current-window-configuration))
  9683. (org-remove-occur-highlights nil nil t)
  9684. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9685. (let* ((context
  9686. ;; Only consider supported types, even if they are not
  9687. ;; the closest one.
  9688. (org-element-lineage
  9689. (org-element-context)
  9690. '(clock comment comment-block footnote-definition
  9691. footnote-reference headline inlinetask keyword link
  9692. node-property timestamp)
  9693. t))
  9694. (type (org-element-type context))
  9695. (value (org-element-property :value context)))
  9696. (cond
  9697. ((not context) (user-error "No link found"))
  9698. ;; Exception: open timestamps and links in properties
  9699. ;; drawers, keywords and comments.
  9700. ((memq type '(comment comment-block keyword node-property))
  9701. (call-interactively #'org-open-at-point-global))
  9702. ;; On a headline or an inlinetask, but not on a timestamp,
  9703. ;; a link, a footnote reference or on tags.
  9704. ((and (memq type '(headline inlinetask))
  9705. ;; Not on tags.
  9706. (progn (save-excursion (beginning-of-line)
  9707. (looking-at org-complex-heading-regexp))
  9708. (or (not (match-beginning 5))
  9709. (< (point) (match-beginning 5)))))
  9710. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9711. (links (car data))
  9712. (links-end (cdr data)))
  9713. (if links
  9714. (dolist (link (if (stringp links) (list links) links))
  9715. (search-forward link nil links-end)
  9716. (goto-char (match-beginning 0))
  9717. (org-open-at-point))
  9718. (require 'org-attach)
  9719. (org-attach-reveal 'if-exists))))
  9720. ;; On a clock line, make sure point is on the timestamp
  9721. ;; before opening it.
  9722. ((and (eq type 'clock)
  9723. value
  9724. (>= (point) (org-element-property :begin value))
  9725. (<= (point) (org-element-property :end value)))
  9726. (org-follow-timestamp-link))
  9727. ;; Do nothing on white spaces after an object.
  9728. ((>= (point)
  9729. (save-excursion
  9730. (goto-char (org-element-property :end context))
  9731. (skip-chars-backward " \t")
  9732. (point)))
  9733. (user-error "No link found"))
  9734. ((eq type 'timestamp) (org-follow-timestamp-link))
  9735. ;; On tags within a headline or an inlinetask.
  9736. ((and (memq type '(headline inlinetask))
  9737. (progn (save-excursion (beginning-of-line)
  9738. (looking-at org-complex-heading-regexp))
  9739. (and (match-beginning 5)
  9740. (>= (point) (match-beginning 5)))))
  9741. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9742. ((eq type 'link)
  9743. ;; When link is located within the description of another
  9744. ;; link (e.g., an inline image), always open the parent
  9745. ;; link.
  9746. (let* ((link (let ((up (org-element-property :parent context)))
  9747. (if (eq (org-element-type up) 'link) up context)))
  9748. (type (org-element-property :type link))
  9749. (path (org-link-unescape (org-element-property :path link))))
  9750. ;; Switch back to REFERENCE-BUFFER needed when called in
  9751. ;; a temporary buffer through `org-open-link-from-string'.
  9752. (with-current-buffer (or reference-buffer (current-buffer))
  9753. (cond
  9754. ((equal type "file")
  9755. (if (string-match "[*?{]" (file-name-nondirectory path))
  9756. (dired path)
  9757. ;; Look into `org-link-parameters' in order to find
  9758. ;; a DEDICATED-FUNCTION to open file. The function
  9759. ;; will be applied on raw link instead of parsed
  9760. ;; link due to the limitation in `org-add-link-type'
  9761. ;; ("open" function called with a single argument).
  9762. ;; If no such function is found, fallback to
  9763. ;; `org-open-file'.
  9764. (let* ((option (org-element-property :search-option link))
  9765. (app (org-element-property :application link))
  9766. (dedicated-function
  9767. (org-link-get-parameter
  9768. (if app (concat type "+" app) type)
  9769. :follow)))
  9770. (if dedicated-function
  9771. (funcall dedicated-function
  9772. (concat path
  9773. (and option (concat "::" option))))
  9774. (apply #'org-open-file
  9775. path
  9776. (cond (arg)
  9777. ((equal app "emacs") 'emacs)
  9778. ((equal app "sys") 'system))
  9779. (cond ((not option) nil)
  9780. ((string-match-p "\\`[0-9]+\\'" option)
  9781. (list (string-to-number option)))
  9782. (t (list nil
  9783. (org-link-unescape option)))))))))
  9784. ((functionp (org-link-get-parameter type :follow))
  9785. (funcall (org-link-get-parameter type :follow) path))
  9786. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9787. (unless (run-hook-with-args-until-success
  9788. 'org-open-link-functions path)
  9789. (if (not arg) (org-mark-ring-push)
  9790. (switch-to-buffer-other-window
  9791. (org-get-buffer-for-internal-link (current-buffer))))
  9792. (let ((destination
  9793. (org-with-wide-buffer
  9794. (if (equal type "radio")
  9795. (org-search-radio-target
  9796. (org-element-property :path link))
  9797. (org-link-search
  9798. (if (member type '("custom-id" "coderef"))
  9799. (org-element-property :raw-link link)
  9800. path)
  9801. ;; Prevent fuzzy links from matching
  9802. ;; themselves.
  9803. (and (equal type "fuzzy")
  9804. (+ 2 (org-element-property :begin link)))))
  9805. (point))))
  9806. (unless (and (<= (point-min) destination)
  9807. (>= (point-max) destination))
  9808. (widen))
  9809. (goto-char destination))))
  9810. (t (browse-url-at-point))))))
  9811. ;; On a footnote reference or at a footnote definition's label.
  9812. ((or (eq type 'footnote-reference)
  9813. (and (eq type 'footnote-definition)
  9814. (save-excursion
  9815. ;; Do not validate action when point is on the
  9816. ;; spaces right after the footnote label, in
  9817. ;; order to be on par with behaviour on links.
  9818. (skip-chars-forward " \t")
  9819. (let ((begin
  9820. (org-element-property :contents-begin context)))
  9821. (if begin (< (point) begin)
  9822. (= (org-element-property :post-affiliated context)
  9823. (line-beginning-position)))))))
  9824. (org-footnote-action))
  9825. (t (user-error "No link found")))))
  9826. (run-hook-with-args 'org-follow-link-hook)))
  9827. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9828. "Offer links in the current entry and return the selected link.
  9829. If there is only one link, return it.
  9830. If NTH is an integer, return the NTH link found.
  9831. If ZERO is a string, check also this string for a link, and if
  9832. there is one, return it."
  9833. (with-current-buffer buffer
  9834. (org-with-wide-buffer
  9835. (goto-char marker)
  9836. (let ((cnt ?0)
  9837. have-zero end links link c)
  9838. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9839. (push (match-string 0 zero) links)
  9840. (setq cnt (1- cnt) have-zero t))
  9841. (save-excursion
  9842. (org-back-to-heading t)
  9843. (setq end (save-excursion (outline-next-heading) (point)))
  9844. (while (re-search-forward org-any-link-re end t)
  9845. (push (match-string 0) links))
  9846. (setq links (org-uniquify (reverse links))))
  9847. (cond
  9848. ((null links)
  9849. (message "No links"))
  9850. ((equal (length links) 1)
  9851. (setq link (car links)))
  9852. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9853. (setq link (nth (if have-zero nth (1- nth)) links)))
  9854. (t ; we have to select a link
  9855. (save-excursion
  9856. (save-window-excursion
  9857. (delete-other-windows)
  9858. (with-output-to-temp-buffer "*Select Link*"
  9859. (dolist (l links)
  9860. (cond
  9861. ((not (string-match org-bracket-link-regexp l))
  9862. (princ (format "[%c] %s\n" (cl-incf cnt)
  9863. (org-unbracket-string "<" ">" l))))
  9864. ((match-end 3)
  9865. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9866. (match-string 3 l) (match-string 1 l))))
  9867. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9868. (match-string 1 l)))))))
  9869. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9870. (message "Select link to open, RET to open all:")
  9871. (setq c (read-char-exclusive))
  9872. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9873. (when (equal c ?q) (user-error "Abort"))
  9874. (if (equal c ?\C-m)
  9875. (setq link links)
  9876. (setq nth (- c ?0))
  9877. (when have-zero (setq nth (1+ nth)))
  9878. (unless (and (integerp nth) (>= (length links) nth))
  9879. (user-error "Invalid link selection"))
  9880. (setq link (nth (1- nth) links)))))
  9881. (cons link end)))))
  9882. ;; TODO: These functions are deprecated since `org-open-at-point'
  9883. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9884. (defun org-open-file-with-system (path)
  9885. "Open file at PATH using the system way of opening it."
  9886. (org-open-file path 'system))
  9887. (defun org-open-file-with-emacs (path)
  9888. "Open file at PATH in Emacs."
  9889. (org-open-file path 'emacs))
  9890. ;;; File search
  9891. (defvar org-create-file-search-functions nil
  9892. "List of functions to construct the right search string for a file link.
  9893. These functions are called in turn with point at the location to
  9894. which the link should point.
  9895. A function in the hook should first test if it would like to
  9896. handle this file type, for example by checking the `major-mode'
  9897. or the file extension. If it decides not to handle this file, it
  9898. should just return nil to give other functions a chance. If it
  9899. does handle the file, it must return the search string to be used
  9900. when following the link. The search string will be part of the
  9901. file link, given after a double colon, and `org-open-at-point'
  9902. will automatically search for it. If special measures must be
  9903. taken to make the search successful, another function should be
  9904. added to the companion hook `org-execute-file-search-functions',
  9905. which see.
  9906. A function in this hook may also use `setq' to set the variable
  9907. `description' to provide a suggestion for the descriptive text to
  9908. be used for this link when it gets inserted into an Org buffer
  9909. with \\[org-insert-link].")
  9910. (defvar org-execute-file-search-functions nil
  9911. "List of functions to execute a file search triggered by a link.
  9912. Functions added to this hook must accept a single argument, the
  9913. search string that was part of the file link, the part after the
  9914. double colon. The function must first check if it would like to
  9915. handle this search, for example by checking the `major-mode' or
  9916. the file extension. If it decides not to handle this search, it
  9917. should just return nil to give other functions a chance. If it
  9918. does handle the search, it must return a non-nil value to keep
  9919. other functions from trying.
  9920. Each function can access the current prefix argument through the
  9921. variable `current-prefix-arg'. Note that a single prefix is used
  9922. to force opening a link in Emacs, so it may be good to only use a
  9923. numeric or double prefix to guide the search function.
  9924. In case this is needed, a function in this hook can also restore
  9925. the window configuration before `org-open-at-point' was called using:
  9926. \(set-window-configuration org-window-config-before-follow-link)")
  9927. (defun org-search-radio-target (target)
  9928. "Search a radio target matching TARGET in current buffer.
  9929. White spaces are not significant."
  9930. (let ((re (format "<<<%s>>>"
  9931. (mapconcat #'regexp-quote
  9932. (org-split-string target "[ \t\n]+")
  9933. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9934. (origin (point)))
  9935. (goto-char (point-min))
  9936. (catch :radio-match
  9937. (while (re-search-forward re nil t)
  9938. (backward-char)
  9939. (let ((object (org-element-context)))
  9940. (when (eq (org-element-type object) 'radio-target)
  9941. (goto-char (org-element-property :begin object))
  9942. (org-show-context 'link-search)
  9943. (throw :radio-match nil))))
  9944. (goto-char origin)
  9945. (user-error "No match for radio target: %s" target))))
  9946. (defun org-link-search (s &optional avoid-pos stealth)
  9947. "Search for a search string S.
  9948. If S starts with \"#\", it triggers a custom ID search.
  9949. If S is enclosed within parenthesis, it initiates a coderef
  9950. search.
  9951. If S is surrounded by forward slashes, it is interpreted as
  9952. a regular expression. In Org mode files, this will create an
  9953. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9954. to list matches. If the current buffer is in `dired-mode', grep
  9955. will be used to search in all files.
  9956. When AVOID-POS is given, ignore matches near that position.
  9957. When optional argument STEALTH is non-nil, do not modify
  9958. visibility around point, thus ignoring `org-show-context-detail'
  9959. variable.
  9960. Search is case-insensitive and ignores white spaces. Return type
  9961. of matched result, with is either `dedicated' or `fuzzy'."
  9962. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9963. (let* ((case-fold-search t)
  9964. (origin (point))
  9965. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9966. (words (org-split-string s "[ \t\n]+"))
  9967. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9968. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9969. type)
  9970. (cond
  9971. ;; Check if there are any special search functions.
  9972. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9973. ((eq (string-to-char s) ?#)
  9974. ;; Look for a custom ID S if S starts with "#".
  9975. (let* ((id (substring normalized 1))
  9976. (match (org-find-property "CUSTOM_ID" id)))
  9977. (if match (progn (goto-char match) (setf type 'dedicated))
  9978. (error "No match for custom ID: %s" id))))
  9979. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9980. ;; Look for coderef targets if S is enclosed within parenthesis.
  9981. (let ((coderef (match-string-no-properties 1 normalized))
  9982. (re (substring s-single-re 1 -1)))
  9983. (goto-char (point-min))
  9984. (catch :coderef-match
  9985. (while (re-search-forward re nil t)
  9986. (let ((element (org-element-at-point)))
  9987. (when (and (memq (org-element-type element)
  9988. '(example-block src-block))
  9989. ;; Build proper regexp according to current
  9990. ;; block's label format.
  9991. (let ((label-fmt
  9992. (regexp-quote
  9993. (or (org-element-property :label-fmt element)
  9994. org-coderef-label-format))))
  9995. (save-excursion
  9996. (beginning-of-line)
  9997. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9998. (format label-fmt coderef))))))
  9999. (setq type 'dedicated)
  10000. (goto-char (match-beginning 1))
  10001. (throw :coderef-match nil))))
  10002. (goto-char origin)
  10003. (error "No match for coderef: %s" coderef))))
  10004. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10005. ;; Look for a regular expression.
  10006. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10007. (match-string 1 s)))
  10008. ;; Fuzzy links.
  10009. (t
  10010. (let ((starred (eq (string-to-char normalized) ?*)))
  10011. (cond
  10012. ;; Look for targets, only if not in a headline search.
  10013. ((and (not starred)
  10014. (let ((target (format "<<%s>>" s-multi-re)))
  10015. (catch :target-match
  10016. (goto-char (point-min))
  10017. (while (re-search-forward target nil t)
  10018. (backward-char)
  10019. (let ((context (org-element-context)))
  10020. (when (eq (org-element-type context) 'target)
  10021. (setq type 'dedicated)
  10022. (goto-char (org-element-property :begin context))
  10023. (throw :target-match t))))
  10024. nil))))
  10025. ;; Look for elements named after S, only if not in a headline
  10026. ;; search.
  10027. ((and (not starred)
  10028. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10029. (catch :name-match
  10030. (goto-char (point-min))
  10031. (while (re-search-forward name nil t)
  10032. (let ((element (org-element-at-point)))
  10033. (when (equal (org-split-string
  10034. (org-element-property :name element)
  10035. "[ \t]+")
  10036. words)
  10037. (setq type 'dedicated)
  10038. (beginning-of-line)
  10039. (throw :name-match t))))
  10040. nil))))
  10041. ;; Regular text search. Prefer headlines in Org mode
  10042. ;; buffers.
  10043. ((and (derived-mode-p 'org-mode)
  10044. (let* ((wspace "[ \t]")
  10045. (wspaceopt (concat wspace "*"))
  10046. (cookie (concat "\\(?:"
  10047. wspaceopt
  10048. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  10049. wspaceopt
  10050. "\\)"))
  10051. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10052. (re (concat
  10053. org-outline-regexp-bol
  10054. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  10055. "\\(?:\\[#.\\][ \t]+\\)?"
  10056. "\\(?:" org-comment-string "[ \t]+\\)?"
  10057. sep "?"
  10058. (let ((title (mapconcat #'regexp-quote
  10059. words
  10060. sep)))
  10061. (if starred (substring title 1) title))
  10062. sep "?"
  10063. "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
  10064. "[ \t]*$")))
  10065. (goto-char (point-min))
  10066. (re-search-forward re nil t)))
  10067. (goto-char (match-beginning 0))
  10068. (setq type 'dedicated))
  10069. ;; Offer to create non-existent headline depending on
  10070. ;; `org-link-search-must-match-exact-headline'.
  10071. ((and (derived-mode-p 'org-mode)
  10072. (not org-link-search-inhibit-query)
  10073. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10074. (yes-or-no-p "No match - create this as a new heading? "))
  10075. (goto-char (point-max))
  10076. (unless (bolp) (newline))
  10077. (org-insert-heading nil t t)
  10078. (insert s "\n")
  10079. (beginning-of-line 0))
  10080. ;; Only headlines are looked after. No need to process
  10081. ;; further: throw an error.
  10082. ((and (derived-mode-p 'org-mode)
  10083. (or starred org-link-search-must-match-exact-headline))
  10084. (goto-char origin)
  10085. (error "No match for fuzzy expression: %s" normalized))
  10086. ;; Regular text search.
  10087. ((catch :fuzzy-match
  10088. (goto-char (point-min))
  10089. (while (re-search-forward s-multi-re nil t)
  10090. ;; Skip match if it contains AVOID-POS or it is included
  10091. ;; in a link with a description but outside the
  10092. ;; description.
  10093. (unless (or (and avoid-pos
  10094. (<= (match-beginning 0) avoid-pos)
  10095. (> (match-end 0) avoid-pos))
  10096. (and (save-match-data
  10097. (org-in-regexp org-bracket-link-regexp))
  10098. (match-beginning 3)
  10099. (or (> (match-beginning 3) (point))
  10100. (<= (match-end 3) (point)))
  10101. (org-element-lineage
  10102. (save-match-data (org-element-context))
  10103. '(link) t)))
  10104. (goto-char (match-beginning 0))
  10105. (setq type 'fuzzy)
  10106. (throw :fuzzy-match t)))
  10107. nil))
  10108. ;; All failed. Throw an error.
  10109. (t (goto-char origin)
  10110. (error "No match for fuzzy expression: %s" normalized))))))
  10111. ;; Disclose surroundings of match, if appropriate.
  10112. (when (and (derived-mode-p 'org-mode) (not stealth))
  10113. (org-show-context 'link-search))
  10114. type))
  10115. (defun org-get-buffer-for-internal-link (buffer)
  10116. "Return a buffer to be used for displaying the link target of internal links."
  10117. (cond
  10118. ((not org-display-internal-link-with-indirect-buffer)
  10119. buffer)
  10120. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10121. (message "Buffer is already a clone, not making another one")
  10122. ;; we also do not modify visibility in this case
  10123. buffer)
  10124. (t ; make a new indirect buffer for displaying the link
  10125. (let* ((bn (buffer-name buffer))
  10126. (ibn (concat bn "(Clone)"))
  10127. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10128. (with-current-buffer ib (org-overview))
  10129. ib))))
  10130. (defun org-do-occur (regexp &optional cleanup)
  10131. "Call the Emacs command `occur'.
  10132. If CLEANUP is non-nil, remove the printout of the regular expression
  10133. in the *Occur* buffer. This is useful if the regex is long and not useful
  10134. to read."
  10135. (occur regexp)
  10136. (when cleanup
  10137. (let ((cwin (selected-window)) win beg end)
  10138. (when (setq win (get-buffer-window "*Occur*"))
  10139. (select-window win))
  10140. (goto-char (point-min))
  10141. (when (re-search-forward "match[a-z]+" nil t)
  10142. (setq beg (match-end 0))
  10143. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10144. (setq end (1- (match-beginning 0)))))
  10145. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10146. (goto-char (point-min))
  10147. (select-window cwin))))
  10148. ;;; The mark ring for links jumps
  10149. (defvar org-mark-ring nil
  10150. "Mark ring for positions before jumps in Org-mode.")
  10151. (defvar org-mark-ring-last-goto nil
  10152. "Last position in the mark ring used to go back.")
  10153. ;; Fill and close the ring
  10154. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10155. (dotimes (_ org-mark-ring-length)
  10156. (push (make-marker) org-mark-ring))
  10157. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10158. org-mark-ring)
  10159. (defun org-mark-ring-push (&optional pos buffer)
  10160. "Put the current position or POS into the mark ring and rotate it."
  10161. (interactive)
  10162. (setq pos (or pos (point)))
  10163. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10164. (move-marker (car org-mark-ring)
  10165. (or pos (point))
  10166. (or buffer (current-buffer)))
  10167. (message "%s"
  10168. (substitute-command-keys
  10169. "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
  10170. (defun org-mark-ring-goto (&optional n)
  10171. "Jump to the previous position in the mark ring.
  10172. With prefix arg N, jump back that many stored positions. When
  10173. called several times in succession, walk through the entire ring.
  10174. Org mode commands jumping to a different position in the current file,
  10175. or to another Org file, automatically push the old position onto the ring."
  10176. (interactive "p")
  10177. (let (p m)
  10178. (if (eq last-command this-command)
  10179. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10180. (setq p org-mark-ring))
  10181. (setq org-mark-ring-last-goto p)
  10182. (setq m (car p))
  10183. (pop-to-buffer-same-window (marker-buffer m))
  10184. (goto-char m)
  10185. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10186. (defun org-add-angle-brackets (s)
  10187. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10188. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10189. s)
  10190. ;;; Following specific links
  10191. (defvar org-agenda-buffer-tmp-name)
  10192. (defvar org-agenda-start-on-weekday)
  10193. (defun org-follow-timestamp-link ()
  10194. "Open an agenda view for the time-stamp date/range at point."
  10195. (cond
  10196. ((org-at-date-range-p t)
  10197. (let ((org-agenda-start-on-weekday)
  10198. (t1 (match-string 1))
  10199. (t2 (match-string 2)) tt1 tt2)
  10200. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10201. tt2 (time-to-days (org-time-string-to-time t2)))
  10202. (let ((org-agenda-buffer-tmp-name
  10203. (format "*Org Agenda(a:%s)"
  10204. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10205. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10206. ((org-at-timestamp-p t)
  10207. (let ((org-agenda-buffer-tmp-name
  10208. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10209. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10210. (substring (match-string 1) 0 10)))
  10211. 1)))
  10212. (t (error "This should not happen"))))
  10213. ;;; Following file links
  10214. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10215. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10216. (declare-function mailcap-mime-info
  10217. "mailcap" (string &optional request no-decode))
  10218. (defvar org-wait nil)
  10219. (defun org-open-file (path &optional in-emacs line search)
  10220. "Open the file at PATH.
  10221. First, this expands any special file name abbreviations. Then the
  10222. configuration variable `org-file-apps' is checked if it contains an
  10223. entry for this file type, and if yes, the corresponding command is launched.
  10224. If no application is found, Emacs simply visits the file.
  10225. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10226. With a double \\[universal-argument] \\[universal-argument] \
  10227. prefix arg, Org tries to avoid opening in Emacs
  10228. and to use an external application to visit the file.
  10229. Optional LINE specifies a line to go to, optional SEARCH a string
  10230. to search for. If LINE or SEARCH is given, the file will be
  10231. opened in Emacs, unless an entry from org-file-apps that makes
  10232. use of groups in a regexp matches.
  10233. If you want to change the way frames are used when following a
  10234. link, please customize `org-link-frame-setup'.
  10235. If the file does not exist, an error is thrown."
  10236. (let* ((file (if (equal path "")
  10237. buffer-file-name
  10238. (substitute-in-file-name (expand-file-name path))))
  10239. (file-apps (append org-file-apps (org-default-apps)))
  10240. (apps (cl-remove-if
  10241. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10242. (apps-dlink (cl-remove-if-not
  10243. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10244. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10245. (dirp (unless remp (file-directory-p file)))
  10246. (file (if (and dirp org-open-directory-means-index-dot-org)
  10247. (concat (file-name-as-directory file) "index.org")
  10248. file))
  10249. (a-m-a-p (assq 'auto-mode apps))
  10250. (dfile (downcase file))
  10251. ;; Reconstruct the original link from the PATH, LINE and
  10252. ;; SEARCH args.
  10253. (link (cond (line (concat file "::" (number-to-string line)))
  10254. (search (concat file "::" search))
  10255. (t file)))
  10256. (dlink (downcase link))
  10257. (old-buffer (current-buffer))
  10258. (old-pos (point))
  10259. (old-mode major-mode)
  10260. (ext
  10261. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10262. (match-string 1 dfile)))
  10263. cmd link-match-data)
  10264. (cond
  10265. ((member in-emacs '((16) system))
  10266. (setq cmd (cdr (assq 'system apps))))
  10267. (in-emacs (setq cmd 'emacs))
  10268. (t
  10269. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10270. (and dirp (cdr (assq 'directory apps)))
  10271. ;; First, try matching against apps-dlink if we
  10272. ;; get a match here, store the match data for
  10273. ;; later.
  10274. (let ((match (assoc-default dlink apps-dlink
  10275. 'string-match)))
  10276. (if match
  10277. (progn (setq link-match-data (match-data))
  10278. match)
  10279. (progn (setq in-emacs (or in-emacs line search))
  10280. nil))) ; if we have no match in apps-dlink,
  10281. ; always open the file in emacs if line or search
  10282. ; is given (for backwards compatibility)
  10283. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10284. 'string-match)
  10285. (cdr (assoc ext apps))
  10286. (cdr (assq t apps))))))
  10287. (when (eq cmd 'system)
  10288. (setq cmd (cdr (assq 'system apps))))
  10289. (when (eq cmd 'default)
  10290. (setq cmd (cdr (assoc t apps))))
  10291. (when (eq cmd 'mailcap)
  10292. (require 'mailcap)
  10293. (mailcap-parse-mailcaps)
  10294. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10295. (command (mailcap-mime-info mime-type)))
  10296. (if (stringp command)
  10297. (setq cmd command)
  10298. (setq cmd 'emacs))))
  10299. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10300. (not (file-exists-p file))
  10301. (not org-open-non-existing-files))
  10302. (user-error "No such file: %s" file))
  10303. (cond
  10304. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10305. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10306. (while (string-match "['\"]%s['\"]" cmd)
  10307. (setq cmd (replace-match "%s" t t cmd)))
  10308. (setq cmd (replace-regexp-in-string
  10309. "%s"
  10310. (shell-quote-argument (convert-standard-filename file))
  10311. cmd
  10312. nil t))
  10313. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10314. (save-match-data
  10315. (let ((match-index 1)
  10316. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10317. (set-match-data link-match-data)
  10318. (while (<= match-index number-of-groups)
  10319. (let ((regex (concat "%" (number-to-string match-index)))
  10320. (replace-with (match-string match-index dlink)))
  10321. (while (string-match regex cmd)
  10322. (setq cmd (replace-match replace-with t t cmd))))
  10323. (setq match-index (+ match-index 1)))))
  10324. (save-window-excursion
  10325. (message "Running %s...done" cmd)
  10326. (start-process-shell-command cmd nil cmd)
  10327. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10328. ((or (stringp cmd)
  10329. (eq cmd 'emacs))
  10330. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10331. (widen)
  10332. (cond (line (org-goto-line line)
  10333. (when (derived-mode-p 'org-mode) (org-reveal)))
  10334. (search (org-link-search search))))
  10335. ((functionp cmd)
  10336. (save-match-data
  10337. (set-match-data link-match-data)
  10338. (condition-case nil
  10339. (funcall cmd file link)
  10340. ;; FIXME: Remove this check when most default installations
  10341. ;; of Emacs have at least Org 9.0.
  10342. ((debug wrong-number-of-arguments wrong-type-argument
  10343. invalid-function)
  10344. (user-error "Please see Org News for version 9.0 about \
  10345. `org-file-apps'--Lisp error: %S" cmd)))))
  10346. ((consp cmd)
  10347. ;; FIXME: Remove this check when most default installations of
  10348. ;; Emacs have at least Org 9.0.
  10349. ;; Heads-up instead of silently fall back to
  10350. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10351. ;; with sexp instead of a function for `cmd'.
  10352. (user-error "Please see Org News for version 9.0 about \
  10353. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10354. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10355. (and (derived-mode-p 'org-mode)
  10356. (eq old-mode 'org-mode)
  10357. (or (not (eq old-buffer (current-buffer)))
  10358. (not (eq old-pos (point))))
  10359. (org-mark-ring-push old-pos old-buffer))))
  10360. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10361. "This function returns non-nil if `entry' uses a regular
  10362. expression which should be matched against the whole link by
  10363. org-open-file.
  10364. It assumes that is the case when the entry uses a regular
  10365. expression which has at least one grouping construct and the
  10366. action is either a lisp form or a command string containing
  10367. `%1', i.e. using at least one subexpression match as a
  10368. parameter."
  10369. (let ((selector (car entry))
  10370. (action (cdr entry)))
  10371. (if (stringp selector)
  10372. (and (> (regexp-opt-depth selector) 0)
  10373. (or (and (stringp action)
  10374. (string-match "%[0-9]" action))
  10375. (consp action)))
  10376. nil)))
  10377. (defun org-default-apps ()
  10378. "Return the default applications for this operating system."
  10379. (cond
  10380. ((eq system-type 'darwin)
  10381. org-file-apps-defaults-macosx)
  10382. ((eq system-type 'windows-nt)
  10383. org-file-apps-defaults-windowsnt)
  10384. (t org-file-apps-defaults-gnu)))
  10385. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10386. "Convert extensions to regular expressions in the cars of LIST.
  10387. Also, weed out any non-string entries, because the return value is used
  10388. only for regexp matching.
  10389. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10390. point to the symbol `emacs', indicating that the file should
  10391. be opened in Emacs."
  10392. (append
  10393. (delq nil
  10394. (mapcar (lambda (x)
  10395. (unless (not (stringp (car x)))
  10396. (if (string-match "\\W" (car x))
  10397. x
  10398. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10399. list))
  10400. (when add-auto-mode
  10401. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10402. (defvar ange-ftp-name-format)
  10403. (defun org-file-remote-p (file)
  10404. "Test whether FILE specifies a location on a remote system.
  10405. Return non-nil if the location is indeed remote.
  10406. For example, the filename \"/user@host:/foo\" specifies a location
  10407. on the system \"/user@host:\"."
  10408. (cond ((fboundp 'file-remote-p)
  10409. (file-remote-p file))
  10410. ((fboundp 'tramp-handle-file-remote-p)
  10411. (tramp-handle-file-remote-p file))
  10412. ((and (boundp 'ange-ftp-name-format)
  10413. (string-match (car ange-ftp-name-format) file))
  10414. t)))
  10415. ;;;; Refiling
  10416. (defun org-get-org-file ()
  10417. "Read a filename, with default directory `org-directory'."
  10418. (let ((default (or org-default-notes-file remember-data-file)))
  10419. (read-file-name (format "File name [%s]: " default)
  10420. (file-name-as-directory org-directory)
  10421. default)))
  10422. (defun org-notes-order-reversed-p ()
  10423. "Check if the current file should receive notes in reversed order."
  10424. (cond
  10425. ((not org-reverse-note-order) nil)
  10426. ((eq t org-reverse-note-order) t)
  10427. ((not (listp org-reverse-note-order)) nil)
  10428. (t (catch 'exit
  10429. (dolist (entry org-reverse-note-order)
  10430. (when (string-match (car entry) buffer-file-name)
  10431. (throw 'exit (cdr entry))))))))
  10432. (defvar org-refile-target-table nil
  10433. "The list of refile targets, created by `org-refile'.")
  10434. (defvar org-agenda-new-buffers nil
  10435. "Buffers created to visit agenda files.")
  10436. (defvar org-refile-cache nil
  10437. "Cache for refile targets.")
  10438. (defvar org-refile-markers nil
  10439. "All the markers used for caching refile locations.")
  10440. (defun org-refile-marker (pos)
  10441. "Get a new refile marker, but only if caching is in use."
  10442. (if (not org-refile-use-cache)
  10443. pos
  10444. (let ((m (make-marker)))
  10445. (move-marker m pos)
  10446. (push m org-refile-markers)
  10447. m)))
  10448. (defun org-refile-cache-clear ()
  10449. "Clear the refile cache and disable all the markers."
  10450. (dolist (m org-refile-markers) (move-marker m nil))
  10451. (setq org-refile-markers nil)
  10452. (setq org-refile-cache nil)
  10453. (message "Refile cache has been cleared"))
  10454. (defun org-refile-cache-check-set (set)
  10455. "Check if all the markers in the cache still have live buffers."
  10456. (let (marker)
  10457. (catch 'exit
  10458. (while (and set (setq marker (nth 3 (pop set))))
  10459. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10460. (when (and marker (null (marker-buffer marker)))
  10461. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10462. (sit-for 3)
  10463. (throw 'exit nil)))
  10464. t)))
  10465. (defun org-refile-cache-put (set &rest identifiers)
  10466. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10467. (let* ((key (sha1 (prin1-to-string identifiers)))
  10468. (entry (assoc key org-refile-cache)))
  10469. (if entry
  10470. (setcdr entry set)
  10471. (push (cons key set) org-refile-cache))))
  10472. (defun org-refile-cache-get (&rest identifiers)
  10473. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10474. (cond
  10475. ((not org-refile-cache) nil)
  10476. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10477. (t
  10478. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10479. org-refile-cache))))
  10480. (and set (org-refile-cache-check-set set) set)))))
  10481. (defvar org-outline-path-cache nil
  10482. "Alist between buffer positions and outline paths.
  10483. It value is an alist (POSITION . PATH) where POSITION is the
  10484. buffer position at the beginning of an entry and PATH is a list
  10485. of strings describing the outline path for that entry, in reverse
  10486. order.")
  10487. (defun org-refile-get-targets (&optional default-buffer)
  10488. "Produce a table with refile targets."
  10489. (let ((case-fold-search nil)
  10490. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10491. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10492. targets tgs files desc descre)
  10493. (message "Getting targets...")
  10494. (with-current-buffer (or default-buffer (current-buffer))
  10495. (dolist (entry entries)
  10496. (setq files (car entry) desc (cdr entry))
  10497. (cond
  10498. ((null files) (setq files (list (current-buffer))))
  10499. ((eq files 'org-agenda-files)
  10500. (setq files (org-agenda-files 'unrestricted)))
  10501. ((and (symbolp files) (fboundp files))
  10502. (setq files (funcall files)))
  10503. ((and (symbolp files) (boundp files))
  10504. (setq files (symbol-value files))))
  10505. (when (stringp files) (setq files (list files)))
  10506. (cond
  10507. ((eq (car desc) :tag)
  10508. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10509. ((eq (car desc) :todo)
  10510. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10511. ((eq (car desc) :regexp)
  10512. (setq descre (cdr desc)))
  10513. ((eq (car desc) :level)
  10514. (setq descre (concat "^\\*\\{" (number-to-string
  10515. (if org-odd-levels-only
  10516. (1- (* 2 (cdr desc)))
  10517. (cdr desc)))
  10518. "\\}[ \t]")))
  10519. ((eq (car desc) :maxlevel)
  10520. (setq descre (concat "^\\*\\{1," (number-to-string
  10521. (if org-odd-levels-only
  10522. (1- (* 2 (cdr desc)))
  10523. (cdr desc)))
  10524. "\\}[ \t]")))
  10525. (t (error "Bad refiling target description %s" desc)))
  10526. (dolist (f files)
  10527. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10528. (or
  10529. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10530. (progn
  10531. (when (bufferp f)
  10532. (setq f (buffer-file-name (buffer-base-buffer f))))
  10533. (setq f (and f (expand-file-name f)))
  10534. (when (eq org-refile-use-outline-path 'file)
  10535. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10536. (org-with-wide-buffer
  10537. (goto-char (point-min))
  10538. (setq org-outline-path-cache nil)
  10539. (while (re-search-forward descre nil t)
  10540. (beginning-of-line)
  10541. (looking-at org-complex-heading-regexp)
  10542. (let ((begin (point))
  10543. (heading (match-string-no-properties 4)))
  10544. (unless (or (and
  10545. org-refile-target-verify-function
  10546. (not
  10547. (funcall org-refile-target-verify-function)))
  10548. (not heading))
  10549. (let ((re (format org-complex-heading-regexp-format
  10550. (regexp-quote heading)))
  10551. (target
  10552. (if (not org-refile-use-outline-path) heading
  10553. (mapconcat
  10554. #'org-protect-slash
  10555. (append
  10556. (pcase org-refile-use-outline-path
  10557. (`file (list (file-name-nondirectory
  10558. (buffer-file-name
  10559. (buffer-base-buffer)))))
  10560. (`full-file-path
  10561. (list (buffer-file-name
  10562. (buffer-base-buffer))))
  10563. (_ nil))
  10564. (org-get-outline-path t t))
  10565. "/"))))
  10566. (push (list target f re (org-refile-marker (point)))
  10567. tgs)))
  10568. (when (= (point) begin)
  10569. ;; Verification function has not moved point.
  10570. (end-of-line)))))))
  10571. (when org-refile-use-cache
  10572. (org-refile-cache-put tgs (buffer-file-name) descre))
  10573. (setq targets (append tgs targets))))))
  10574. (message "Getting targets...done")
  10575. (nreverse targets)))
  10576. (defun org-protect-slash (s)
  10577. (replace-regexp-in-string "/" "\\/" s nil t))
  10578. (defun org--get-outline-path-1 (&optional use-cache)
  10579. "Return outline path to current headline.
  10580. Outline path is a list of strings, in reverse order. When
  10581. optional argument USE-CACHE is non-nil, make use of a cache. See
  10582. `org-get-outline-path' for details.
  10583. Assume buffer is widened and point is on a headline."
  10584. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10585. (let ((p (point))
  10586. (heading (progn
  10587. (looking-at org-complex-heading-regexp)
  10588. (if (not (match-end 4)) ""
  10589. ;; Remove statistics cookies.
  10590. (org-trim
  10591. (org-link-display-format
  10592. (replace-regexp-in-string
  10593. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10594. (match-string-no-properties 4))))))))
  10595. (if (org-up-heading-safe)
  10596. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10597. (when use-cache
  10598. (push (cons p path) org-outline-path-cache))
  10599. path)
  10600. ;; This is a new root node. Since we assume we are moving
  10601. ;; forward, we can drop previous cache so as to limit number
  10602. ;; of associations there.
  10603. (let ((path (list heading)))
  10604. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10605. path)))))
  10606. (defun org-get-outline-path (&optional with-self use-cache)
  10607. "Return the outline path to the current entry.
  10608. An outline path is a list of ancestors for current headline, as
  10609. a list of strings. Statistics cookies are removed and links are
  10610. replaced with their description, if any, or their path otherwise.
  10611. When optional argument WITH-SELF is non-nil, the path also
  10612. includes the current headline.
  10613. When optional argument USE-CACHE is non-nil, cache outline paths
  10614. between calls to this function so as to avoid backtracking. This
  10615. argument is useful when planning to find more than one outline
  10616. path in the same document. In that case, there are two
  10617. conditions to satisfy:
  10618. - `org-outline-path-cache' is set to nil before starting the
  10619. process;
  10620. - outline paths are computed by increasing buffer positions."
  10621. (org-with-wide-buffer
  10622. (and (or (and with-self (org-back-to-heading t))
  10623. (org-up-heading-safe))
  10624. (reverse (org--get-outline-path-1 use-cache)))))
  10625. (defun org-format-outline-path (path &optional width prefix separator)
  10626. "Format the outline path PATH for display.
  10627. WIDTH is the maximum number of characters that is available.
  10628. PREFIX is a prefix to be included in the returned string,
  10629. such as the file name.
  10630. SEPARATOR is inserted between the different parts of the path,
  10631. the default is \"/\"."
  10632. (setq width (or width 79))
  10633. (setq path (delq nil path))
  10634. (unless (> width 0)
  10635. (user-error "Argument `width' must be positive"))
  10636. (setq separator (or separator "/"))
  10637. (let* ((org-odd-levels-only nil)
  10638. (fpath (concat
  10639. prefix (and prefix path separator)
  10640. (mapconcat
  10641. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10642. (cl-loop for head in path
  10643. for n from 0
  10644. collect (org-add-props
  10645. head nil 'face
  10646. (nth (% n org-n-level-faces) org-level-faces)))
  10647. separator))))
  10648. (when (> (length fpath) width)
  10649. (if (< width 7)
  10650. ;; It's unlikely that `width' will be this small, but don't
  10651. ;; waste characters by adding ".." if it is.
  10652. (setq fpath (substring fpath 0 width))
  10653. (setf (substring fpath (- width 2)) "..")))
  10654. fpath))
  10655. (defun org-display-outline-path (&optional file current separator just-return-string)
  10656. "Display the current outline path in the echo area.
  10657. If FILE is non-nil, prepend the output with the file name.
  10658. If CURRENT is non-nil, append the current heading to the output.
  10659. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10660. the different parts of the path and defaults to \"/\".
  10661. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10662. (interactive "P")
  10663. (let* (case-fold-search
  10664. (bfn (buffer-file-name (buffer-base-buffer)))
  10665. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10666. res)
  10667. (when current (setq path (append path
  10668. (save-excursion
  10669. (org-back-to-heading t)
  10670. (when (looking-at org-complex-heading-regexp)
  10671. (list (match-string 4)))))))
  10672. (setq res
  10673. (org-format-outline-path
  10674. path
  10675. (1- (frame-width))
  10676. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10677. separator))
  10678. (if just-return-string
  10679. (org-no-properties res)
  10680. (org-unlogged-message "%s" res))))
  10681. (defvar org-refile-history nil
  10682. "History for refiling operations.")
  10683. (defvar org-after-refile-insert-hook nil
  10684. "Hook run after `org-refile' has inserted its stuff at the new location.
  10685. Note that this is still *before* the stuff will be removed from
  10686. the *old* location.")
  10687. (defvar org-capture-last-stored-marker)
  10688. (defvar org-refile-keep nil
  10689. "Non-nil means `org-refile' will copy instead of refile.")
  10690. (defun org-copy ()
  10691. "Like `org-refile', but copy."
  10692. (interactive)
  10693. (let ((org-refile-keep t))
  10694. (funcall 'org-refile nil nil nil "Copy")))
  10695. (defun org-refile (&optional arg default-buffer rfloc msg)
  10696. "Move the entry or entries at point to another heading.
  10697. The list of target headings is compiled using the information in
  10698. `org-refile-targets', which see.
  10699. At the target location, the entry is filed as a subitem of the
  10700. target heading. Depending on `org-reverse-note-order', the new
  10701. subitem will either be the first or the last subitem.
  10702. If there is an active region, all entries in that region will be
  10703. refiled. However, the region must fulfill the requirement that
  10704. the first heading sets the top-level of the moved text.
  10705. With prefix arg ARG, the command will only visit the target
  10706. location and not actually move anything.
  10707. With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
  10708. refiling operation has put the subtree.
  10709. With a numeric prefix argument of `2', refile to the running clock.
  10710. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10711. being set to t and copy to the target location, don't move it.
  10712. Beware that keeping refiled entries may result in duplicated ID
  10713. properties.
  10714. RFLOC can be a refile location obtained in a different way.
  10715. MSG is a string to replace \"Refile\" in the default prompt with
  10716. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10717. See also `org-refile-use-outline-path'.
  10718. If you are using target caching (see `org-refile-use-cache'), you
  10719. have to clear the target cache in order to find new targets.
  10720. This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
  10721. prefix argument (`C-u C-u C-u C-c C-w')."
  10722. (interactive "P")
  10723. (if (member arg '(0 (64)))
  10724. (org-refile-cache-clear)
  10725. (let* ((actionmsg (cond (msg msg)
  10726. ((equal arg 3) "Refile (and keep)")
  10727. (t "Refile")))
  10728. (regionp (org-region-active-p))
  10729. (region-start (and regionp (region-beginning)))
  10730. (region-end (and regionp (region-end)))
  10731. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10732. pos it nbuf file level reversed)
  10733. (setq last-command nil)
  10734. (when regionp
  10735. (goto-char region-start)
  10736. (or (bolp) (goto-char (point-at-bol)))
  10737. (setq region-start (point))
  10738. (unless (or (org-kill-is-subtree-p
  10739. (buffer-substring region-start region-end))
  10740. (prog1 org-refile-active-region-within-subtree
  10741. (let ((s (point-at-eol)))
  10742. (org-toggle-heading)
  10743. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10744. (user-error "The region is not a (sequence of) subtree(s)")))
  10745. (if (equal arg '(16))
  10746. (org-refile-goto-last-stored)
  10747. (when (or
  10748. (and (equal arg 2)
  10749. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10750. (prog1
  10751. (setq it (list (or org-clock-heading "running clock")
  10752. (buffer-file-name
  10753. (marker-buffer org-clock-hd-marker))
  10754. ""
  10755. (marker-position org-clock-hd-marker)))
  10756. (setq arg nil)))
  10757. (setq it
  10758. (or rfloc
  10759. (let (heading-text)
  10760. (save-excursion
  10761. (unless (and arg (listp arg))
  10762. (org-back-to-heading t)
  10763. (setq heading-text
  10764. (replace-regexp-in-string
  10765. org-bracket-link-regexp
  10766. "\\3"
  10767. (or (nth 4 (org-heading-components))
  10768. ""))))
  10769. (org-refile-get-location
  10770. (cond ((and arg (listp arg)) "Goto")
  10771. (regionp (concat actionmsg " region to"))
  10772. (t (concat actionmsg " subtree \""
  10773. heading-text "\" to")))
  10774. default-buffer
  10775. (and (not (equal '(4) arg))
  10776. org-refile-allow-creating-parent-nodes)))))))
  10777. (setq file (nth 1 it)
  10778. pos (nth 3 it))
  10779. (when (and (not arg)
  10780. pos
  10781. (equal (buffer-file-name) file)
  10782. (if regionp
  10783. (and (>= pos region-start)
  10784. (<= pos region-end))
  10785. (and (>= pos (point))
  10786. (< pos (save-excursion
  10787. (org-end-of-subtree t t))))))
  10788. (error "Cannot refile to position inside the tree or region"))
  10789. (setq nbuf (or (find-buffer-visiting file)
  10790. (find-file-noselect file)))
  10791. (if (and arg (not (equal arg 3)))
  10792. (progn
  10793. (pop-to-buffer-same-window nbuf)
  10794. (goto-char pos)
  10795. (org-show-context 'org-goto))
  10796. (if regionp
  10797. (progn
  10798. (org-kill-new (buffer-substring region-start region-end))
  10799. (org-save-markers-in-region region-start region-end))
  10800. (org-copy-subtree 1 nil t))
  10801. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10802. (find-file-noselect file)))
  10803. (setq reversed (org-notes-order-reversed-p))
  10804. (org-with-wide-buffer
  10805. (if pos
  10806. (progn
  10807. (goto-char pos)
  10808. (looking-at org-outline-regexp)
  10809. (setq level (org-get-valid-level (funcall outline-level) 1))
  10810. (goto-char
  10811. (if reversed
  10812. (or (outline-next-heading) (point-max))
  10813. (or (save-excursion (org-get-next-sibling))
  10814. (org-end-of-subtree t t)
  10815. (point-max)))))
  10816. (setq level 1)
  10817. (if (not reversed)
  10818. (goto-char (point-max))
  10819. (goto-char (point-min))
  10820. (or (outline-next-heading) (goto-char (point-max)))))
  10821. (unless (bolp) (newline))
  10822. (org-paste-subtree level nil nil t)
  10823. (when org-log-refile
  10824. (org-add-log-setup 'refile nil nil org-log-refile)
  10825. (unless (eq org-log-refile 'note)
  10826. (save-excursion (org-add-log-note))))
  10827. (and org-auto-align-tags
  10828. (let ((org-loop-over-headlines-in-active-region nil))
  10829. (org-set-tags nil t)))
  10830. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10831. :last-refile)))
  10832. (when bookmark-name
  10833. (with-demoted-errors
  10834. (bookmark-set bookmark-name))))
  10835. ;; If we are refiling for capture, make sure that the
  10836. ;; last-capture pointers point here
  10837. (when (bound-and-true-p org-capture-is-refiling)
  10838. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10839. :last-capture-marker)))
  10840. (when bookmark-name
  10841. (with-demoted-errors
  10842. (bookmark-set bookmark-name))))
  10843. (move-marker org-capture-last-stored-marker (point)))
  10844. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10845. (run-hooks 'org-after-refile-insert-hook)))
  10846. (unless org-refile-keep
  10847. (if regionp
  10848. (delete-region (point) (+ (point) (- region-end region-start)))
  10849. (delete-region
  10850. (and (org-back-to-heading t) (point))
  10851. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10852. (when (featurep 'org-inlinetask)
  10853. (org-inlinetask-remove-END-maybe))
  10854. (setq org-markers-to-move nil)
  10855. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10856. (defun org-refile-goto-last-stored ()
  10857. "Go to the location where the last refile was stored."
  10858. (interactive)
  10859. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10860. (message "This is the location of the last refile"))
  10861. (defun org-refile--get-location (refloc tbl)
  10862. "When user refile to REFLOC, find the associated target in TBL.
  10863. Also check `org-refile-target-table'."
  10864. (car (delq
  10865. nil
  10866. (mapcar
  10867. (lambda (r) (or (assoc r tbl)
  10868. (assoc r org-refile-target-table)))
  10869. (list (replace-regexp-in-string "/$" "" refloc)
  10870. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10871. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10872. "Prompt the user for a refile location, using PROMPT.
  10873. PROMPT should not be suffixed with a colon and a space, because
  10874. this function appends the default value from
  10875. `org-refile-history' automatically, if that is not empty."
  10876. (let ((org-refile-targets org-refile-targets)
  10877. (org-refile-use-outline-path org-refile-use-outline-path))
  10878. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10879. (unless org-refile-target-table
  10880. (user-error "No refile targets"))
  10881. (let* ((cbuf (current-buffer))
  10882. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10883. (cfunc (if (and org-refile-use-outline-path
  10884. org-outline-path-complete-in-steps)
  10885. #'org-olpath-completing-read
  10886. #'completing-read))
  10887. (extra (if org-refile-use-outline-path "/" ""))
  10888. (cbnex (concat (buffer-name) extra))
  10889. (filename (and cfn (expand-file-name cfn)))
  10890. (tbl (mapcar
  10891. (lambda (x)
  10892. (if (and (not (member org-refile-use-outline-path
  10893. '(file full-file-path)))
  10894. (not (equal filename (nth 1 x))))
  10895. (cons (concat (car x) extra " ("
  10896. (file-name-nondirectory (nth 1 x)) ")")
  10897. (cdr x))
  10898. (cons (concat (car x) extra) (cdr x))))
  10899. org-refile-target-table))
  10900. (completion-ignore-case t)
  10901. cdef
  10902. (prompt (concat prompt
  10903. (or (and (car org-refile-history)
  10904. (concat " (default " (car org-refile-history) ")"))
  10905. (and (assoc cbnex tbl) (setq cdef cbnex)
  10906. (concat " (default " cbnex ")"))) ": "))
  10907. pa answ parent-target child parent old-hist)
  10908. (setq old-hist org-refile-history)
  10909. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10910. nil 'org-refile-history (or cdef (car org-refile-history))))
  10911. (if (setq pa (org-refile--get-location answ tbl))
  10912. (progn
  10913. (org-refile-check-position pa)
  10914. (when (or (not org-refile-history)
  10915. (not (eq old-hist org-refile-history))
  10916. (not (equal (car pa) (car org-refile-history))))
  10917. (setq org-refile-history
  10918. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10919. org-refile-history
  10920. (cdr org-refile-history))))
  10921. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10922. (pop org-refile-history)))
  10923. pa)
  10924. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10925. (progn
  10926. (setq parent (match-string 1 answ)
  10927. child (match-string 2 answ))
  10928. (setq parent-target (org-refile--get-location parent tbl))
  10929. (when (and parent-target
  10930. (or (eq new-nodes t)
  10931. (and (eq new-nodes 'confirm)
  10932. (y-or-n-p (format "Create new node \"%s\"? "
  10933. child)))))
  10934. (org-refile-new-child parent-target child)))
  10935. (user-error "Invalid target location")))))
  10936. (declare-function org-string-nw-p "org-macs" (s))
  10937. (defun org-refile-check-position (refile-pointer)
  10938. "Check if the refile pointer matches the headline to which it points."
  10939. (let* ((file (nth 1 refile-pointer))
  10940. (re (nth 2 refile-pointer))
  10941. (pos (nth 3 refile-pointer))
  10942. buffer)
  10943. (if (and (not (markerp pos)) (not file))
  10944. (user-error "Please indicate a target file in the refile path")
  10945. (when (org-string-nw-p re)
  10946. (setq buffer (if (markerp pos)
  10947. (marker-buffer pos)
  10948. (or (find-buffer-visiting file)
  10949. (find-file-noselect file))))
  10950. (with-current-buffer buffer
  10951. (org-with-wide-buffer
  10952. (goto-char pos)
  10953. (beginning-of-line 1)
  10954. (unless (looking-at-p re)
  10955. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10956. (defun org-refile-new-child (parent-target child)
  10957. "Use refile target PARENT-TARGET to add new CHILD below it."
  10958. (unless parent-target
  10959. (error "Cannot find parent for new node"))
  10960. (let ((file (nth 1 parent-target))
  10961. (pos (nth 3 parent-target))
  10962. level)
  10963. (with-current-buffer (or (find-buffer-visiting file)
  10964. (find-file-noselect file))
  10965. (org-with-wide-buffer
  10966. (if pos
  10967. (goto-char pos)
  10968. (goto-char (point-max))
  10969. (unless (bolp) (newline)))
  10970. (when (looking-at org-outline-regexp)
  10971. (setq level (funcall outline-level))
  10972. (org-end-of-subtree t t))
  10973. (org-back-over-empty-lines)
  10974. (insert "\n" (make-string
  10975. (if pos (org-get-valid-level level 1) 1) ?*)
  10976. " " child "\n")
  10977. (beginning-of-line 0)
  10978. (list (concat (car parent-target) "/" child) file "" (point))))))
  10979. (defun org-olpath-completing-read (prompt collection &rest args)
  10980. "Read an outline path like a file name."
  10981. (let ((thetable collection))
  10982. (apply #'completing-read
  10983. prompt
  10984. (lambda (string predicate &optional flag)
  10985. (cond
  10986. ((eq flag nil) (try-completion string thetable))
  10987. ((eq flag t)
  10988. (let ((l (length string)))
  10989. (mapcar (lambda (x)
  10990. (let ((r (substring x l))
  10991. (f (if (string-match " ([^)]*)$" x)
  10992. (match-string 0 x)
  10993. "")))
  10994. (if (string-match "/" r)
  10995. (concat string (substring r 0 (match-end 0)) f)
  10996. x)))
  10997. (all-completions string thetable predicate))))
  10998. ;; Exact match?
  10999. ((eq flag 'lambda) (assoc string thetable))))
  11000. args)))
  11001. ;;;; Dynamic blocks
  11002. (defun org-find-dblock (name)
  11003. "Find the first dynamic block with name NAME in the buffer.
  11004. If not found, stay at current position and return nil."
  11005. (let ((case-fold-search t) pos)
  11006. (save-excursion
  11007. (goto-char (point-min))
  11008. (setq pos (and (re-search-forward
  11009. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11010. (match-beginning 0))))
  11011. (when pos (goto-char pos))
  11012. pos))
  11013. (defun org-create-dblock (plist)
  11014. "Create a dynamic block section, with parameters taken from PLIST.
  11015. PLIST must contain a :name entry which is used as the name of the block."
  11016. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11017. (end-of-line 1)
  11018. (newline))
  11019. (let ((col (current-column))
  11020. (name (plist-get plist :name)))
  11021. (insert "#+BEGIN: " name)
  11022. (while plist
  11023. (if (eq (car plist) :name)
  11024. (setq plist (cddr plist))
  11025. (insert " " (prin1-to-string (pop plist)))))
  11026. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11027. (beginning-of-line -2)))
  11028. (defun org-prepare-dblock ()
  11029. "Prepare dynamic block for refresh.
  11030. This empties the block, puts the cursor at the insert position and returns
  11031. the property list including an extra property :name with the block name."
  11032. (unless (looking-at org-dblock-start-re)
  11033. (user-error "Not at a dynamic block"))
  11034. (let* ((begdel (1+ (match-end 0)))
  11035. (name (org-no-properties (match-string 1)))
  11036. (params (append (list :name name)
  11037. (read (concat "(" (match-string 3) ")")))))
  11038. (save-excursion
  11039. (beginning-of-line 1)
  11040. (skip-chars-forward " \t")
  11041. (setq params (plist-put params :indentation-column (current-column))))
  11042. (unless (re-search-forward org-dblock-end-re nil t)
  11043. (error "Dynamic block not terminated"))
  11044. (setq params
  11045. (append params
  11046. (list :content (buffer-substring
  11047. begdel (match-beginning 0)))))
  11048. (delete-region begdel (match-beginning 0))
  11049. (goto-char begdel)
  11050. (open-line 1)
  11051. params))
  11052. (defun org-map-dblocks (&optional command)
  11053. "Apply COMMAND to all dynamic blocks in the current buffer.
  11054. If COMMAND is not given, use `org-update-dblock'."
  11055. (let ((cmd (or command 'org-update-dblock)))
  11056. (save-excursion
  11057. (goto-char (point-min))
  11058. (while (re-search-forward org-dblock-start-re nil t)
  11059. (goto-char (match-beginning 0))
  11060. (save-excursion
  11061. (condition-case nil
  11062. (funcall cmd)
  11063. (error (message "Error during update of dynamic block"))))
  11064. (unless (re-search-forward org-dblock-end-re nil t)
  11065. (error "Dynamic block not terminated"))))))
  11066. (defun org-dblock-update (&optional arg)
  11067. "User command for updating dynamic blocks.
  11068. Update the dynamic block at point. With prefix ARG, update all dynamic
  11069. blocks in the buffer."
  11070. (interactive "P")
  11071. (if arg
  11072. (org-update-all-dblocks)
  11073. (or (looking-at org-dblock-start-re)
  11074. (org-beginning-of-dblock))
  11075. (org-update-dblock)))
  11076. (defun org-update-dblock ()
  11077. "Update the dynamic block at point.
  11078. This means to empty the block, parse for parameters and then call
  11079. the correct writing function."
  11080. (interactive)
  11081. (save-excursion
  11082. (let* ((win (selected-window))
  11083. (pos (point))
  11084. (line (org-current-line))
  11085. (params (org-prepare-dblock))
  11086. (name (plist-get params :name))
  11087. (indent (plist-get params :indentation-column))
  11088. (cmd (intern (concat "org-dblock-write:" name))))
  11089. (message "Updating dynamic block `%s' at line %d..." name line)
  11090. (funcall cmd params)
  11091. (message "Updating dynamic block `%s' at line %d...done" name line)
  11092. (goto-char pos)
  11093. (when (and indent (> indent 0))
  11094. (setq indent (make-string indent ?\ ))
  11095. (save-excursion
  11096. (select-window win)
  11097. (org-beginning-of-dblock)
  11098. (forward-line 1)
  11099. (while (not (looking-at org-dblock-end-re))
  11100. (insert indent)
  11101. (beginning-of-line 2))
  11102. (when (looking-at org-dblock-end-re)
  11103. (and (looking-at "[ \t]+")
  11104. (replace-match ""))
  11105. (insert indent)))))))
  11106. (defun org-beginning-of-dblock ()
  11107. "Find the beginning of the dynamic block at point.
  11108. Error if there is no such block at point."
  11109. (let ((pos (point))
  11110. beg)
  11111. (end-of-line 1)
  11112. (if (and (re-search-backward org-dblock-start-re nil t)
  11113. (setq beg (match-beginning 0))
  11114. (re-search-forward org-dblock-end-re nil t)
  11115. (> (match-end 0) pos))
  11116. (goto-char beg)
  11117. (goto-char pos)
  11118. (error "Not in a dynamic block"))))
  11119. (defun org-update-all-dblocks ()
  11120. "Update all dynamic blocks in the buffer.
  11121. This function can be used in a hook."
  11122. (interactive)
  11123. (when (derived-mode-p 'org-mode)
  11124. (org-map-dblocks 'org-update-dblock)))
  11125. ;;;; Completion
  11126. (declare-function org-export-backend-options "ox" (cl-x) t)
  11127. (defun org-get-export-keywords ()
  11128. "Return a list of all currently understood export keywords.
  11129. Export keywords include options, block names, attributes and
  11130. keywords relative to each registered export back-end."
  11131. (let (keywords)
  11132. (dolist (backend
  11133. (bound-and-true-p org-export-registered-backends)
  11134. (delq nil keywords))
  11135. ;; Back-end name (for keywords, like #+LATEX:)
  11136. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11137. (dolist (option-entry (org-export-backend-options backend))
  11138. ;; Back-end options.
  11139. (push (nth 1 option-entry) keywords)))))
  11140. (defconst org-options-keywords
  11141. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11142. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11143. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11144. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11145. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11146. (defcustom org-structure-template-alist
  11147. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11148. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11149. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11150. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11151. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11152. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11153. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11154. ("L" "#+LaTeX: ")
  11155. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11156. ("H" "#+HTML: ")
  11157. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11158. ("A" "#+ASCII: ")
  11159. ("i" "#+INDEX: ?")
  11160. ("I" "#+INCLUDE: %file ?"))
  11161. "Structure completion elements.
  11162. This is a list of abbreviation keys and values. The value gets inserted
  11163. if you type `<' followed by the key and then press the completion key,
  11164. usually `TAB'. %file will be replaced by a file name after prompting
  11165. for the file using completion. The cursor will be placed at the position
  11166. of the `?' in the template.
  11167. There are two templates for each key, the first uses the original Org syntax,
  11168. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11169. the default when the /org-mtags.el/ module has been loaded. See also the
  11170. variable `org-mtags-prefer-muse-templates'."
  11171. :group 'org-completion
  11172. :type '(repeat
  11173. (list
  11174. (string :tag "Key")
  11175. (string :tag "Template")))
  11176. :version "25.1"
  11177. :package-version '(Org . "8.3"))
  11178. (defun org-try-structure-completion ()
  11179. "Try to complete a structure template before point.
  11180. This looks for strings like \"<e\" on an otherwise empty line and
  11181. expands them."
  11182. (let ((l (buffer-substring (point-at-bol) (point)))
  11183. a)
  11184. (when (and (looking-at "[ \t]*$")
  11185. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11186. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11187. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11188. (match-beginning 1)) a)
  11189. t)))
  11190. (defun org-complete-expand-structure-template (start cell)
  11191. "Expand a structure template."
  11192. (let ((rpl (nth 1 cell))
  11193. (ind ""))
  11194. (delete-region start (point))
  11195. (when (string-match "\\`[ \t]*#\\+" rpl)
  11196. (cond
  11197. ((bolp))
  11198. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11199. (setq ind (buffer-substring (point-at-bol) (point))))
  11200. (t (newline))))
  11201. (setq start (point))
  11202. (when (string-match "%file" rpl)
  11203. (setq rpl (replace-match
  11204. (concat
  11205. "\""
  11206. (save-match-data
  11207. (abbreviate-file-name (read-file-name "Include file: ")))
  11208. "\"")
  11209. t t rpl)))
  11210. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11211. (concat "\n" ind)))
  11212. (insert rpl)
  11213. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11214. ;;;; TODO, DEADLINE, Comments
  11215. (defun org-toggle-comment ()
  11216. "Change the COMMENT state of an entry."
  11217. (interactive)
  11218. (save-excursion
  11219. (org-back-to-heading)
  11220. (looking-at org-complex-heading-regexp)
  11221. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11222. (skip-chars-forward " \t")
  11223. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11224. (if (org-in-commented-heading-p t)
  11225. (delete-region (point)
  11226. (progn (search-forward " " (line-end-position) 'move)
  11227. (skip-chars-forward " \t")
  11228. (point)))
  11229. (insert org-comment-string)
  11230. (unless (eolp) (insert " ")))))
  11231. (defvar org-last-todo-state-is-todo nil
  11232. "This is non-nil when the last TODO state change led to a TODO state.
  11233. If the last change removed the TODO tag or switched to DONE, then
  11234. this is nil.")
  11235. (defvar org-setting-tags nil) ; dynamically skipped
  11236. (defvar org-todo-setup-filter-hook nil
  11237. "Hook for functions that pre-filter todo specs.
  11238. Each function takes a todo spec and returns either nil or the spec
  11239. transformed into canonical form." )
  11240. (defvar org-todo-get-default-hook nil
  11241. "Hook for functions that get a default item for todo.
  11242. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11243. nil or a string to be used for the todo mark." )
  11244. (defvar org-agenda-headline-snapshot-before-repeat)
  11245. (defun org-current-effective-time ()
  11246. "Return current time adjusted for `org-extend-today-until' variable."
  11247. (let* ((ct (org-current-time))
  11248. (dct (decode-time ct))
  11249. (ct1
  11250. (cond
  11251. (org-use-last-clock-out-time-as-effective-time
  11252. (or (org-clock-get-last-clock-out-time) ct))
  11253. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11254. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11255. (t ct))))
  11256. ct1))
  11257. (defun org-todo-yesterday (&optional arg)
  11258. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11259. (interactive "P")
  11260. (if (eq major-mode 'org-agenda-mode)
  11261. (apply 'org-agenda-todo-yesterday arg)
  11262. (let* ((org-use-effective-time t)
  11263. (hour (nth 2 (decode-time (org-current-time))))
  11264. (org-extend-today-until (1+ hour)))
  11265. (org-todo arg))))
  11266. (defvar org-block-entry-blocking ""
  11267. "First entry preventing the TODO state change.")
  11268. (defun org-cancel-repeater ()
  11269. "Cancel a repeater by setting its numeric value to zero."
  11270. (interactive)
  11271. (save-excursion
  11272. (org-back-to-heading t)
  11273. (let ((bound1 (point))
  11274. (bound0 (save-excursion (outline-next-heading) (point))))
  11275. (when (and (re-search-forward
  11276. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11277. org-deadline-time-regexp "\\)\\|\\("
  11278. org-ts-regexp "\\)")
  11279. bound0 t)
  11280. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11281. bound1 t))
  11282. (replace-match "0" t nil nil 1)))))
  11283. (defvar org-state) ;; dynamically scoped into this function
  11284. (defun org-todo (&optional arg)
  11285. "Change the TODO state of an item.
  11286. The state of an item is given by a keyword at the start of the heading,
  11287. like
  11288. *** TODO Write paper
  11289. *** DONE Call mom
  11290. The different keywords are specified in the variable `org-todo-keywords'.
  11291. By default the available states are \"TODO\" and \"DONE\".
  11292. So for this example: when the item starts with TODO, it is changed to DONE.
  11293. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11294. DONE are present, add TODO at the beginning of the heading.
  11295. With \\[universal-argument] prefix arg, use completion to determine the new \
  11296. state.
  11297. With numeric prefix arg, switch to that state.
  11298. With a double \\[universal-argument] prefix, switch to the next set of TODO \
  11299. keywords (nextset).
  11300. With a triple \\[universal-argument] prefix, circumvent any state blocking.
  11301. With a numeric prefix arg of 0, inhibit note taking for the change.
  11302. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11303. When called through ELisp, arg is also interpreted in the following way:
  11304. `none' -> empty state
  11305. \"\"(empty string) -> switch to empty state
  11306. `done' -> switch to DONE
  11307. `nextset' -> switch to the next set of keywords
  11308. `previousset' -> switch to the previous set of keywords
  11309. \"WAITING\" -> switch to the specified keyword, but only if it
  11310. really is a member of `org-todo-keywords'."
  11311. (interactive "P")
  11312. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11313. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11314. 'region-start-level 'region))
  11315. org-loop-over-headlines-in-active-region)
  11316. (org-map-entries
  11317. `(org-todo ,arg)
  11318. org-loop-over-headlines-in-active-region
  11319. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11320. (when (equal arg '(16)) (setq arg 'nextset))
  11321. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11322. (let ((org-blocker-hook org-blocker-hook)
  11323. commentp
  11324. case-fold-search)
  11325. (when (equal arg '(64))
  11326. (setq arg nil org-blocker-hook nil))
  11327. (when (and org-blocker-hook
  11328. (or org-inhibit-blocking
  11329. (org-entry-get nil "NOBLOCKING")))
  11330. (setq org-blocker-hook nil))
  11331. (save-excursion
  11332. (catch 'exit
  11333. (org-back-to-heading t)
  11334. (when (org-in-commented-heading-p t)
  11335. (org-toggle-comment)
  11336. (setq commentp t))
  11337. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11338. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11339. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11340. (let* ((match-data (match-data))
  11341. (startpos (point-at-bol))
  11342. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11343. (org-log-done org-log-done)
  11344. (org-log-repeat org-log-repeat)
  11345. (org-todo-log-states org-todo-log-states)
  11346. (org-inhibit-logging
  11347. (if (equal arg 0)
  11348. (progn (setq arg nil) 'note) org-inhibit-logging))
  11349. (this (match-string 1))
  11350. (hl-pos (match-beginning 0))
  11351. (head (org-get-todo-sequence-head this))
  11352. (ass (assoc head org-todo-kwd-alist))
  11353. (interpret (nth 1 ass))
  11354. (done-word (nth 3 ass))
  11355. (final-done-word (nth 4 ass))
  11356. (org-last-state (or this ""))
  11357. (completion-ignore-case t)
  11358. (member (member this org-todo-keywords-1))
  11359. (tail (cdr member))
  11360. (org-state (cond
  11361. ((and org-todo-key-trigger
  11362. (or (and (equal arg '(4))
  11363. (eq org-use-fast-todo-selection 'prefix))
  11364. (and (not arg) org-use-fast-todo-selection
  11365. (not (eq org-use-fast-todo-selection
  11366. 'prefix)))))
  11367. ;; Use fast selection
  11368. (org-fast-todo-selection))
  11369. ((and (equal arg '(4))
  11370. (or (not org-use-fast-todo-selection)
  11371. (not org-todo-key-trigger)))
  11372. ;; Read a state with completion
  11373. (completing-read
  11374. "State: " (mapcar #'list org-todo-keywords-1)
  11375. nil t))
  11376. ((eq arg 'right)
  11377. (if this
  11378. (if tail (car tail) nil)
  11379. (car org-todo-keywords-1)))
  11380. ((eq arg 'left)
  11381. (unless (equal member org-todo-keywords-1)
  11382. (if this
  11383. (nth (- (length org-todo-keywords-1)
  11384. (length tail) 2)
  11385. org-todo-keywords-1)
  11386. (org-last org-todo-keywords-1))))
  11387. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11388. (setq arg nil))) ; hack to fall back to cycling
  11389. (arg
  11390. ;; user or caller requests a specific state
  11391. (cond
  11392. ((equal arg "") nil)
  11393. ((eq arg 'none) nil)
  11394. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11395. ((eq arg 'nextset)
  11396. (or (car (cdr (member head org-todo-heads)))
  11397. (car org-todo-heads)))
  11398. ((eq arg 'previousset)
  11399. (let ((org-todo-heads (reverse org-todo-heads)))
  11400. (or (car (cdr (member head org-todo-heads)))
  11401. (car org-todo-heads))))
  11402. ((car (member arg org-todo-keywords-1)))
  11403. ((stringp arg)
  11404. (user-error "State `%s' not valid in this file" arg))
  11405. ((nth (1- (prefix-numeric-value arg))
  11406. org-todo-keywords-1))))
  11407. ((null member) (or head (car org-todo-keywords-1)))
  11408. ((equal this final-done-word) nil) ;; -> make empty
  11409. ((null tail) nil) ;; -> first entry
  11410. ((memq interpret '(type priority))
  11411. (if (eq this-command last-command)
  11412. (car tail)
  11413. (if (> (length tail) 0)
  11414. (or done-word (car org-done-keywords))
  11415. nil)))
  11416. (t
  11417. (car tail))))
  11418. (org-state (or
  11419. (run-hook-with-args-until-success
  11420. 'org-todo-get-default-hook org-state org-last-state)
  11421. org-state))
  11422. (next (if org-state (concat " " org-state " ") " "))
  11423. (change-plist (list :type 'todo-state-change :from this :to org-state
  11424. :position startpos))
  11425. dolog now-done-p)
  11426. (when org-blocker-hook
  11427. (setq org-last-todo-state-is-todo
  11428. (not (member this org-done-keywords)))
  11429. (unless (save-excursion
  11430. (save-match-data
  11431. (org-with-wide-buffer
  11432. (run-hook-with-args-until-failure
  11433. 'org-blocker-hook change-plist))))
  11434. (if (called-interactively-p 'interactive)
  11435. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11436. this org-state org-block-entry-blocking)
  11437. ;; fail silently
  11438. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11439. this org-state org-block-entry-blocking)
  11440. (throw 'exit nil))))
  11441. (store-match-data match-data)
  11442. (replace-match next t t)
  11443. (cond ((equal this org-state)
  11444. (message "TODO state was already %s" (org-trim next)))
  11445. ((pos-visible-in-window-p hl-pos)
  11446. (message "TODO state changed to %s" (org-trim next))))
  11447. (unless head
  11448. (setq head (org-get-todo-sequence-head org-state)
  11449. ass (assoc head org-todo-kwd-alist)
  11450. interpret (nth 1 ass)
  11451. done-word (nth 3 ass)
  11452. final-done-word (nth 4 ass)))
  11453. (when (memq arg '(nextset previousset))
  11454. (message "Keyword-Set %d/%d: %s"
  11455. (- (length org-todo-sets) -1
  11456. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11457. (length org-todo-sets)
  11458. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11459. (setq org-last-todo-state-is-todo
  11460. (not (member org-state org-done-keywords)))
  11461. (setq now-done-p (and (member org-state org-done-keywords)
  11462. (not (member this org-done-keywords))))
  11463. (and logging (org-local-logging logging))
  11464. (when (and (or org-todo-log-states org-log-done)
  11465. (not (eq org-inhibit-logging t))
  11466. (not (memq arg '(nextset previousset))))
  11467. ;; we need to look at recording a time and note
  11468. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11469. (nth 2 (assoc this org-todo-log-states))))
  11470. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11471. (setq dolog 'time))
  11472. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11473. (and org-state
  11474. (member org-state org-not-done-keywords)
  11475. (not (member this org-not-done-keywords))))
  11476. ;; This is now a todo state and was not one before
  11477. ;; If there was a CLOSED time stamp, get rid of it.
  11478. (org-add-planning-info nil nil 'closed))
  11479. (when (and now-done-p org-log-done)
  11480. ;; It is now done, and it was not done before
  11481. (org-add-planning-info 'closed (org-current-effective-time))
  11482. (when (and (not dolog) (eq 'note org-log-done))
  11483. (org-add-log-setup 'done org-state this 'note)))
  11484. (when (and org-state dolog)
  11485. ;; This is a non-nil state, and we need to log it
  11486. (org-add-log-setup 'state org-state this dolog)))
  11487. ;; Fixup tag positioning
  11488. (org-todo-trigger-tag-changes org-state)
  11489. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11490. (when org-provide-todo-statistics
  11491. (org-update-parent-todo-statistics))
  11492. (run-hooks 'org-after-todo-state-change-hook)
  11493. (when (and arg (not (member org-state org-done-keywords)))
  11494. (setq head (org-get-todo-sequence-head org-state)))
  11495. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11496. ;; Do we need to trigger a repeat?
  11497. (when now-done-p
  11498. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11499. ;; This is for the agenda, take a snapshot of the headline.
  11500. (save-match-data
  11501. (setq org-agenda-headline-snapshot-before-repeat
  11502. (org-get-heading))))
  11503. (org-auto-repeat-maybe org-state))
  11504. ;; Fixup cursor location if close to the keyword
  11505. (when (and (outline-on-heading-p)
  11506. (not (bolp))
  11507. (save-excursion (beginning-of-line 1)
  11508. (looking-at org-todo-line-regexp))
  11509. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11510. (goto-char (or (match-end 2) (match-end 1)))
  11511. (and (looking-at " ") (just-one-space)))
  11512. (when org-trigger-hook
  11513. (save-excursion
  11514. (run-hook-with-args 'org-trigger-hook change-plist)))
  11515. (when commentp (org-toggle-comment))))))))
  11516. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11517. "Block turning an entry into a TODO, using the hierarchy.
  11518. This checks whether the current task should be blocked from state
  11519. changes. Such blocking occurs when:
  11520. 1. The task has children which are not all in a completed state.
  11521. 2. A task has a parent with the property :ORDERED:, and there
  11522. are siblings prior to the current task with incomplete
  11523. status.
  11524. 3. The parent of the task is blocked because it has siblings that should
  11525. be done first, or is child of a block grandparent TODO entry."
  11526. (if (not org-enforce-todo-dependencies)
  11527. t ; if locally turned off don't block
  11528. (catch 'dont-block
  11529. ;; If this is not a todo state change, or if this entry is already DONE,
  11530. ;; do not block
  11531. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11532. (member (plist-get change-plist :from)
  11533. (cons 'done org-done-keywords))
  11534. (member (plist-get change-plist :to)
  11535. (cons 'todo org-not-done-keywords))
  11536. (not (plist-get change-plist :to)))
  11537. (throw 'dont-block t))
  11538. ;; If this task has children, and any are undone, it's blocked
  11539. (save-excursion
  11540. (org-back-to-heading t)
  11541. (let ((this-level (funcall outline-level)))
  11542. (outline-next-heading)
  11543. (let ((child-level (funcall outline-level)))
  11544. (while (and (not (eobp))
  11545. (> child-level this-level))
  11546. ;; this todo has children, check whether they are all
  11547. ;; completed
  11548. (when (and (not (org-entry-is-done-p))
  11549. (org-entry-is-todo-p))
  11550. (setq org-block-entry-blocking (org-get-heading))
  11551. (throw 'dont-block nil))
  11552. (outline-next-heading)
  11553. (setq child-level (funcall outline-level))))))
  11554. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11555. ;; any previous siblings are undone, it's blocked
  11556. (save-excursion
  11557. (org-back-to-heading t)
  11558. (let* ((pos (point))
  11559. (parent-pos (and (org-up-heading-safe) (point))))
  11560. (unless parent-pos (throw 'dont-block t)) ; no parent
  11561. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11562. (forward-line 1)
  11563. (re-search-forward org-not-done-heading-regexp pos t))
  11564. (setq org-block-entry-blocking (match-string 0))
  11565. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11566. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11567. (while t
  11568. (goto-char parent-pos)
  11569. (unless (looking-at org-not-done-heading-regexp)
  11570. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11571. (setq pos (point))
  11572. (setq parent-pos (and (org-up-heading-safe) (point)))
  11573. (unless parent-pos (throw 'dont-block t)) ; no parent
  11574. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11575. (forward-line 1)
  11576. (re-search-forward org-not-done-heading-regexp pos t)
  11577. (setq org-block-entry-blocking (org-get-heading)))
  11578. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11579. (defcustom org-track-ordered-property-with-tag nil
  11580. "Should the ORDERED property also be shown as a tag?
  11581. The ORDERED property decides if an entry should require subtasks to be
  11582. completed in sequence. Since a property is not very visible, setting
  11583. this option means that toggling the ORDERED property with the command
  11584. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11585. not relevant for the behavior, but it makes things more visible.
  11586. Note that toggling the tag with tags commands will not change the property
  11587. and therefore not influence behavior!
  11588. This can be t, meaning the tag ORDERED should be used, It can also be a
  11589. string to select a different tag for this task."
  11590. :group 'org-todo
  11591. :type '(choice
  11592. (const :tag "No tracking" nil)
  11593. (const :tag "Track with ORDERED tag" t)
  11594. (string :tag "Use other tag")))
  11595. (defun org-toggle-ordered-property ()
  11596. "Toggle the ORDERED property of the current entry.
  11597. For better visibility, you can track the value of this property with a tag.
  11598. See variable `org-track-ordered-property-with-tag'."
  11599. (interactive)
  11600. (let* ((t1 org-track-ordered-property-with-tag)
  11601. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11602. (save-excursion
  11603. (org-back-to-heading)
  11604. (if (org-entry-get nil "ORDERED")
  11605. (progn
  11606. (org-delete-property "ORDERED")
  11607. (and tag (org-toggle-tag tag 'off))
  11608. (message "Subtasks can be completed in arbitrary order"))
  11609. (org-entry-put nil "ORDERED" "t")
  11610. (and tag (org-toggle-tag tag 'on))
  11611. (message "Subtasks must be completed in sequence")))))
  11612. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11613. (defun org-block-todo-from-checkboxes (change-plist)
  11614. "Block turning an entry into a TODO, using checkboxes.
  11615. This checks whether the current task should be blocked from state
  11616. changes because there are unchecked boxes in this entry."
  11617. (if (not org-enforce-todo-checkbox-dependencies)
  11618. t ; if locally turned off don't block
  11619. (catch 'dont-block
  11620. ;; If this is not a todo state change, or if this entry is already DONE,
  11621. ;; do not block
  11622. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11623. (member (plist-get change-plist :from)
  11624. (cons 'done org-done-keywords))
  11625. (member (plist-get change-plist :to)
  11626. (cons 'todo org-not-done-keywords))
  11627. (not (plist-get change-plist :to)))
  11628. (throw 'dont-block t))
  11629. ;; If this task has checkboxes that are not checked, it's blocked
  11630. (save-excursion
  11631. (org-back-to-heading t)
  11632. (let ((beg (point)) end)
  11633. (outline-next-heading)
  11634. (setq end (point))
  11635. (goto-char beg)
  11636. (when (org-list-search-forward
  11637. (concat (org-item-beginning-re)
  11638. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11639. "\\[[- ]\\]")
  11640. end t)
  11641. (when (boundp 'org-blocked-by-checkboxes)
  11642. (setq org-blocked-by-checkboxes t))
  11643. (throw 'dont-block nil))))
  11644. t))) ; do not block
  11645. (defun org-entry-blocked-p ()
  11646. "Non-nil if entry at point is blocked."
  11647. (and (not (org-entry-get nil "NOBLOCKING"))
  11648. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11649. (not (run-hook-with-args-until-failure
  11650. 'org-blocker-hook
  11651. (list :type 'todo-state-change
  11652. :position (point)
  11653. :from 'todo
  11654. :to 'done)))))
  11655. (defun org-update-statistics-cookies (all)
  11656. "Update the statistics cookie, either from TODO or from checkboxes.
  11657. This should be called with the cursor in a line with a statistics
  11658. cookie. When called with a \\[universal-argument] prefix, update
  11659. all statistics cookies in the buffer."
  11660. (interactive "P")
  11661. (if all
  11662. (progn
  11663. (org-update-checkbox-count 'all)
  11664. (org-map-entries 'org-update-parent-todo-statistics))
  11665. (if (not (org-at-heading-p))
  11666. (org-update-checkbox-count)
  11667. (let ((pos (point-marker))
  11668. end l1 l2)
  11669. (ignore-errors (org-back-to-heading t))
  11670. (if (not (org-at-heading-p))
  11671. (org-update-checkbox-count)
  11672. (setq l1 (org-outline-level))
  11673. (setq end (save-excursion
  11674. (outline-next-heading)
  11675. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11676. (point)))
  11677. (if (and (save-excursion
  11678. (re-search-forward
  11679. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11680. (not (save-excursion (re-search-forward
  11681. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11682. (org-update-checkbox-count)
  11683. (if (and l2 (> l2 l1))
  11684. (progn
  11685. (goto-char end)
  11686. (org-update-parent-todo-statistics))
  11687. (goto-char pos)
  11688. (beginning-of-line 1)
  11689. (while (re-search-forward
  11690. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11691. (point-at-eol) t)
  11692. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11693. (goto-char pos)
  11694. (move-marker pos nil)))))
  11695. (defvar org-entry-property-inherited-from) ;; defined below
  11696. (defun org-update-parent-todo-statistics ()
  11697. "Update any statistics cookie in the parent of the current headline.
  11698. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11699. the entire subtree and this will travel up the hierarchy and update
  11700. statistics everywhere."
  11701. (let* ((prop (save-excursion (org-up-heading-safe)
  11702. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11703. (recursive (or (not org-hierarchical-todo-statistics)
  11704. (and prop (string-match "\\<recursive\\>" prop))))
  11705. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11706. 0))
  11707. (first t)
  11708. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11709. level ltoggle l1 new ndel
  11710. (cnt-all 0) (cnt-done 0) is-percent kwd
  11711. checkbox-beg cookie-present)
  11712. (catch 'exit
  11713. (save-excursion
  11714. (beginning-of-line 1)
  11715. (setq ltoggle (funcall outline-level))
  11716. ;; Three situations are to consider:
  11717. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11718. ;; to the top-level ancestor on the headline;
  11719. ;; 2. If parent has "recursive" property, repeat up to the
  11720. ;; headline setting that property, taking inheritance into
  11721. ;; account;
  11722. ;; 3. Else, move up to direct parent and proceed only once.
  11723. (while (and (setq level (org-up-heading-safe))
  11724. (or recursive first)
  11725. (>= (point) lim))
  11726. (setq first nil cookie-present nil)
  11727. (unless (and level
  11728. (not (string-match
  11729. "\\<checkbox\\>"
  11730. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11731. "")))))
  11732. (throw 'exit nil))
  11733. (while (re-search-forward box-re (point-at-eol) t)
  11734. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11735. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11736. (save-match-data
  11737. (unless (outline-next-heading) (throw 'exit nil))
  11738. (while (and (looking-at org-complex-heading-regexp)
  11739. (> (setq l1 (length (match-string 1))) level))
  11740. (setq kwd (and (or recursive (= l1 ltoggle))
  11741. (match-string 2)))
  11742. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11743. (and (eq org-provide-todo-statistics t)
  11744. (or (member kwd org-done-keywords)))
  11745. (and (listp org-provide-todo-statistics)
  11746. (stringp (car org-provide-todo-statistics))
  11747. (or (member kwd org-provide-todo-statistics)
  11748. (member kwd org-done-keywords)))
  11749. (and (listp org-provide-todo-statistics)
  11750. (listp (car org-provide-todo-statistics))
  11751. (or (member kwd (car org-provide-todo-statistics))
  11752. (and (member kwd org-done-keywords)
  11753. (member kwd (cadr org-provide-todo-statistics))))))
  11754. (setq cnt-all (1+ cnt-all))
  11755. (and (eq org-provide-todo-statistics t)
  11756. kwd
  11757. (setq cnt-all (1+ cnt-all))))
  11758. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11759. (member kwd org-done-keywords))
  11760. (and (listp org-provide-todo-statistics)
  11761. (listp (car org-provide-todo-statistics))
  11762. (member kwd org-done-keywords)
  11763. (member kwd (cadr org-provide-todo-statistics)))
  11764. (and (listp org-provide-todo-statistics)
  11765. (stringp (car org-provide-todo-statistics))
  11766. (member kwd org-done-keywords)))
  11767. (setq cnt-done (1+ cnt-done)))
  11768. (outline-next-heading)))
  11769. (setq new
  11770. (if is-percent
  11771. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11772. (max 1 cnt-all)))
  11773. (format "[%d/%d]" cnt-done cnt-all))
  11774. ndel (- (match-end 0) checkbox-beg))
  11775. (goto-char checkbox-beg)
  11776. (insert new)
  11777. (delete-region (point) (+ (point) ndel))
  11778. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11779. (when cookie-present
  11780. (run-hook-with-args 'org-after-todo-statistics-hook
  11781. cnt-done (- cnt-all cnt-done))))))
  11782. (run-hooks 'org-todo-statistics-hook)))
  11783. (defvar org-after-todo-statistics-hook nil
  11784. "Hook that is called after a TODO statistics cookie has been updated.
  11785. Each function is called with two arguments: the number of not-done entries
  11786. and the number of done entries.
  11787. For example, the following function, when added to this hook, will switch
  11788. an entry to DONE when all children are done, and back to TODO when new
  11789. entries are set to a TODO status. Note that this hook is only called
  11790. when there is a statistics cookie in the headline!
  11791. \(defun org-summary-todo (n-done n-not-done)
  11792. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11793. \(let (org-log-done org-log-states) ; turn off logging
  11794. \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11795. ")
  11796. (defvar org-todo-statistics-hook nil
  11797. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11798. This hook runs even if there is no statistics cookie present, in which case
  11799. `org-after-todo-statistics-hook' would not run.")
  11800. (defun org-todo-trigger-tag-changes (state)
  11801. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11802. (let ((l org-todo-state-tags-triggers)
  11803. changes)
  11804. (when (or (not state) (equal state ""))
  11805. (setq changes (append changes (cdr (assoc "" l)))))
  11806. (when (and (stringp state) (> (length state) 0))
  11807. (setq changes (append changes (cdr (assoc state l)))))
  11808. (when (member state org-not-done-keywords)
  11809. (setq changes (append changes (cdr (assq 'todo l)))))
  11810. (when (member state org-done-keywords)
  11811. (setq changes (append changes (cdr (assq 'done l)))))
  11812. (dolist (c changes)
  11813. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11814. (defun org-local-logging (value)
  11815. "Get logging settings from a property VALUE."
  11816. ;; Directly set the variables, they are already local.
  11817. (setq org-log-done nil
  11818. org-log-repeat nil
  11819. org-todo-log-states nil)
  11820. (dolist (w (org-split-string value))
  11821. (let (a)
  11822. (cond
  11823. ((setq a (assoc w org-startup-options))
  11824. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11825. (set (nth 1 a) (nth 2 a))))
  11826. ((setq a (org-extract-log-state-settings w))
  11827. (and (member (car a) org-todo-keywords-1)
  11828. (push a org-todo-log-states)))))))
  11829. (defun org-get-todo-sequence-head (kwd)
  11830. "Return the head of the TODO sequence to which KWD belongs.
  11831. If KWD is not set, check if there is a text property remembering the
  11832. right sequence."
  11833. (let (p)
  11834. (cond
  11835. ((not kwd)
  11836. (or (get-text-property (point-at-bol) 'org-todo-head)
  11837. (progn
  11838. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11839. nil (point-at-eol)))
  11840. (get-text-property p 'org-todo-head))))
  11841. ((not (member kwd org-todo-keywords-1))
  11842. (car org-todo-keywords-1))
  11843. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11844. (defun org-fast-todo-selection ()
  11845. "Fast TODO keyword selection with single keys.
  11846. Returns the new TODO keyword, or nil if no state change should occur."
  11847. (let* ((fulltable org-todo-key-alist)
  11848. (done-keywords org-done-keywords) ;; needed for the faces.
  11849. (maxlen (apply 'max (mapcar
  11850. (lambda (x)
  11851. (if (stringp (car x)) (string-width (car x)) 0))
  11852. fulltable)))
  11853. (expert nil)
  11854. (fwidth (+ maxlen 3 1 3))
  11855. (ncol (/ (- (window-width) 4) fwidth))
  11856. tg cnt e c tbl
  11857. groups ingroup)
  11858. (save-excursion
  11859. (save-window-excursion
  11860. (if expert
  11861. (set-buffer (get-buffer-create " *Org todo*"))
  11862. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11863. (erase-buffer)
  11864. (setq-local org-done-keywords done-keywords)
  11865. (setq tbl fulltable cnt 0)
  11866. (while (setq e (pop tbl))
  11867. (cond
  11868. ((equal e '(:startgroup))
  11869. (push '() groups) (setq ingroup t)
  11870. (unless (= cnt 0)
  11871. (setq cnt 0)
  11872. (insert "\n"))
  11873. (insert "{ "))
  11874. ((equal e '(:endgroup))
  11875. (setq ingroup nil cnt 0)
  11876. (insert "}\n"))
  11877. ((equal e '(:newline))
  11878. (unless (= cnt 0)
  11879. (setq cnt 0)
  11880. (insert "\n")
  11881. (setq e (car tbl))
  11882. (while (equal (car tbl) '(:newline))
  11883. (insert "\n")
  11884. (setq tbl (cdr tbl)))))
  11885. (t
  11886. (setq tg (car e) c (cdr e))
  11887. (when ingroup (push tg (car groups)))
  11888. (setq tg (org-add-props tg nil 'face
  11889. (org-get-todo-face tg)))
  11890. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11891. (insert "[" c "] " tg (make-string
  11892. (- fwidth 4 (length tg)) ?\ ))
  11893. (when (= (setq cnt (1+ cnt)) ncol)
  11894. (insert "\n")
  11895. (when ingroup (insert " "))
  11896. (setq cnt 0)))))
  11897. (insert "\n")
  11898. (goto-char (point-min))
  11899. (unless expert (org-fit-window-to-buffer))
  11900. (message "[a-z..]:Set [SPC]:clear")
  11901. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11902. (cond
  11903. ((or (= c ?\C-g)
  11904. (and (= c ?q) (not (rassoc c fulltable))))
  11905. (setq quit-flag t))
  11906. ((= c ?\ ) nil)
  11907. ((setq e (rassoc c fulltable) tg (car e))
  11908. tg)
  11909. (t (setq quit-flag t)))))))
  11910. (defun org-entry-is-todo-p ()
  11911. (member (org-get-todo-state) org-not-done-keywords))
  11912. (defun org-entry-is-done-p ()
  11913. (member (org-get-todo-state) org-done-keywords))
  11914. (defun org-get-todo-state ()
  11915. "Return the TODO keyword of the current subtree."
  11916. (save-excursion
  11917. (org-back-to-heading t)
  11918. (and (looking-at org-todo-line-regexp)
  11919. (match-end 2)
  11920. (match-string 2))))
  11921. (defun org-at-date-range-p (&optional inactive-ok)
  11922. "Non-nil if point is inside a date range.
  11923. When optional argument INACTIVE-OK is non-nil, also consider
  11924. inactive time ranges.
  11925. When this function returns a non-nil value, match data is set
  11926. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11927. on INACTIVE-OK."
  11928. (interactive)
  11929. (save-excursion
  11930. (catch 'exit
  11931. (let ((pos (point)))
  11932. (skip-chars-backward "^[<\r\n")
  11933. (skip-chars-backward "<[")
  11934. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11935. (>= (match-end 0) pos)
  11936. (throw 'exit t))
  11937. (skip-chars-backward "^<[\r\n")
  11938. (skip-chars-backward "<[")
  11939. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11940. (>= (match-end 0) pos)
  11941. (throw 'exit t)))
  11942. nil)))
  11943. (defun org-get-repeat (&optional tagline)
  11944. "Check if there is a deadline/schedule with repeater in this entry."
  11945. (save-match-data
  11946. (save-excursion
  11947. (org-back-to-heading t)
  11948. (and (re-search-forward (if tagline
  11949. (concat tagline "\\s-*" org-repeat-re)
  11950. org-repeat-re)
  11951. (org-entry-end-position) t)
  11952. (match-string-no-properties 1)))))
  11953. (defvar org-last-changed-timestamp)
  11954. (defvar org-last-inserted-timestamp)
  11955. (defvar org-log-post-message)
  11956. (defvar org-log-note-purpose)
  11957. (defvar org-log-note-how nil)
  11958. (defvar org-log-note-extra)
  11959. (defun org-auto-repeat-maybe (done-word)
  11960. "Check if the current headline contains a repeated time-stamp.
  11961. If yes, set TODO state back to what it was and change the base date
  11962. of repeating deadline/scheduled time stamps to new date.
  11963. This function is run automatically after each state change to a DONE state."
  11964. (let* ((repeat (org-get-repeat))
  11965. (aa (assoc org-last-state org-todo-kwd-alist))
  11966. (interpret (nth 1 aa))
  11967. (head (nth 2 aa))
  11968. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11969. (msg "Entry repeats: ")
  11970. (org-log-done nil)
  11971. (org-todo-log-states nil))
  11972. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11973. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11974. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11975. org-todo-repeat-to-state)))
  11976. (unless (and to-state (member to-state org-todo-keywords-1))
  11977. (setq to-state (if (eq interpret 'type) org-last-state head)))
  11978. (org-todo to-state))
  11979. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11980. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11981. (org-time-stamp-format t t))))
  11982. (when org-log-repeat
  11983. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11984. (memq 'org-add-log-note post-command-hook))
  11985. ;; We are already setup for some record.
  11986. (when (eq org-log-repeat 'note)
  11987. ;; Make sure we take a note, not only a time stamp.
  11988. (setq org-log-note-how 'note))
  11989. ;; Set up for taking a record.
  11990. (org-add-log-setup 'state
  11991. (or done-word (car org-done-keywords))
  11992. org-last-state
  11993. org-log-repeat)))
  11994. (org-back-to-heading t)
  11995. (org-add-planning-info nil nil 'closed)
  11996. (let ((end (save-excursion (outline-next-heading) (point))))
  11997. (while (re-search-forward org-ts-regexp end t)
  11998. (when (save-match-data
  11999. (or (org-at-planning-p)
  12000. (org-at-property-p)
  12001. (eq (org-element-type (save-excursion
  12002. (backward-char)
  12003. (org-element-context)))
  12004. 'timestamp)))
  12005. (let ((type (cond ((match-end 1) org-scheduled-string)
  12006. ((match-end 3) org-deadline-string)
  12007. (t "Plain:")))
  12008. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  12009. (cond
  12010. ((not
  12011. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12012. ;; Time-stamps without a repeater are usually skipped.
  12013. ;; However, a SCHEDULED time-stamp without one is
  12014. ;; removed, as it is considered as no longer relevant.
  12015. (when (equal type org-scheduled-string)
  12016. (org-remove-timestamp-with-keyword type)))
  12017. (t
  12018. (let ((n (string-to-number (match-string 2 ts)))
  12019. (what (match-string 3 ts)))
  12020. (when (equal what "w") (setq n (* n 7) what "d"))
  12021. (when (and (equal what "h")
  12022. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12023. ts)))
  12024. (user-error
  12025. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12026. has been set"
  12027. n))
  12028. ;; Preparation, see if we need to modify the start
  12029. ;; date for the change.
  12030. (when (match-end 1)
  12031. (let ((time (save-match-data (org-time-string-to-time ts))))
  12032. (cond
  12033. ((equal (match-string 1 ts) ".")
  12034. ;; Shift starting date to today
  12035. (org-timestamp-change
  12036. (- (org-today) (time-to-days time))
  12037. 'day))
  12038. ((equal (match-string 1 ts) "+")
  12039. (let ((nshiftmax 10)
  12040. (nshift 0))
  12041. (while (or (= nshift 0)
  12042. (not (time-less-p (current-time) time)))
  12043. (when (= (cl-incf nshift) nshiftmax)
  12044. (or (y-or-n-p
  12045. (format "%d repeater intervals were not \
  12046. enough to shift date past today. Continue? "
  12047. nshift))
  12048. (user-error "Abort")))
  12049. (org-timestamp-change n (cdr (assoc what whata)))
  12050. (org-at-timestamp-p t)
  12051. (setq ts (match-string 1))
  12052. (setq time
  12053. (save-match-data
  12054. (org-time-string-to-time ts)))))
  12055. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12056. ;; Rematch, so that we have everything in
  12057. ;; place for the real shift.
  12058. (org-at-timestamp-p t)
  12059. (setq ts (match-string 1))
  12060. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12061. ts)))))
  12062. (save-excursion
  12063. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12064. (setq msg
  12065. (concat
  12066. msg type " " org-last-changed-timestamp " ")))))))))
  12067. (setq org-log-post-message msg)
  12068. (message "%s" msg))))
  12069. (defun org-show-todo-tree (arg)
  12070. "Make a compact tree which shows all headlines marked with TODO.
  12071. The tree will show the lines where the regexp matches, and all higher
  12072. headlines above the match.
  12073. With a \\[universal-argument] prefix, prompt for a regexp to match.
  12074. With a numeric prefix N, construct a sparse tree for the Nth element
  12075. of `org-todo-keywords-1'."
  12076. (interactive "P")
  12077. (let ((case-fold-search nil)
  12078. (kwd-re
  12079. (cond ((null arg) org-not-done-regexp)
  12080. ((equal arg '(4))
  12081. (let ((kwd
  12082. (completing-read "Keyword (or KWD1|KWD2|...): "
  12083. (mapcar #'list org-todo-keywords-1))))
  12084. (concat "\\("
  12085. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12086. "\\)\\>")))
  12087. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12088. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12089. org-todo-keywords-1)))
  12090. (t (user-error "Invalid prefix argument: %s" arg)))))
  12091. (message "%d TODO entries found"
  12092. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12093. (defun org-deadline (arg &optional time)
  12094. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12095. With one universal prefix argument, remove any deadline from the item.
  12096. With two universal prefix arguments, prompt for a warning delay.
  12097. With argument TIME, set the deadline at the corresponding date. TIME
  12098. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12099. (interactive "P")
  12100. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12101. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12102. 'region-start-level 'region))
  12103. org-loop-over-headlines-in-active-region)
  12104. (org-map-entries
  12105. `(org-deadline ',arg ,time)
  12106. org-loop-over-headlines-in-active-region
  12107. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12108. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12109. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12110. (repeater (and old-date
  12111. (string-match
  12112. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12113. old-date)
  12114. (match-string 1 old-date))))
  12115. (cond
  12116. ((equal arg '(4))
  12117. (when (and old-date org-log-redeadline)
  12118. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12119. (org-remove-timestamp-with-keyword org-deadline-string)
  12120. (message "Item no longer has a deadline."))
  12121. ((equal arg '(16))
  12122. (save-excursion
  12123. (org-back-to-heading t)
  12124. (if (re-search-forward
  12125. org-deadline-time-regexp
  12126. (save-excursion (outline-next-heading) (point)) t)
  12127. (let* ((rpl0 (match-string 1))
  12128. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12129. (replace-match
  12130. (concat org-deadline-string
  12131. " <" rpl
  12132. (format " -%dd"
  12133. (abs
  12134. (- (time-to-days
  12135. (save-match-data
  12136. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12137. (time-to-days old-date-time))))
  12138. ">") t t))
  12139. (user-error "No deadline information to update"))))
  12140. (t
  12141. (org-add-planning-info 'deadline time 'closed)
  12142. (when (and old-date
  12143. org-log-redeadline
  12144. (not (equal old-date org-last-inserted-timestamp)))
  12145. (org-add-log-setup
  12146. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12147. (when repeater
  12148. (save-excursion
  12149. (org-back-to-heading t)
  12150. (when (re-search-forward (concat org-deadline-string " "
  12151. org-last-inserted-timestamp)
  12152. (save-excursion
  12153. (outline-next-heading) (point)) t)
  12154. (goto-char (1- (match-end 0)))
  12155. (insert " " repeater)
  12156. (setq org-last-inserted-timestamp
  12157. (concat (substring org-last-inserted-timestamp 0 -1)
  12158. " " repeater
  12159. (substring org-last-inserted-timestamp -1))))))
  12160. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12161. (defun org-schedule (arg &optional time)
  12162. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12163. With one universal prefix argument, remove any scheduling date from the item.
  12164. With two universal prefix arguments, prompt for a delay cookie.
  12165. With argument TIME, scheduled at the corresponding date. TIME can
  12166. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12167. (interactive "P")
  12168. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12169. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12170. 'region-start-level 'region))
  12171. org-loop-over-headlines-in-active-region)
  12172. (org-map-entries
  12173. `(org-schedule ',arg ,time)
  12174. org-loop-over-headlines-in-active-region
  12175. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12176. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12177. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12178. (repeater (and old-date
  12179. (string-match
  12180. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12181. old-date)
  12182. (match-string 1 old-date))))
  12183. (cond
  12184. ((equal arg '(4))
  12185. (progn
  12186. (when (and old-date org-log-reschedule)
  12187. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12188. (org-remove-timestamp-with-keyword org-scheduled-string)
  12189. (message "Item is no longer scheduled.")))
  12190. ((equal arg '(16))
  12191. (save-excursion
  12192. (org-back-to-heading t)
  12193. (if (re-search-forward
  12194. org-scheduled-time-regexp
  12195. (save-excursion (outline-next-heading) (point)) t)
  12196. (let* ((rpl0 (match-string 1))
  12197. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12198. (replace-match
  12199. (concat org-scheduled-string
  12200. " <" rpl
  12201. (format " -%dd"
  12202. (abs
  12203. (- (time-to-days
  12204. (save-match-data
  12205. (org-read-date nil t nil "Delay until" old-date-time)))
  12206. (time-to-days old-date-time))))
  12207. ">") t t))
  12208. (user-error "No scheduled information to update"))))
  12209. (t
  12210. (org-add-planning-info 'scheduled time 'closed)
  12211. (when (and old-date
  12212. org-log-reschedule
  12213. (not (equal old-date org-last-inserted-timestamp)))
  12214. (org-add-log-setup
  12215. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12216. (when repeater
  12217. (save-excursion
  12218. (org-back-to-heading t)
  12219. (when (re-search-forward (concat org-scheduled-string " "
  12220. org-last-inserted-timestamp)
  12221. (save-excursion
  12222. (outline-next-heading) (point)) t)
  12223. (goto-char (1- (match-end 0)))
  12224. (insert " " repeater)
  12225. (setq org-last-inserted-timestamp
  12226. (concat (substring org-last-inserted-timestamp 0 -1)
  12227. " " repeater
  12228. (substring org-last-inserted-timestamp -1))))))
  12229. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12230. (defun org-get-scheduled-time (pom &optional inherit)
  12231. "Get the scheduled time as a time tuple, of a format suitable
  12232. for calling org-schedule with, or if there is no scheduling,
  12233. returns nil."
  12234. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12235. (when time
  12236. (apply 'encode-time (org-parse-time-string time)))))
  12237. (defun org-get-deadline-time (pom &optional inherit)
  12238. "Get the deadline as a time tuple, of a format suitable for
  12239. calling org-deadline with, or if there is no scheduling, returns
  12240. nil."
  12241. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12242. (when time
  12243. (apply 'encode-time (org-parse-time-string time)))))
  12244. (defun org-remove-timestamp-with-keyword (keyword)
  12245. "Remove all time stamps with KEYWORD in the current entry."
  12246. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12247. beg)
  12248. (save-excursion
  12249. (org-back-to-heading t)
  12250. (setq beg (point))
  12251. (outline-next-heading)
  12252. (while (re-search-backward re beg t)
  12253. (replace-match "")
  12254. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12255. (equal (char-before) ?\ ))
  12256. (backward-delete-char 1)
  12257. (when (string-match "^[ \t]*$" (buffer-substring
  12258. (point-at-bol) (point-at-eol)))
  12259. (delete-region (point-at-bol)
  12260. (min (point-max) (1+ (point-at-eol))))))))))
  12261. (defvar org-time-was-given) ; dynamically scoped parameter
  12262. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12263. (defun org-at-planning-p ()
  12264. "Non-nil when point is on a planning info line."
  12265. ;; This is as accurate and faster than `org-element-at-point' since
  12266. ;; planning info location is fixed in the section.
  12267. (org-with-wide-buffer
  12268. (beginning-of-line)
  12269. (and (looking-at-p org-planning-line-re)
  12270. (eq (point)
  12271. (ignore-errors
  12272. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12273. (org-back-to-heading t)
  12274. (org-with-limited-levels (org-back-to-heading t)))
  12275. (line-beginning-position 2))))))
  12276. (defun org-add-planning-info (what &optional time &rest remove)
  12277. "Insert new timestamp with keyword in the planning line.
  12278. WHAT indicates what kind of time stamp to add. It is a symbol
  12279. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12280. the time to use. If none is given, the user is prompted for
  12281. a date. REMOVE indicates what kind of entries to remove. An old
  12282. WHAT entry will also be removed."
  12283. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12284. (catch 'exit
  12285. (when (and (memq what '(scheduled deadline))
  12286. (or (not time)
  12287. (and (stringp time)
  12288. (string-match "^[-+]+[0-9]" time))))
  12289. ;; Try to get a default date/time from existing timestamp
  12290. (save-excursion
  12291. (org-back-to-heading t)
  12292. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12293. (when (re-search-forward (if (eq what 'scheduled)
  12294. org-scheduled-time-regexp
  12295. org-deadline-time-regexp)
  12296. end t)
  12297. (setq ts (match-string 1)
  12298. default-time (apply 'encode-time (org-parse-time-string ts))
  12299. default-input (and ts (org-get-compact-tod ts)))))))
  12300. (when what
  12301. (setq time
  12302. (if (stringp time)
  12303. ;; This is a string (relative or absolute), set
  12304. ;; proper date.
  12305. (apply #'encode-time
  12306. (org-read-date-analyze
  12307. time default-time (decode-time default-time)))
  12308. ;; If necessary, get the time from the user
  12309. (or time (org-read-date nil 'to-time nil nil
  12310. default-time default-input)))))
  12311. (org-with-wide-buffer
  12312. (org-back-to-heading t)
  12313. (forward-line)
  12314. (unless (bolp) (insert "\n"))
  12315. (cond ((looking-at-p org-planning-line-re)
  12316. ;; Move to current indentation.
  12317. (skip-chars-forward " \t")
  12318. ;; Check if we have to remove something.
  12319. (dolist (type (if what (cons what remove) remove))
  12320. (save-excursion
  12321. (when (re-search-forward
  12322. (cl-case type
  12323. (closed org-closed-time-regexp)
  12324. (deadline org-deadline-time-regexp)
  12325. (scheduled org-scheduled-time-regexp)
  12326. (otherwise
  12327. (error "Invalid planning type: %s" type)))
  12328. (line-end-position) t)
  12329. ;; Delete until next keyword or end of line.
  12330. (delete-region
  12331. (match-beginning 0)
  12332. (if (re-search-forward org-keyword-time-not-clock-regexp
  12333. (line-end-position)
  12334. t)
  12335. (match-beginning 0)
  12336. (line-end-position))))))
  12337. ;; If there is nothing more to add and no more keyword
  12338. ;; is left, remove the line completely.
  12339. (if (and (looking-at-p "[ \t]*$") (not what))
  12340. (delete-region (line-beginning-position)
  12341. (line-beginning-position 2))
  12342. ;; If we removed last keyword, do not leave trailing
  12343. ;; white space at the end of line.
  12344. (let ((p (point)))
  12345. (save-excursion
  12346. (end-of-line)
  12347. (unless (= (skip-chars-backward " \t" p) 0)
  12348. (delete-region (point) (line-end-position)))))))
  12349. ((not what) (throw 'exit nil)) ; Nothing to do.
  12350. (t (insert-before-markers "\n")
  12351. (backward-char 1)
  12352. (when org-adapt-indentation
  12353. (indent-to-column (1+ (org-outline-level))))))
  12354. (when what
  12355. ;; Insert planning keyword.
  12356. (insert (cl-case what
  12357. (closed org-closed-string)
  12358. (deadline org-deadline-string)
  12359. (scheduled org-scheduled-string)
  12360. (otherwise (error "Invalid planning type: %s" what)))
  12361. " ")
  12362. ;; Insert associated timestamp.
  12363. (let ((ts (org-insert-time-stamp
  12364. time
  12365. (or org-time-was-given
  12366. (and (eq what 'closed) org-log-done-with-time))
  12367. (eq what 'closed)
  12368. nil nil (list org-end-time-was-given))))
  12369. (unless (eolp) (insert " "))
  12370. ts))))))
  12371. (defvar org-log-note-marker (make-marker)
  12372. "Marker pointing at the entry where the note is to be inserted.")
  12373. (defvar org-log-note-purpose nil)
  12374. (defvar org-log-note-state nil)
  12375. (defvar org-log-note-previous-state nil)
  12376. (defvar org-log-note-extra nil)
  12377. (defvar org-log-note-window-configuration nil)
  12378. (defvar org-log-note-return-to (make-marker))
  12379. (defvar org-log-note-effective-time nil
  12380. "Remembered current time so that dynamically scoped
  12381. `org-extend-today-until' affects timestamps in state change log")
  12382. (defvar org-log-post-message nil
  12383. "Message to be displayed after a log note has been stored.
  12384. The auto-repeater uses this.")
  12385. (defun org-add-note ()
  12386. "Add a note to the current entry.
  12387. This is done in the same way as adding a state change note."
  12388. (interactive)
  12389. (org-add-log-setup 'note))
  12390. (defun org-log-beginning (&optional create)
  12391. "Return expected start of log notes in current entry.
  12392. When optional argument CREATE is non-nil, the function creates
  12393. a drawer to store notes, if necessary. Returned position ignores
  12394. narrowing."
  12395. (org-with-wide-buffer
  12396. (let ((drawer (org-log-into-drawer)))
  12397. (cond
  12398. (drawer
  12399. (org-end-of-meta-data)
  12400. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12401. (end (if (org-at-heading-p) (point)
  12402. (save-excursion (outline-next-heading) (point))))
  12403. (case-fold-search t))
  12404. (catch 'exit
  12405. ;; Try to find existing drawer.
  12406. (while (re-search-forward regexp end t)
  12407. (let ((element (org-element-at-point)))
  12408. (when (eq (org-element-type element) 'drawer)
  12409. (let ((cend (org-element-property :contents-end element)))
  12410. (when (and (not org-log-states-order-reversed) cend)
  12411. (goto-char cend)))
  12412. (throw 'exit nil))))
  12413. ;; No drawer found. Create one, if permitted.
  12414. (when create
  12415. (unless (bolp) (insert "\n"))
  12416. (let ((beg (point)))
  12417. (insert ":" drawer ":\n:END:\n")
  12418. (org-indent-region beg (point)))
  12419. (end-of-line -1)))))
  12420. (t
  12421. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12422. (skip-chars-forward " \t\n")
  12423. (beginning-of-line)
  12424. (unless org-log-states-order-reversed
  12425. (org-skip-over-state-notes)
  12426. (skip-chars-backward " \t\n")
  12427. (forward-line)))))
  12428. (if (bolp) (point) (line-beginning-position 2))))
  12429. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12430. "Set up the post command hook to take a note.
  12431. If this is about to TODO state change, the new state is expected in STATE.
  12432. HOW is an indicator what kind of note should be created.
  12433. EXTRA is additional text that will be inserted into the notes buffer."
  12434. (move-marker org-log-note-marker (point))
  12435. (setq org-log-note-purpose purpose
  12436. org-log-note-state state
  12437. org-log-note-previous-state prev-state
  12438. org-log-note-how how
  12439. org-log-note-extra extra
  12440. org-log-note-effective-time (org-current-effective-time))
  12441. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12442. (defun org-skip-over-state-notes ()
  12443. "Skip past the list of State notes in an entry."
  12444. (when (ignore-errors (goto-char (org-in-item-p)))
  12445. (let* ((struct (org-list-struct))
  12446. (prevs (org-list-prevs-alist struct))
  12447. (regexp
  12448. (concat "[ \t]*- +"
  12449. (replace-regexp-in-string
  12450. " +" " +"
  12451. (org-replace-escapes
  12452. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12453. `(("%d" . ,org-ts-regexp-inactive)
  12454. ("%D" . ,org-ts-regexp)
  12455. ("%s" . "\"\\S-+\"")
  12456. ("%S" . "\"\\S-+\"")
  12457. ("%t" . ,org-ts-regexp-inactive)
  12458. ("%T" . ,org-ts-regexp)
  12459. ("%u" . ".*?")
  12460. ("%U" . ".*?")))))))
  12461. (while (looking-at-p regexp)
  12462. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12463. (org-list-get-item-end (point) struct)))))))
  12464. (defun org-add-log-note (&optional _purpose)
  12465. "Pop up a window for taking a note, and add this note later."
  12466. (remove-hook 'post-command-hook 'org-add-log-note)
  12467. (setq org-log-note-window-configuration (current-window-configuration))
  12468. (delete-other-windows)
  12469. (move-marker org-log-note-return-to (point))
  12470. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12471. (goto-char org-log-note-marker)
  12472. (org-switch-to-buffer-other-window "*Org Note*")
  12473. (erase-buffer)
  12474. (if (memq org-log-note-how '(time state))
  12475. (let (current-prefix-arg) (org-store-log-note))
  12476. (let ((org-inhibit-startup t)) (org-mode))
  12477. (insert (format "# Insert note for %s.
  12478. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12479. (cond
  12480. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12481. ((eq org-log-note-purpose 'done) "closed todo item")
  12482. ((eq org-log-note-purpose 'state)
  12483. (format "state change from \"%s\" to \"%s\""
  12484. (or org-log-note-previous-state "")
  12485. (or org-log-note-state "")))
  12486. ((eq org-log-note-purpose 'reschedule)
  12487. "rescheduling")
  12488. ((eq org-log-note-purpose 'delschedule)
  12489. "no longer scheduled")
  12490. ((eq org-log-note-purpose 'redeadline)
  12491. "changing deadline")
  12492. ((eq org-log-note-purpose 'deldeadline)
  12493. "removing deadline")
  12494. ((eq org-log-note-purpose 'refile)
  12495. "refiling")
  12496. ((eq org-log-note-purpose 'note)
  12497. "this entry")
  12498. (t (error "This should not happen")))))
  12499. (when org-log-note-extra (insert org-log-note-extra))
  12500. (setq-local org-finish-function 'org-store-log-note)
  12501. (run-hooks 'org-log-buffer-setup-hook)))
  12502. (defvar org-note-abort nil) ; dynamically scoped
  12503. (defun org-store-log-note ()
  12504. "Finish taking a log note, and insert it to where it belongs."
  12505. (let ((txt (prog1 (buffer-string)
  12506. (kill-buffer)))
  12507. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12508. lines)
  12509. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12510. (setq txt (replace-match "" t t txt)))
  12511. (when (string-match "\\s-+\\'" txt)
  12512. (setq txt (replace-match "" t t txt)))
  12513. (setq lines (org-split-string txt "\n"))
  12514. (when (org-string-nw-p note)
  12515. (setq note
  12516. (org-replace-escapes
  12517. note
  12518. (list (cons "%u" (user-login-name))
  12519. (cons "%U" user-full-name)
  12520. (cons "%t" (format-time-string
  12521. (org-time-stamp-format 'long 'inactive)
  12522. org-log-note-effective-time))
  12523. (cons "%T" (format-time-string
  12524. (org-time-stamp-format 'long nil)
  12525. org-log-note-effective-time))
  12526. (cons "%d" (format-time-string
  12527. (org-time-stamp-format nil 'inactive)
  12528. org-log-note-effective-time))
  12529. (cons "%D" (format-time-string
  12530. (org-time-stamp-format nil nil)
  12531. org-log-note-effective-time))
  12532. (cons "%s" (cond
  12533. ((not org-log-note-state) "")
  12534. ((string-match-p org-ts-regexp
  12535. org-log-note-state)
  12536. (format "\"[%s]\""
  12537. (substring org-log-note-state 1 -1)))
  12538. (t (format "\"%s\"" org-log-note-state))))
  12539. (cons "%S"
  12540. (cond
  12541. ((not org-log-note-previous-state) "")
  12542. ((string-match-p org-ts-regexp
  12543. org-log-note-previous-state)
  12544. (format "\"[%s]\""
  12545. (substring
  12546. org-log-note-previous-state 1 -1)))
  12547. (t (format "\"%s\""
  12548. org-log-note-previous-state)))))))
  12549. (when lines (setq note (concat note " \\\\")))
  12550. (push note lines))
  12551. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12552. (with-current-buffer (marker-buffer org-log-note-marker)
  12553. (org-with-wide-buffer
  12554. ;; Find location for the new note.
  12555. (goto-char org-log-note-marker)
  12556. (set-marker org-log-note-marker nil)
  12557. (goto-char (org-log-beginning t))
  12558. ;; Make sure point is at the beginning of an empty line.
  12559. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12560. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12561. ;; In an existing list, add a new item at the top level.
  12562. ;; Otherwise, indent line like a regular one.
  12563. (let ((itemp (org-in-item-p)))
  12564. (if itemp
  12565. (indent-line-to
  12566. (let ((struct (save-excursion
  12567. (goto-char itemp) (org-list-struct))))
  12568. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12569. (org-indent-line)))
  12570. (insert (org-list-bullet-string "-") (pop lines))
  12571. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12572. (dolist (line lines)
  12573. (insert "\n")
  12574. (indent-line-to ind)
  12575. (insert line)))
  12576. (message "Note stored")
  12577. (org-back-to-heading t)
  12578. (org-cycle-hide-drawers 'children))
  12579. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12580. ;; from within `org-add-log-note' because `buffer-undo-list'
  12581. ;; is then modified outside of `org-with-remote-undo'.
  12582. (when (eq this-command 'org-agenda-todo)
  12583. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12584. ;; Don't add undo information when called from `org-agenda-todo'.
  12585. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12586. (set-window-configuration org-log-note-window-configuration)
  12587. (with-current-buffer (marker-buffer org-log-note-return-to)
  12588. (goto-char org-log-note-return-to))
  12589. (move-marker org-log-note-return-to nil)
  12590. (when org-log-post-message (message "%s" org-log-post-message))))
  12591. (defun org-remove-empty-drawer-at (pos)
  12592. "Remove an empty drawer at position POS.
  12593. POS may also be a marker."
  12594. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12595. (org-with-wide-buffer
  12596. (goto-char pos)
  12597. (let ((drawer (org-element-at-point)))
  12598. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12599. (not (org-element-property :contents-begin drawer)))
  12600. (delete-region (org-element-property :begin drawer)
  12601. (progn (goto-char (org-element-property :end drawer))
  12602. (skip-chars-backward " \r\t\n")
  12603. (forward-line)
  12604. (point))))))))
  12605. (defvar org-ts-type nil)
  12606. (defun org-sparse-tree (&optional arg type)
  12607. "Create a sparse tree, prompt for the details.
  12608. This command can create sparse trees. You first need to select the type
  12609. of match used to create the tree:
  12610. t Show all TODO entries.
  12611. T Show entries with a specific TODO keyword.
  12612. m Show entries selected by a tags/property match.
  12613. p Enter a property name and its value (both with completion on existing
  12614. names/values) and show entries with that property.
  12615. r Show entries matching a regular expression (`/' can be used as well).
  12616. b Show deadlines and scheduled items before a date.
  12617. a Show deadlines and scheduled items after a date.
  12618. d Show deadlines due within `org-deadline-warning-days'.
  12619. D Show deadlines and scheduled items between a date range."
  12620. (interactive "P")
  12621. (setq type (or type org-sparse-tree-default-date-type))
  12622. (setq org-ts-type type)
  12623. (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12624. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12625. \[c]ycle through date types: %s"
  12626. (cl-case type
  12627. (all "all timestamps")
  12628. (scheduled "only scheduled")
  12629. (deadline "only deadline")
  12630. (active "only active timestamps")
  12631. (inactive "only inactive timestamps")
  12632. (closed "with a closed time-stamp")
  12633. (otherwise "scheduled/deadline")))
  12634. (let ((answer (read-char-exclusive)))
  12635. (cl-case answer
  12636. (?c
  12637. (org-sparse-tree
  12638. arg
  12639. (cadr
  12640. (memq type '(nil all scheduled deadline active inactive closed)))))
  12641. (?d (call-interactively 'org-check-deadlines))
  12642. (?b (call-interactively 'org-check-before-date))
  12643. (?a (call-interactively 'org-check-after-date))
  12644. (?D (call-interactively 'org-check-dates-range))
  12645. (?t (call-interactively 'org-show-todo-tree))
  12646. (?T (org-show-todo-tree '(4)))
  12647. (?m (call-interactively 'org-match-sparse-tree))
  12648. ((?p ?P)
  12649. (let* ((kwd (completing-read
  12650. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12651. (value (completing-read
  12652. "Value: " (mapcar #'list (org-property-values kwd)))))
  12653. (unless (string-match "\\`{.*}\\'" value)
  12654. (setq value (concat "\"" value "\"")))
  12655. (org-match-sparse-tree arg (concat kwd "=" value))))
  12656. ((?r ?R ?/) (call-interactively 'org-occur))
  12657. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12658. (defvar-local org-occur-highlights nil
  12659. "List of overlays used for occur matches.")
  12660. (defvar-local org-occur-parameters nil
  12661. "Parameters of the active org-occur calls.
  12662. This is a list, each call to org-occur pushes as cons cell,
  12663. containing the regular expression and the callback, onto the list.
  12664. The list can contain several entries if `org-occur' has been called
  12665. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12666. will only contain one set of parameters. When the highlights are
  12667. removed (for example with `C-c C-c', or with the next edit (depending
  12668. on `org-remove-highlights-with-change'), this variable is emptied
  12669. as well.")
  12670. (defun org-occur (regexp &optional keep-previous callback)
  12671. "Make a compact tree which shows all matches of REGEXP.
  12672. The tree will show the lines where the regexp matches, and any other context
  12673. defined in `org-show-context-detail', which see.
  12674. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12675. done by a previous call to `org-occur' will be kept, to allow stacking of
  12676. calls to this command.
  12677. Optional argument CALLBACK can be a function of no argument. In this case,
  12678. it is called with point at the end of the match, match data being set
  12679. accordingly. Current match is shown only if the return value is non-nil.
  12680. The function must neither move point nor alter narrowing."
  12681. (interactive "sRegexp: \nP")
  12682. (when (equal regexp "")
  12683. (user-error "Regexp cannot be empty"))
  12684. (unless keep-previous
  12685. (org-remove-occur-highlights nil nil t))
  12686. (push (cons regexp callback) org-occur-parameters)
  12687. (let ((cnt 0))
  12688. (save-excursion
  12689. (goto-char (point-min))
  12690. (when (or (not keep-previous) ; do not want to keep
  12691. (not org-occur-highlights)) ; no previous matches
  12692. ;; hide everything
  12693. (org-overview))
  12694. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12695. (isearch-no-upper-case-p regexp t)
  12696. org-occur-case-fold-search)))
  12697. (while (re-search-forward regexp nil t)
  12698. (when (or (not callback)
  12699. (save-match-data (funcall callback)))
  12700. (setq cnt (1+ cnt))
  12701. (when org-highlight-sparse-tree-matches
  12702. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12703. (org-show-context 'occur-tree)))))
  12704. (when org-remove-highlights-with-change
  12705. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12706. nil 'local))
  12707. (unless org-sparse-tree-open-archived-trees
  12708. (org-hide-archived-subtrees (point-min) (point-max)))
  12709. (run-hooks 'org-occur-hook)
  12710. (when (called-interactively-p 'interactive)
  12711. (message "%d match(es) for regexp %s" cnt regexp))
  12712. cnt))
  12713. (defun org-occur-next-match (&optional n _reset)
  12714. "Function for `next-error-function' to find sparse tree matches.
  12715. N is the number of matches to move, when negative move backwards.
  12716. This function always goes back to the starting point when no
  12717. match is found."
  12718. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12719. (search-func (if (< n 0)
  12720. 'previous-single-char-property-change
  12721. 'next-single-char-property-change))
  12722. (n (abs n))
  12723. (pos (point))
  12724. p1)
  12725. (catch 'exit
  12726. (while (setq p1 (funcall search-func (point) 'org-type))
  12727. (when (equal p1 limit)
  12728. (goto-char pos)
  12729. (user-error "No more matches"))
  12730. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12731. (setq n (1- n))
  12732. (when (= n 0)
  12733. (goto-char p1)
  12734. (throw 'exit (point))))
  12735. (goto-char p1))
  12736. (goto-char p1)
  12737. (user-error "No more matches"))))
  12738. (defun org-show-context (&optional key)
  12739. "Make sure point and context are visible.
  12740. Optional argument KEY, when non-nil, is a symbol. See
  12741. `org-show-context-detail' for allowed values and how much is to
  12742. be shown."
  12743. (org-show-set-visibility
  12744. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12745. ((cdr (assq key org-show-context-detail)))
  12746. (t (cdr (assq 'default org-show-context-detail))))))
  12747. (defun org-show-set-visibility (detail)
  12748. "Set visibility around point according to DETAIL.
  12749. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12750. `tree', `canonical' or t. See `org-show-context-detail' for more
  12751. information."
  12752. ;; Show current heading and possibly its entry, following headline
  12753. ;; or all children.
  12754. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12755. (org-flag-heading nil)
  12756. (org-show-entry)
  12757. ;; If point is hidden within a drawer or a block, make sure to
  12758. ;; expose it.
  12759. (dolist (o (overlays-at (point)))
  12760. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12761. (delete-overlay o)))
  12762. (unless (org-before-first-heading-p)
  12763. (org-with-limited-levels
  12764. (cl-case detail
  12765. ((tree canonical t) (org-show-children))
  12766. ((nil minimal ancestors))
  12767. (t (save-excursion
  12768. (outline-next-heading)
  12769. (org-flag-heading nil)))))))
  12770. ;; Show all siblings.
  12771. (when (eq detail 'lineage) (org-show-siblings))
  12772. ;; Show ancestors, possibly with their children.
  12773. (when (memq detail '(ancestors lineage tree canonical t))
  12774. (save-excursion
  12775. (while (org-up-heading-safe)
  12776. (org-flag-heading nil)
  12777. (when (memq detail '(canonical t)) (org-show-entry))
  12778. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12779. (defvar org-reveal-start-hook nil
  12780. "Hook run before revealing a location.")
  12781. (defun org-reveal (&optional siblings)
  12782. "Show current entry, hierarchy above it, and the following headline.
  12783. This can be used to show a consistent set of context around
  12784. locations exposed with `org-show-context'.
  12785. With optional argument SIBLINGS, on each level of the hierarchy all
  12786. siblings are shown. This repairs the tree structure to what it would
  12787. look like when opened with hierarchical calls to `org-cycle'.
  12788. With double optional argument \\[universal-argument] \\[universal-argument], \
  12789. go to the parent and show the
  12790. entire tree."
  12791. (interactive "P")
  12792. (run-hooks 'org-reveal-start-hook)
  12793. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12794. ((equal siblings '(16))
  12795. (save-excursion
  12796. (when (org-up-heading-safe)
  12797. (org-show-subtree)
  12798. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12799. (t (org-show-set-visibility 'lineage))))
  12800. (defun org-highlight-new-match (beg end)
  12801. "Highlight from BEG to END and mark the highlight is an occur headline."
  12802. (let ((ov (make-overlay beg end)))
  12803. (overlay-put ov 'face 'secondary-selection)
  12804. (overlay-put ov 'org-type 'org-occur)
  12805. (push ov org-occur-highlights)))
  12806. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12807. "Remove the occur highlights from the buffer.
  12808. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12809. from the `before-change-functions' in the current buffer."
  12810. (interactive)
  12811. (unless org-inhibit-highlight-removal
  12812. (mapc #'delete-overlay org-occur-highlights)
  12813. (setq org-occur-highlights nil)
  12814. (setq org-occur-parameters nil)
  12815. (unless noremove
  12816. (remove-hook 'before-change-functions
  12817. 'org-remove-occur-highlights 'local))))
  12818. ;;;; Priorities
  12819. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12820. "Regular expression matching the priority indicator.")
  12821. (defvar org-remove-priority-next-time nil)
  12822. (defun org-priority-up ()
  12823. "Increase the priority of the current item."
  12824. (interactive)
  12825. (org-priority 'up))
  12826. (defun org-priority-down ()
  12827. "Decrease the priority of the current item."
  12828. (interactive)
  12829. (org-priority 'down))
  12830. (defun org-priority (&optional action _show)
  12831. "Change the priority of an item.
  12832. ACTION can be `set', `up', `down', or a character."
  12833. (interactive "P")
  12834. (if (equal action '(4))
  12835. (org-show-priority)
  12836. (unless org-enable-priority-commands
  12837. (user-error "Priority commands are disabled"))
  12838. (setq action (or action 'set))
  12839. (let (current new news have remove)
  12840. (save-excursion
  12841. (org-back-to-heading t)
  12842. (when (looking-at org-priority-regexp)
  12843. (setq current (string-to-char (match-string 2))
  12844. have t))
  12845. (cond
  12846. ((eq action 'remove)
  12847. (setq remove t new ?\ ))
  12848. ((or (eq action 'set)
  12849. (integerp action))
  12850. (if (not (eq action 'set))
  12851. (setq new action)
  12852. (message "Priority %c-%c, SPC to remove: "
  12853. org-highest-priority org-lowest-priority)
  12854. (save-match-data
  12855. (setq new (read-char-exclusive))))
  12856. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12857. (= (upcase org-lowest-priority) org-lowest-priority))
  12858. (setq new (upcase new)))
  12859. (cond ((equal new ?\ ) (setq remove t))
  12860. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12861. (user-error "Priority must be between `%c' and `%c'"
  12862. org-highest-priority org-lowest-priority))))
  12863. ((eq action 'up)
  12864. (setq new (if have
  12865. (1- current) ; normal cycling
  12866. ;; last priority was empty
  12867. (if (eq last-command this-command)
  12868. org-lowest-priority ; wrap around empty to lowest
  12869. ;; default
  12870. (if org-priority-start-cycle-with-default
  12871. org-default-priority
  12872. (1- org-default-priority))))))
  12873. ((eq action 'down)
  12874. (setq new (if have
  12875. (1+ current) ; normal cycling
  12876. ;; last priority was empty
  12877. (if (eq last-command this-command)
  12878. org-highest-priority ; wrap around empty to highest
  12879. ;; default
  12880. (if org-priority-start-cycle-with-default
  12881. org-default-priority
  12882. (1+ org-default-priority))))))
  12883. (t (user-error "Invalid action")))
  12884. (when (or (< (upcase new) org-highest-priority)
  12885. (> (upcase new) org-lowest-priority))
  12886. (if (and (memq action '(up down))
  12887. (not have) (not (eq last-command this-command)))
  12888. ;; `new' is from default priority
  12889. (error
  12890. "The default can not be set, see `org-default-priority' why")
  12891. ;; normal cycling: `new' is beyond highest/lowest priority
  12892. ;; and is wrapped around to the empty priority
  12893. (setq remove t)))
  12894. (setq news (format "%c" new))
  12895. (if have
  12896. (if remove
  12897. (replace-match "" t t nil 1)
  12898. (replace-match news t t nil 2))
  12899. (if remove
  12900. (user-error "No priority cookie found in line")
  12901. (let ((case-fold-search nil))
  12902. (looking-at org-todo-line-regexp))
  12903. (if (match-end 2)
  12904. (progn
  12905. (goto-char (match-end 2))
  12906. (insert " [#" news "]"))
  12907. (goto-char (match-beginning 3))
  12908. (insert "[#" news "] "))))
  12909. (org-set-tags nil 'align))
  12910. (if remove
  12911. (message "Priority removed")
  12912. (message "Priority of current item set to %s" news)))))
  12913. (defun org-show-priority ()
  12914. "Show the priority of the current item.
  12915. This priority is composed of the main priority given with the [#A] cookies,
  12916. and by additional input from the age of a schedules or deadline entry."
  12917. (interactive)
  12918. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12919. (org-get-at-bol 'priority)
  12920. (save-excursion
  12921. (save-match-data
  12922. (beginning-of-line)
  12923. (and (looking-at org-heading-regexp)
  12924. (org-get-priority (match-string 0))))))))
  12925. (message "Priority is %d" (if pri pri -1000))))
  12926. (defun org-get-priority (s)
  12927. "Find priority cookie and return priority."
  12928. (save-match-data
  12929. (if (functionp org-get-priority-function)
  12930. (funcall org-get-priority-function)
  12931. (if (not (string-match org-priority-regexp s))
  12932. (* 1000 (- org-lowest-priority org-default-priority))
  12933. (* 1000 (- org-lowest-priority
  12934. (string-to-char (match-string 2 s))))))))
  12935. ;;;; Tags
  12936. (defvar org-agenda-archives-mode)
  12937. (defvar org-map-continue-from nil
  12938. "Position from where mapping should continue.
  12939. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12940. (defvar org-scanner-tags nil
  12941. "The current tag list while the tags scanner is running.")
  12942. (defvar org-trust-scanner-tags nil
  12943. "Should `org-get-tags-at' use the tags for the scanner.
  12944. This is for internal dynamical scoping only.
  12945. When this is non-nil, the function `org-get-tags-at' will return the value
  12946. of `org-scanner-tags' instead of building the list by itself. This
  12947. can lead to large speed-ups when the tags scanner is used in a file with
  12948. many entries, and when the list of tags is retrieved, for example to
  12949. obtain a list of properties. Building the tags list for each entry in such
  12950. a file becomes an N^2 operation - but with this variable set, it scales
  12951. as N.")
  12952. (defvar org--matcher-tags-todo-only nil)
  12953. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12954. "Scan headline tags with inheritance and produce output ACTION.
  12955. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12956. or `agenda' to produce an entry list for an agenda view. It can also be
  12957. a Lisp form or a function that should be called at each matched headline, in
  12958. this case the return value is a list of all return values from these calls.
  12959. MATCHER is a function accepting three arguments, returning
  12960. a non-nil value whenever a given set of tags qualifies a headline
  12961. for inclusion. See `org-make-tags-matcher' for more information.
  12962. As a special case, it can also be set to t (respectively nil) in
  12963. order to match all (respectively none) headline.
  12964. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12965. keyword are included in the output.
  12966. START-LEVEL can be a string with asterisks, reducing the scope to
  12967. headlines matching this string."
  12968. (require 'org-agenda)
  12969. (let* ((re (concat "^"
  12970. (if start-level
  12971. ;; Get the correct level to match
  12972. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12973. org-outline-regexp)
  12974. " *\\(\\<\\("
  12975. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12976. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12977. (props (list 'face 'default
  12978. 'done-face 'org-agenda-done
  12979. 'undone-face 'default
  12980. 'mouse-face 'highlight
  12981. 'org-not-done-regexp org-not-done-regexp
  12982. 'org-todo-regexp org-todo-regexp
  12983. 'org-complex-heading-regexp org-complex-heading-regexp
  12984. 'help-echo
  12985. (format "mouse-2 or RET jump to org file %s"
  12986. (abbreviate-file-name
  12987. (or (buffer-file-name (buffer-base-buffer))
  12988. (buffer-name (buffer-base-buffer)))))))
  12989. (org-map-continue-from nil)
  12990. lspos tags tags-list
  12991. (tags-alist (list (cons 0 org-file-tags)))
  12992. (llast 0) rtn rtn1 level category i txt
  12993. todo marker entry priority
  12994. ts-date ts-date-type ts-date-pair)
  12995. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12996. (setq action (list 'lambda nil action)))
  12997. (save-excursion
  12998. (goto-char (point-min))
  12999. (when (eq action 'sparse-tree)
  13000. (org-overview)
  13001. (org-remove-occur-highlights))
  13002. (while (let (case-fold-search)
  13003. (re-search-forward re nil t))
  13004. (setq org-map-continue-from nil)
  13005. (catch :skip
  13006. (setq todo
  13007. ;; TODO: is the 1-2 difference a bug?
  13008. (when (match-end 1) (match-string-no-properties 2))
  13009. tags (when (match-end 4) (match-string-no-properties 4)))
  13010. (goto-char (setq lspos (match-beginning 0)))
  13011. (setq level (org-reduced-level (org-outline-level))
  13012. category (org-get-category))
  13013. (when (eq action 'agenda)
  13014. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13015. ts-date (car ts-date-pair)
  13016. ts-date-type (cdr ts-date-pair)))
  13017. (setq i llast llast level)
  13018. ;; remove tag lists from same and sublevels
  13019. (while (>= i level)
  13020. (when (setq entry (assoc i tags-alist))
  13021. (setq tags-alist (delete entry tags-alist)))
  13022. (setq i (1- i)))
  13023. ;; add the next tags
  13024. (when tags
  13025. (setq tags (org-split-string tags ":")
  13026. tags-alist
  13027. (cons (cons level tags) tags-alist)))
  13028. ;; compile tags for current headline
  13029. (setq tags-list
  13030. (if org-use-tag-inheritance
  13031. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13032. tags)
  13033. org-scanner-tags tags-list)
  13034. (when org-use-tag-inheritance
  13035. (setcdr (car tags-alist)
  13036. (mapcar (lambda (x)
  13037. (setq x (copy-sequence x))
  13038. (org-add-prop-inherited x))
  13039. (cdar tags-alist))))
  13040. (when (and tags org-use-tag-inheritance
  13041. (or (not (eq t org-use-tag-inheritance))
  13042. org-tags-exclude-from-inheritance))
  13043. ;; Selective inheritance, remove uninherited ones.
  13044. (setcdr (car tags-alist)
  13045. (org-remove-uninherited-tags (cdar tags-alist))))
  13046. (when (and
  13047. ;; eval matcher only when the todo condition is OK
  13048. (and (or (not todo-only) (member todo org-not-done-keywords))
  13049. (if (functionp matcher)
  13050. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13051. (funcall matcher todo tags-list level))
  13052. matcher))
  13053. ;; Call the skipper, but return t if it does not
  13054. ;; skip, so that the `and' form continues evaluating.
  13055. (progn
  13056. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13057. t)
  13058. ;; Check if timestamps are deselecting this entry
  13059. (or (not todo-only)
  13060. (and (member todo org-not-done-keywords)
  13061. (or (not org-agenda-tags-todo-honor-ignore-options)
  13062. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13063. ;; select this headline
  13064. (cond
  13065. ((eq action 'sparse-tree)
  13066. (and org-highlight-sparse-tree-matches
  13067. (org-get-heading) (match-end 0)
  13068. (org-highlight-new-match
  13069. (match-beginning 1) (match-end 1)))
  13070. (org-show-context 'tags-tree))
  13071. ((eq action 'agenda)
  13072. (setq txt (org-agenda-format-item
  13073. ""
  13074. (concat
  13075. (if (eq org-tags-match-list-sublevels 'indented)
  13076. (make-string (1- level) ?.) "")
  13077. (org-get-heading))
  13078. (make-string level ?\s)
  13079. category
  13080. tags-list)
  13081. priority (org-get-priority txt))
  13082. (goto-char lspos)
  13083. (setq marker (org-agenda-new-marker))
  13084. (org-add-props txt props
  13085. 'org-marker marker 'org-hd-marker marker 'org-category category
  13086. 'todo-state todo
  13087. 'ts-date ts-date
  13088. 'priority priority
  13089. 'type (concat "tagsmatch" ts-date-type))
  13090. (push txt rtn))
  13091. ((functionp action)
  13092. (setq org-map-continue-from nil)
  13093. (save-excursion
  13094. (setq rtn1 (funcall action))
  13095. (push rtn1 rtn)))
  13096. (t (user-error "Invalid action")))
  13097. ;; if we are to skip sublevels, jump to end of subtree
  13098. (unless org-tags-match-list-sublevels
  13099. (org-end-of-subtree t)
  13100. (backward-char 1))))
  13101. ;; Get the correct position from where to continue
  13102. (if org-map-continue-from
  13103. (goto-char org-map-continue-from)
  13104. (and (= (point) lspos) (end-of-line 1)))))
  13105. (when (and (eq action 'sparse-tree)
  13106. (not org-sparse-tree-open-archived-trees))
  13107. (org-hide-archived-subtrees (point-min) (point-max)))
  13108. (nreverse rtn)))
  13109. (defun org-remove-uninherited-tags (tags)
  13110. "Remove all tags that are not inherited from the list TAGS."
  13111. (cond
  13112. ((eq org-use-tag-inheritance t)
  13113. (if org-tags-exclude-from-inheritance
  13114. (org-delete-all org-tags-exclude-from-inheritance tags)
  13115. tags))
  13116. ((not org-use-tag-inheritance) nil)
  13117. ((stringp org-use-tag-inheritance)
  13118. (delq nil (mapcar
  13119. (lambda (x)
  13120. (if (and (string-match org-use-tag-inheritance x)
  13121. (not (member x org-tags-exclude-from-inheritance)))
  13122. x nil))
  13123. tags)))
  13124. ((listp org-use-tag-inheritance)
  13125. (delq nil (mapcar
  13126. (lambda (x)
  13127. (if (member x org-use-tag-inheritance) x nil))
  13128. tags)))))
  13129. (defun org-match-sparse-tree (&optional todo-only match)
  13130. "Create a sparse tree according to tags string MATCH.
  13131. MATCH can contain positive and negative selection of tags, like
  13132. \"+WORK+URGENT-WITHBOSS\".
  13133. If optional argument TODO-ONLY is non-nil, only select lines that are
  13134. also TODO lines."
  13135. (interactive "P")
  13136. (org-agenda-prepare-buffers (list (current-buffer)))
  13137. (let ((org--matcher-tags-todo-only todo-only))
  13138. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13139. org--matcher-tags-todo-only)))
  13140. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13141. (defvar org-cached-props nil)
  13142. (defun org-cached-entry-get (pom property)
  13143. (if (or (eq t org-use-property-inheritance)
  13144. (and (stringp org-use-property-inheritance)
  13145. (let ((case-fold-search t))
  13146. (string-match-p org-use-property-inheritance property)))
  13147. (and (listp org-use-property-inheritance)
  13148. (member-ignore-case property org-use-property-inheritance)))
  13149. ;; Caching is not possible, check it directly.
  13150. (org-entry-get pom property 'inherit)
  13151. ;; Get all properties, so we can do complicated checks easily.
  13152. (cdr (assoc-string property
  13153. (or org-cached-props
  13154. (setq org-cached-props (org-entry-properties pom)))
  13155. t))))
  13156. (defun org-global-tags-completion-table (&optional files)
  13157. "Return the list of all tags in all agenda buffer/files.
  13158. Optional FILES argument is a list of files which can be used
  13159. instead of the agenda files."
  13160. (save-excursion
  13161. (org-uniquify
  13162. (delq nil
  13163. (apply #'append
  13164. (mapcar
  13165. (lambda (file)
  13166. (set-buffer (find-file-noselect file))
  13167. (mapcar (lambda (x)
  13168. (and (stringp (car-safe x))
  13169. (list (car-safe x))))
  13170. (or org-current-tag-alist (org-get-buffer-tags))))
  13171. (if (car-safe files) files
  13172. (org-agenda-files))))))))
  13173. (defun org-make-tags-matcher (match)
  13174. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13175. Returns a cons of the selection string MATCH and a function
  13176. implementing the matcher.
  13177. The matcher is to be called at an Org entry, with point on the
  13178. headline, and returns non-nil if the entry matches the selection
  13179. string MATCH. It must be called with three arguments: the TODO
  13180. keyword at the entry (or nil if none), the list of all tags at
  13181. the entry including inherited ones and the reduced level of the
  13182. headline. Additionally, the category of the entry, if any, must
  13183. be specified as the text property `org-category' on the headline.
  13184. This function sets the variable `org--matcher-tags-todo-only' to
  13185. a non-nil value if the matcher restricts matching to TODO
  13186. entries, otherwise it is not touched.
  13187. See also `org-scan-tags'."
  13188. (unless match
  13189. ;; Get a new match request, with completion against the global
  13190. ;; tags table and the local tags in current buffer.
  13191. (let ((org-last-tags-completion-table
  13192. (org-uniquify
  13193. (delq nil (append (org-get-buffer-tags)
  13194. (org-global-tags-completion-table))))))
  13195. (setq match
  13196. (completing-read
  13197. "Match: "
  13198. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13199. (let ((match0 match)
  13200. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13201. (start 0)
  13202. tagsmatch todomatch tagsmatcher todomatcher)
  13203. ;; Expand group tags.
  13204. (setq match (org-tags-expand match))
  13205. ;; Check if there is a TODO part of this match, which would be the
  13206. ;; part after a "/". To make sure that this slash is not part of
  13207. ;; a property value to be matched against, we also check that
  13208. ;; there is no / after that slash. First, find the last slash.
  13209. (let ((s 0))
  13210. (while (string-match "/+" match s)
  13211. (setq start (match-beginning 0))
  13212. (setq s (match-end 0))))
  13213. (if (and (string-match "/+" match start)
  13214. (not (string-match-p "\"" match start)))
  13215. ;; Match contains also a TODO-matching request.
  13216. (progn
  13217. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13218. (setq todomatch (substring match (match-end 0)))
  13219. (when (string-prefix-p "!" todomatch)
  13220. (setq org--matcher-tags-todo-only t)
  13221. (setq todomatch (substring todomatch 1)))
  13222. (when (string-match "\\`\\s-*\\'" todomatch)
  13223. (setq todomatch nil)))
  13224. ;; Only matching tags.
  13225. (setq tagsmatch match)
  13226. (setq todomatch nil))
  13227. ;; Make the tags matcher.
  13228. (when (org-string-nw-p tagsmatch)
  13229. (let ((orlist nil)
  13230. (orterms (org-split-string tagsmatch "|"))
  13231. term)
  13232. (while (setq term (pop orterms))
  13233. (while (and (equal (substring term -1) "\\") orterms)
  13234. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13235. (while (string-match re term)
  13236. (let* ((rest (substring term (match-end 0)))
  13237. (minus (and (match-end 1)
  13238. (equal (match-string 1 term) "-")))
  13239. (tag (save-match-data
  13240. (replace-regexp-in-string
  13241. "\\\\-" "-" (match-string 2 term))))
  13242. (regexp (eq (string-to-char tag) ?{))
  13243. (levelp (match-end 4))
  13244. (propp (match-end 5))
  13245. (mm
  13246. (cond
  13247. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13248. (levelp
  13249. `(,(org-op-to-function (match-string 3 term))
  13250. level
  13251. ,(string-to-number (match-string 4 term))))
  13252. (propp
  13253. (let* ((gv (pcase (upcase (match-string 5 term))
  13254. ("CATEGORY"
  13255. '(get-text-property (point) 'org-category))
  13256. ("TODO" 'todo)
  13257. (p `(org-cached-entry-get nil ,p))))
  13258. (pv (match-string 7 term))
  13259. (regexp (eq (string-to-char pv) ?{))
  13260. (strp (eq (string-to-char pv) ?\"))
  13261. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13262. (po (org-op-to-function (match-string 6 term)
  13263. (if timep 'time strp))))
  13264. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13265. (when timep (setq pv (org-matcher-time pv)))
  13266. (cond ((and regexp (eq po 'org<>))
  13267. `(not (string-match ,pv (or ,gv ""))))
  13268. (regexp `(string-match ,pv (or ,gv "")))
  13269. (strp `(,po (or ,gv "") ,pv))
  13270. (t
  13271. `(,po
  13272. (string-to-number (or ,gv ""))
  13273. ,(string-to-number pv))))))
  13274. (t `(member ,tag tags-list)))))
  13275. (push (if minus `(not ,mm) mm) tagsmatcher)
  13276. (setq term rest)))
  13277. (push `(and ,@tagsmatcher) orlist)
  13278. (setq tagsmatcher nil))
  13279. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13280. ;; Make the TODO matcher.
  13281. (when (org-string-nw-p todomatch)
  13282. (let ((orlist nil))
  13283. (dolist (term (org-split-string todomatch "|"))
  13284. (while (string-match re term)
  13285. (let* ((minus (and (match-end 1)
  13286. (equal (match-string 1 term) "-")))
  13287. (kwd (match-string 2 term))
  13288. (regexp (eq (string-to-char kwd) ?{))
  13289. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13290. `(equal todo ,kwd))))
  13291. (push (if minus `(not ,mm) mm) todomatcher))
  13292. (setq term (substring term (match-end 0))))
  13293. (push (if (> (length todomatcher) 1)
  13294. (cons 'and todomatcher)
  13295. (car todomatcher))
  13296. orlist)
  13297. (setq todomatcher nil))
  13298. (setq todomatcher (cons 'or orlist))))
  13299. ;; Return the string and function of the matcher. If no
  13300. ;; tags-specific or todo-specific matcher exists, match
  13301. ;; everything.
  13302. (let ((matcher (if (and tagsmatcher todomatcher)
  13303. `(and ,tagsmatcher ,todomatcher)
  13304. (or tagsmatcher todomatcher t))))
  13305. (when org--matcher-tags-todo-only
  13306. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13307. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13308. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13309. "Expand group tags in MATCH.
  13310. This replaces every group tag in MATCH with a regexp tag search.
  13311. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13312. will be replaced like this:
  13313. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13314. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13315. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13316. Replacing by a regexp preserves the structure of the match.
  13317. E.g., this expansion
  13318. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13319. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13320. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13321. A group tag in MATCH can contain regular expressions of its own.
  13322. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13323. will be replaced like this:
  13324. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13325. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13326. assumed to be a single group tag, and the function will return
  13327. the list of tags in this group.
  13328. When DOWNCASE is non-nil, expand downcased TAGS."
  13329. (if org-group-tags
  13330. (let* ((case-fold-search t)
  13331. (stable org-mode-syntax-table)
  13332. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13333. (taggroups (if downcased
  13334. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13335. taggroups)
  13336. taggroups))
  13337. (taggroups-keys (mapcar #'car taggroups))
  13338. (return-match (if downcased (downcase match) match))
  13339. (count 0)
  13340. (work-already-expanded tags-already-expanded)
  13341. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13342. ;; @ and _ are allowed as word-components in tags.
  13343. (modify-syntax-entry ?@ "w" stable)
  13344. (modify-syntax-entry ?_ "w" stable)
  13345. ;; Temporarily replace regexp-expressions in the match-expression.
  13346. (while (string-match "{.+?}" return-match)
  13347. (cl-incf count)
  13348. (push (match-string 0 return-match) regexps-in-match)
  13349. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13350. (while (and taggroups-keys
  13351. (with-syntax-table stable
  13352. (string-match
  13353. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13354. (regexp-opt taggroups-keys) "\\>\\)")
  13355. return-match)))
  13356. (let* ((dir (match-string 1 return-match))
  13357. (tag (match-string 2 return-match))
  13358. (tag (if downcased (downcase tag) tag)))
  13359. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13360. (member tag work-already-expanded))
  13361. (setq tags-in-group (assoc tag taggroups))
  13362. (push tag work-already-expanded)
  13363. ;; Recursively expand each tag in the group, if the tag hasn't
  13364. ;; already been expanded. Restore the match-data after all recursive calls.
  13365. (save-match-data
  13366. (let (tags-expanded)
  13367. (dolist (x (cdr tags-in-group))
  13368. (if (and (member x taggroups-keys)
  13369. (not (member x work-already-expanded)))
  13370. (setq tags-expanded
  13371. (delete-dups
  13372. (append
  13373. (org-tags-expand x t downcased
  13374. work-already-expanded)
  13375. tags-expanded)))
  13376. (setq tags-expanded
  13377. (append (list x) tags-expanded)))
  13378. (setq work-already-expanded
  13379. (delete-dups
  13380. (append tags-expanded
  13381. work-already-expanded))))
  13382. (setq tags-in-group
  13383. (delete-dups (cons (car tags-in-group)
  13384. tags-expanded)))))
  13385. ;; Filter tag-regexps from tags.
  13386. (setq regexp-in-group-escaped
  13387. (delq nil (mapcar (lambda (x)
  13388. (if (stringp x)
  13389. (and (equal "{" (substring x 0 1))
  13390. (equal "}" (substring x -1))
  13391. x)
  13392. x))
  13393. tags-in-group))
  13394. regexp-in-group
  13395. (mapcar (lambda (x)
  13396. (substring x 1 -1))
  13397. regexp-in-group-escaped)
  13398. tags-in-group
  13399. (delq nil (mapcar (lambda (x)
  13400. (if (stringp x)
  13401. (and (not (equal "{" (substring x 0 1)))
  13402. (not (equal "}" (substring x -1)))
  13403. x)
  13404. x))
  13405. tags-in-group)))
  13406. ;; If single-as-list, do no more in the while-loop.
  13407. (if (not single-as-list)
  13408. (progn
  13409. (when regexp-in-group
  13410. (setq regexp-in-group
  13411. (concat "\\|"
  13412. (mapconcat 'identity regexp-in-group
  13413. "\\|"))))
  13414. (setq tags-in-group
  13415. (concat dir
  13416. "{\\<"
  13417. (regexp-opt tags-in-group)
  13418. "\\>"
  13419. regexp-in-group
  13420. "}"))
  13421. (when (stringp tags-in-group)
  13422. (org-add-props tags-in-group '(grouptag t)))
  13423. (setq return-match
  13424. (replace-match tags-in-group t t return-match)))
  13425. (setq tags-in-group
  13426. (append regexp-in-group-escaped tags-in-group))))
  13427. (setq taggroups-keys (delete tag taggroups-keys))))
  13428. ;; Add the regular expressions back into the match-expression again.
  13429. (while regexps-in-match
  13430. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13431. (pop regexps-in-match)
  13432. return-match t t))
  13433. (cl-decf count))
  13434. (if single-as-list
  13435. (if tags-in-group tags-in-group (list return-match))
  13436. return-match))
  13437. (if single-as-list
  13438. (list (if downcased (downcase match) match))
  13439. match)))
  13440. (defun org-op-to-function (op &optional stringp)
  13441. "Turn an operator into the appropriate function."
  13442. (setq op
  13443. (cond
  13444. ((equal op "<" ) '(< string< org-time<))
  13445. ((equal op ">" ) '(> org-string> org-time>))
  13446. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13447. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13448. ((member op '("=" "==")) '(= string= org-time=))
  13449. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13450. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13451. (defun org<> (a b) (not (= a b)))
  13452. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13453. (defun org-string>= (a b) (not (string< a b)))
  13454. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13455. (defun org-string<> (a b) (not (string= a b)))
  13456. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13457. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13458. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13459. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13460. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13461. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13462. (defun org-2ft (s)
  13463. "Convert S to a floating point time.
  13464. If S is already a number, just return it. If it is a string, parse
  13465. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13466. (cond
  13467. ((numberp s) s)
  13468. ((stringp s)
  13469. (condition-case nil
  13470. (float-time (apply 'encode-time (org-parse-time-string s)))
  13471. (error 0.)))
  13472. (t 0.)))
  13473. (defun org-time-today ()
  13474. "Time in seconds today at 0:00.
  13475. Returns the float number of seconds since the beginning of the
  13476. epoch to the beginning of today (00:00)."
  13477. (float-time (apply 'encode-time
  13478. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13479. (defun org-matcher-time (s)
  13480. "Interpret a time comparison value."
  13481. (save-match-data
  13482. (cond
  13483. ((string= s "<now>") (float-time))
  13484. ((string= s "<today>") (org-time-today))
  13485. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13486. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13487. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13488. (+ (org-time-today)
  13489. (* (string-to-number (match-string 1 s))
  13490. (cdr (assoc (match-string 2 s)
  13491. '(("d" . 86400.0) ("w" . 604800.0)
  13492. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13493. (t (org-2ft s)))))
  13494. (defun org-match-any-p (re list)
  13495. "Does re match any element of list?"
  13496. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13497. (delq nil list))
  13498. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13499. (defvar org-tags-overlay (make-overlay 1 1))
  13500. (delete-overlay org-tags-overlay)
  13501. (defun org-get-local-tags-at (&optional pos)
  13502. "Get a list of tags defined in the current headline."
  13503. (org-get-tags-at pos 'local))
  13504. (defun org-get-local-tags ()
  13505. "Get a list of tags defined in the current headline."
  13506. (org-get-tags-at nil 'local))
  13507. (defun org-get-tags-at (&optional pos local)
  13508. "Get a list of all headline tags applicable at POS.
  13509. POS defaults to point. If tags are inherited, the list contains
  13510. the targets in the same sequence as the headlines appear, i.e.
  13511. the tags of the current headline come last.
  13512. When LOCAL is non-nil, only return tags from the current headline,
  13513. ignore inherited ones."
  13514. (interactive)
  13515. (if (and org-trust-scanner-tags
  13516. (or (not pos) (equal pos (point)))
  13517. (not local))
  13518. org-scanner-tags
  13519. (let (tags ltags lastpos parent)
  13520. (save-excursion
  13521. (save-restriction
  13522. (widen)
  13523. (goto-char (or pos (point)))
  13524. (save-match-data
  13525. (catch 'done
  13526. (condition-case nil
  13527. (progn
  13528. (org-back-to-heading t)
  13529. (while (not (equal lastpos (point)))
  13530. (setq lastpos (point))
  13531. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13532. (setq ltags (org-split-string
  13533. (match-string-no-properties 1) ":"))
  13534. (when parent
  13535. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13536. (setq tags (append
  13537. (if parent
  13538. (org-remove-uninherited-tags ltags)
  13539. ltags)
  13540. tags)))
  13541. (or org-use-tag-inheritance (throw 'done t))
  13542. (when local (throw 'done t))
  13543. (or (org-up-heading-safe) (error nil))
  13544. (setq parent t)))
  13545. (error nil)))))
  13546. (if local
  13547. tags
  13548. (reverse (delete-dups
  13549. (reverse (append
  13550. (org-remove-uninherited-tags
  13551. org-file-tags)
  13552. tags)))))))))
  13553. (defun org-add-prop-inherited (s)
  13554. (add-text-properties 0 (length s) '(inherited t) s)
  13555. s)
  13556. (defun org-toggle-tag (tag &optional onoff)
  13557. "Toggle the tag TAG for the current line.
  13558. If ONOFF is `on' or `off', don't toggle but set to this state."
  13559. (let (res current)
  13560. (save-excursion
  13561. (org-back-to-heading t)
  13562. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13563. (point-at-eol) t)
  13564. (progn
  13565. (setq current (match-string 1))
  13566. (replace-match ""))
  13567. (setq current ""))
  13568. (setq current (nreverse (org-split-string current ":")))
  13569. (cond
  13570. ((eq onoff 'on)
  13571. (setq res t)
  13572. (or (member tag current) (push tag current)))
  13573. ((eq onoff 'off)
  13574. (or (not (member tag current)) (setq current (delete tag current))))
  13575. (t (if (member tag current)
  13576. (setq current (delete tag current))
  13577. (setq res t)
  13578. (push tag current))))
  13579. (end-of-line 1)
  13580. (if current
  13581. (progn
  13582. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13583. (org-set-tags nil t))
  13584. (delete-horizontal-space))
  13585. (run-hooks 'org-after-tags-change-hook))
  13586. res))
  13587. (defun org-align-tags-here (to-col)
  13588. "Align tags on the current headline to TO-COL.
  13589. Assume point is on a headline."
  13590. (let ((pos (point)))
  13591. (beginning-of-line)
  13592. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13593. (>= pos (match-beginning 2)))
  13594. ;; No tags or point within tags: do not align.
  13595. (goto-char pos)
  13596. (goto-char (match-beginning 1))
  13597. (let ((shift (max (- (if (>= to-col 0) to-col
  13598. (- (abs to-col) (string-width (match-string 2))))
  13599. (current-column))
  13600. 1)))
  13601. (replace-match (make-string shift ?\s) nil nil nil 1)
  13602. ;; Preserve initial position, if possible. In any case, stop
  13603. ;; before tags.
  13604. (when (< pos (point)) (goto-char pos))))))
  13605. (defun org-set-tags-command (&optional arg just-align)
  13606. "Call the set-tags command for the current entry."
  13607. (interactive "P")
  13608. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13609. (org-set-tags arg just-align)
  13610. (save-excursion
  13611. (unless (and (org-region-active-p)
  13612. org-loop-over-headlines-in-active-region)
  13613. (org-back-to-heading t))
  13614. (org-set-tags arg just-align))))
  13615. (defun org-set-tags-to (data)
  13616. "Set the tags of the current entry to DATA, replacing the current tags.
  13617. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13618. If DATA is nil or the empty string, any tags will be removed."
  13619. (interactive "sTags: ")
  13620. (setq data
  13621. (cond
  13622. ((eq data nil) "")
  13623. ((equal data "") "")
  13624. ((stringp data)
  13625. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13626. ":"))
  13627. ((listp data)
  13628. (concat ":" (mapconcat 'identity data ":") ":"))))
  13629. (when data
  13630. (save-excursion
  13631. (org-back-to-heading t)
  13632. (when (looking-at org-complex-heading-regexp)
  13633. (if (match-end 5)
  13634. (progn
  13635. (goto-char (match-beginning 5))
  13636. (insert data)
  13637. (delete-region (point) (point-at-eol))
  13638. (org-set-tags nil 'align))
  13639. (goto-char (point-at-eol))
  13640. (insert " " data)
  13641. (org-set-tags nil 'align)))
  13642. (beginning-of-line 1)
  13643. (when (looking-at ".*?\\([ \t]+\\)$")
  13644. (delete-region (match-beginning 1) (match-end 1))))))
  13645. (defun org-align-all-tags ()
  13646. "Align the tags in all headings."
  13647. (interactive)
  13648. (save-excursion
  13649. (or (ignore-errors (org-back-to-heading t))
  13650. (outline-next-heading))
  13651. (if (org-at-heading-p)
  13652. (org-set-tags t)
  13653. (message "No headings"))))
  13654. (defvar org-indent-indentation-per-level)
  13655. (defun org-set-tags (&optional arg just-align)
  13656. "Set the tags for the current headline.
  13657. With prefix ARG, realign all tags in headings in the current buffer.
  13658. When JUST-ALIGN is non-nil, only align tags."
  13659. (interactive "P")
  13660. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13661. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13662. 'region-start-level
  13663. 'region))
  13664. org-loop-over-headlines-in-active-region)
  13665. (org-map-entries
  13666. ;; We don't use ARG and JUST-ALIGN here because these args
  13667. ;; are not useful when looping over headlines.
  13668. #'org-set-tags
  13669. org-loop-over-headlines-in-active-region
  13670. cl
  13671. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13672. (let ((org-setting-tags t))
  13673. (if arg
  13674. (save-excursion
  13675. (goto-char (point-min))
  13676. (while (re-search-forward org-outline-regexp-bol nil t)
  13677. (org-set-tags nil t)
  13678. (end-of-line))
  13679. (message "All tags realigned to column %d" org-tags-column))
  13680. (let* ((current (org-get-tags-string))
  13681. (col (current-column))
  13682. (tags
  13683. (if just-align current
  13684. ;; Get a new set of tags from the user.
  13685. (save-excursion
  13686. (let* ((seen)
  13687. (table
  13688. (setq
  13689. org-last-tags-completion-table
  13690. ;; Uniquify tags in alists, yet preserve
  13691. ;; structure (i.e., keywords).
  13692. (delq nil
  13693. (mapcar
  13694. (lambda (pair)
  13695. (let ((head (car pair)))
  13696. (cond ((symbolp head) pair)
  13697. ((member head seen) nil)
  13698. (t (push head seen)
  13699. pair))))
  13700. (append
  13701. (or org-current-tag-alist
  13702. (org-get-buffer-tags))
  13703. (and
  13704. org-complete-tags-always-offer-all-agenda-tags
  13705. (org-global-tags-completion-table
  13706. (org-agenda-files))))))))
  13707. (current-tags (org-split-string current ":"))
  13708. (inherited-tags
  13709. (nreverse (nthcdr (length current-tags)
  13710. (nreverse (org-get-tags-at))))))
  13711. (replace-regexp-in-string
  13712. "\\([-+&]+\\|,\\)"
  13713. ":"
  13714. (if (or (eq t org-use-fast-tag-selection)
  13715. (and org-use-fast-tag-selection
  13716. (delq nil (mapcar #'cdr table))))
  13717. (org-fast-tag-selection
  13718. current-tags inherited-tags table
  13719. (and org-fast-tag-selection-include-todo
  13720. org-todo-key-alist))
  13721. (let ((org-add-colon-after-tag-completion
  13722. (< 1 (length table))))
  13723. (org-trim
  13724. (completing-read
  13725. "Tags: "
  13726. #'org-tags-completion-function
  13727. nil nil current 'org-tags-history))))))))))
  13728. (when org-tags-sort-function
  13729. (setq tags
  13730. (mapconcat
  13731. #'identity
  13732. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13733. org-tags-sort-function)
  13734. ":")))
  13735. (if (not (org-string-nw-p tags)) (setq tags "")
  13736. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13737. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13738. ;; Insert new tags at the correct column
  13739. (beginning-of-line)
  13740. (let ((level (if (looking-at org-outline-regexp)
  13741. (- (match-end 0) (point) 1)
  13742. 1)))
  13743. (cond
  13744. ((and (equal current "") (equal tags "")))
  13745. ((re-search-forward
  13746. (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
  13747. (line-end-position)
  13748. t)
  13749. (if (equal tags "") (replace-match "" t t)
  13750. (goto-char (match-beginning 0))
  13751. (let* ((c0 (current-column))
  13752. ;; Compute offset for the case of org-indent-mode
  13753. ;; active.
  13754. (di (if (bound-and-true-p org-indent-mode)
  13755. (* (1- org-indent-indentation-per-level)
  13756. (1- level))
  13757. 0))
  13758. (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
  13759. (tc (+ org-tags-column
  13760. (if (> org-tags-column 0) (- di) di)))
  13761. (c1 (max (1+ c0)
  13762. (if (> tc 0) tc
  13763. (- (- tc) (string-width tags)))))
  13764. (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
  13765. (replace-match rpl t t)
  13766. (when indent-tabs-mode (tabify p0 (point))))))
  13767. (t (error "Tags alignment failed"))))
  13768. (org-move-to-column col))
  13769. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13770. (defun org-change-tag-in-region (beg end tag off)
  13771. "Add or remove TAG for each entry in the region.
  13772. This works in the agenda, and also in an Org buffer."
  13773. (interactive
  13774. (list (region-beginning) (region-end)
  13775. (let ((org-last-tags-completion-table
  13776. (if (derived-mode-p 'org-mode)
  13777. (org-uniquify
  13778. (delq nil (append (org-get-buffer-tags)
  13779. (org-global-tags-completion-table))))
  13780. (org-global-tags-completion-table))))
  13781. (completing-read
  13782. "Tag: " 'org-tags-completion-function nil nil nil
  13783. 'org-tags-history))
  13784. (progn
  13785. (message "[s]et or [r]emove? ")
  13786. (equal (read-char-exclusive) ?r))))
  13787. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13788. (let ((agendap (equal major-mode 'org-agenda-mode))
  13789. l1 l2 m buf pos newhead (cnt 0))
  13790. (goto-char end)
  13791. (setq l2 (1- (org-current-line)))
  13792. (goto-char beg)
  13793. (setq l1 (org-current-line))
  13794. (cl-loop for l from l1 to l2 do
  13795. (org-goto-line l)
  13796. (setq m (get-text-property (point) 'org-hd-marker))
  13797. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13798. (and agendap m))
  13799. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13800. pos (if agendap m (point)))
  13801. (with-current-buffer buf
  13802. (save-excursion
  13803. (save-restriction
  13804. (goto-char pos)
  13805. (setq cnt (1+ cnt))
  13806. (org-toggle-tag tag (if off 'off 'on))
  13807. (setq newhead (org-get-heading)))))
  13808. (and agendap (org-agenda-change-all-lines newhead m))))
  13809. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13810. (defun org-tags-completion-function (string _predicate &optional flag)
  13811. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13812. (confirm (lambda (x) (stringp (car x)))))
  13813. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13814. (setq s1 (match-string 1 string)
  13815. s2 (match-string 2 string))
  13816. (setq s1 "" s2 string))
  13817. (cond
  13818. ((eq flag nil)
  13819. ;; try completion
  13820. (setq rtn (try-completion s2 ctable confirm))
  13821. (when (stringp rtn)
  13822. (setq rtn
  13823. (concat s1 s2 (substring rtn (length s2))
  13824. (if (and org-add-colon-after-tag-completion
  13825. (assoc rtn ctable))
  13826. ":" ""))))
  13827. rtn)
  13828. ((eq flag t)
  13829. ;; all-completions
  13830. (all-completions s2 ctable confirm))
  13831. ((eq flag 'lambda)
  13832. ;; exact match?
  13833. (assoc s2 ctable)))))
  13834. (defun org-fast-tag-insert (kwd tags face &optional end)
  13835. "Insert KDW, and the TAGS, the latter with face FACE.
  13836. Also insert END."
  13837. (insert (format "%-12s" (concat kwd ":"))
  13838. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13839. (or end "")))
  13840. (defun org-fast-tag-show-exit (flag)
  13841. (save-excursion
  13842. (org-goto-line 3)
  13843. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13844. (replace-match ""))
  13845. (when flag
  13846. (end-of-line 1)
  13847. (org-move-to-column (- (window-width) 19) t)
  13848. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13849. (defun org-set-current-tags-overlay (current prefix)
  13850. "Add an overlay to CURRENT tag with PREFIX."
  13851. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13852. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13853. (org-overlay-display org-tags-overlay (concat prefix s))))
  13854. (defvar org-last-tag-selection-key nil)
  13855. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13856. "Fast tag selection with single keys.
  13857. CURRENT is the current list of tags in the headline, INHERITED is the
  13858. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13859. possibly with grouping information. TODO-TABLE is a similar table with
  13860. TODO keywords, should these have keys assigned to them.
  13861. If the keys are nil, a-z are automatically assigned.
  13862. Returns the new tags string, or nil to not change the current settings."
  13863. (let* ((fulltable (append table todo-table))
  13864. (maxlen (apply 'max (mapcar
  13865. (lambda (x)
  13866. (if (stringp (car x)) (string-width (car x)) 0))
  13867. fulltable)))
  13868. (buf (current-buffer))
  13869. (expert (eq org-fast-tag-selection-single-key 'expert))
  13870. (buffer-tags nil)
  13871. (fwidth (+ maxlen 3 1 3))
  13872. (ncol (/ (- (window-width) 4) fwidth))
  13873. (i-face 'org-done)
  13874. (c-face 'org-todo)
  13875. tg cnt e c char c1 c2 ntable tbl rtn
  13876. ov-start ov-end ov-prefix
  13877. (exit-after-next org-fast-tag-selection-single-key)
  13878. (done-keywords org-done-keywords)
  13879. groups ingroup intaggroup)
  13880. (save-excursion
  13881. (beginning-of-line 1)
  13882. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13883. (setq ov-start (match-beginning 1)
  13884. ov-end (match-end 1)
  13885. ov-prefix "")
  13886. (setq ov-start (1- (point-at-eol))
  13887. ov-end (1+ ov-start))
  13888. (skip-chars-forward "^\n\r")
  13889. (setq ov-prefix
  13890. (concat
  13891. (buffer-substring (1- (point)) (point))
  13892. (if (> (current-column) org-tags-column)
  13893. " "
  13894. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13895. (move-overlay org-tags-overlay ov-start ov-end)
  13896. (save-window-excursion
  13897. (if expert
  13898. (set-buffer (get-buffer-create " *Org tags*"))
  13899. (delete-other-windows)
  13900. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13901. (org-switch-to-buffer-other-window " *Org tags*"))
  13902. (erase-buffer)
  13903. (setq-local org-done-keywords done-keywords)
  13904. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13905. (org-fast-tag-insert "Current" current c-face "\n\n")
  13906. (org-fast-tag-show-exit exit-after-next)
  13907. (org-set-current-tags-overlay current ov-prefix)
  13908. (setq tbl fulltable char ?a cnt 0)
  13909. (while (setq e (pop tbl))
  13910. (cond
  13911. ((eq (car e) :startgroup)
  13912. (push '() groups) (setq ingroup t)
  13913. (unless (zerop cnt)
  13914. (setq cnt 0)
  13915. (insert "\n"))
  13916. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13917. ((eq (car e) :endgroup)
  13918. (setq ingroup nil cnt 0)
  13919. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13920. ((eq (car e) :startgrouptag)
  13921. (setq intaggroup t)
  13922. (unless (zerop cnt)
  13923. (setq cnt 0)
  13924. (insert "\n"))
  13925. (insert "[ "))
  13926. ((eq (car e) :endgrouptag)
  13927. (setq intaggroup nil cnt 0)
  13928. (insert "]\n"))
  13929. ((equal e '(:newline))
  13930. (unless (zerop cnt)
  13931. (setq cnt 0)
  13932. (insert "\n")
  13933. (setq e (car tbl))
  13934. (while (equal (car tbl) '(:newline))
  13935. (insert "\n")
  13936. (setq tbl (cdr tbl)))))
  13937. ((equal e '(:grouptags)) (insert " : "))
  13938. (t
  13939. (setq tg (copy-sequence (car e)) c2 nil)
  13940. (if (cdr e)
  13941. (setq c (cdr e))
  13942. ;; automatically assign a character.
  13943. (setq c1 (string-to-char
  13944. (downcase (substring
  13945. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13946. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13947. (while (or (rassoc char ntable) (rassoc char table))
  13948. (setq char (1+ char)))
  13949. (setq c2 c1))
  13950. (setq c (or c2 char)))
  13951. (when ingroup (push tg (car groups)))
  13952. (setq tg (org-add-props tg nil 'face
  13953. (cond
  13954. ((not (assoc tg table))
  13955. (org-get-todo-face tg))
  13956. ((member tg current) c-face)
  13957. ((member tg inherited) i-face))))
  13958. (when (equal (caar tbl) :grouptags)
  13959. (org-add-props tg nil 'face 'org-tag-group))
  13960. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13961. (insert "[" c "] " tg (make-string
  13962. (- fwidth 4 (length tg)) ?\ ))
  13963. (push (cons tg c) ntable)
  13964. (when (= (cl-incf cnt) ncol)
  13965. (insert "\n")
  13966. (when (or ingroup intaggroup) (insert " "))
  13967. (setq cnt 0)))))
  13968. (setq ntable (nreverse ntable))
  13969. (insert "\n")
  13970. (goto-char (point-min))
  13971. (unless expert (org-fit-window-to-buffer))
  13972. (setq rtn
  13973. (catch 'exit
  13974. (while t
  13975. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13976. (if (not groups) "no " "")
  13977. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13978. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13979. (setq org-last-tag-selection-key c)
  13980. (cond
  13981. ((= c ?\r) (throw 'exit t))
  13982. ((= c ?!)
  13983. (setq groups (not groups))
  13984. (goto-char (point-min))
  13985. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13986. ((= c ?\C-c)
  13987. (if (not expert)
  13988. (org-fast-tag-show-exit
  13989. (setq exit-after-next (not exit-after-next)))
  13990. (setq expert nil)
  13991. (delete-other-windows)
  13992. (set-window-buffer (split-window-vertically) " *Org tags*")
  13993. (org-switch-to-buffer-other-window " *Org tags*")
  13994. (org-fit-window-to-buffer)))
  13995. ((or (= c ?\C-g)
  13996. (and (= c ?q) (not (rassoc c ntable))))
  13997. (delete-overlay org-tags-overlay)
  13998. (setq quit-flag t))
  13999. ((= c ?\ )
  14000. (setq current nil)
  14001. (when exit-after-next (setq exit-after-next 'now)))
  14002. ((= c ?\t)
  14003. (condition-case nil
  14004. (setq tg (completing-read
  14005. "Tag: "
  14006. (or buffer-tags
  14007. (with-current-buffer buf
  14008. (setq buffer-tags
  14009. (org-get-buffer-tags))))))
  14010. (quit (setq tg "")))
  14011. (when (string-match "\\S-" tg)
  14012. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14013. (if (member tg current)
  14014. (setq current (delete tg current))
  14015. (push tg current)))
  14016. (when exit-after-next (setq exit-after-next 'now)))
  14017. ((setq e (rassoc c todo-table) tg (car e))
  14018. (with-current-buffer buf
  14019. (save-excursion (org-todo tg)))
  14020. (when exit-after-next (setq exit-after-next 'now)))
  14021. ((setq e (rassoc c ntable) tg (car e))
  14022. (if (member tg current)
  14023. (setq current (delete tg current))
  14024. (cl-loop for g in groups do
  14025. (when (member tg g)
  14026. (dolist (x g) (setq current (delete x current)))))
  14027. (push tg current))
  14028. (when exit-after-next (setq exit-after-next 'now))))
  14029. ;; Create a sorted list
  14030. (setq current
  14031. (sort current
  14032. (lambda (a b)
  14033. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14034. (when (eq exit-after-next 'now) (throw 'exit t))
  14035. (goto-char (point-min))
  14036. (beginning-of-line 2)
  14037. (delete-region (point) (point-at-eol))
  14038. (org-fast-tag-insert "Current" current c-face)
  14039. (org-set-current-tags-overlay current ov-prefix)
  14040. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14041. (setq tg (match-string 1))
  14042. (add-text-properties
  14043. (match-beginning 1) (match-end 1)
  14044. (list 'face
  14045. (cond
  14046. ((member tg current) c-face)
  14047. ((member tg inherited) i-face)
  14048. (t (get-text-property (match-beginning 1) 'face))))))
  14049. (goto-char (point-min)))))
  14050. (delete-overlay org-tags-overlay)
  14051. (if rtn
  14052. (mapconcat 'identity current ":")
  14053. nil))))
  14054. (defun org-get-tags-string ()
  14055. "Get the TAGS string in the current headline."
  14056. (unless (org-at-heading-p t)
  14057. (user-error "Not on a heading"))
  14058. (save-excursion
  14059. (beginning-of-line 1)
  14060. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14061. (match-string-no-properties 1)
  14062. "")))
  14063. (defun org-get-tags ()
  14064. "Get the list of tags specified in the current headline."
  14065. (org-split-string (org-get-tags-string) ":"))
  14066. (defun org-get-buffer-tags ()
  14067. "Get a table of all tags used in the buffer, for completion."
  14068. (org-with-wide-buffer
  14069. (goto-char (point-min))
  14070. (let ((tag-re (concat org-outline-regexp-bol
  14071. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14072. tags)
  14073. (while (re-search-forward tag-re nil t)
  14074. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14075. (push tag tags)))
  14076. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14077. ;;;; The mapping API
  14078. (defvar org-agenda-skip-comment-trees)
  14079. (defvar org-agenda-skip-function)
  14080. (defun org-map-entries (func &optional match scope &rest skip)
  14081. "Call FUNC at each headline selected by MATCH in SCOPE.
  14082. FUNC is a function or a lisp form. The function will be called without
  14083. arguments, with the cursor positioned at the beginning of the headline.
  14084. The return values of all calls to the function will be collected and
  14085. returned as a list.
  14086. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14087. does not need to preserve point. After evaluation, the cursor will be
  14088. moved to the end of the line (presumably of the headline of the
  14089. processed entry) and search continues from there. Under some
  14090. circumstances, this may not produce the wanted results. For example,
  14091. if you have removed (e.g. archived) the current (sub)tree it could
  14092. mean that the next entry will be skipped entirely. In such cases, you
  14093. can specify the position from where search should continue by making
  14094. FUNC set the variable `org-map-continue-from' to the desired buffer
  14095. position.
  14096. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14097. Only headlines that are matched by this query will be considered during
  14098. the iteration. When MATCH is nil or t, all headlines will be
  14099. visited by the iteration.
  14100. SCOPE determines the scope of this command. It can be any of:
  14101. nil The current buffer, respecting the restriction if any
  14102. tree The subtree started with the entry at point
  14103. region The entries within the active region, if any
  14104. region-start-level
  14105. The entries within the active region, but only those at
  14106. the same level than the first one.
  14107. file The current buffer, without restriction
  14108. file-with-archives
  14109. The current buffer, and any archives associated with it
  14110. agenda All agenda files
  14111. agenda-with-archives
  14112. All agenda files with any archive files associated with them
  14113. \(file1 file2 ...)
  14114. If this is a list, all files in the list will be scanned
  14115. The remaining args are treated as settings for the skipping facilities of
  14116. the scanner. The following items can be given here:
  14117. archive skip trees with the archive tag
  14118. comment skip trees with the COMMENT keyword
  14119. function or Emacs Lisp form:
  14120. will be used as value for `org-agenda-skip-function', so
  14121. whenever the function returns a position, FUNC will not be
  14122. called for that entry and search will continue from the
  14123. position returned
  14124. If your function needs to retrieve the tags including inherited tags
  14125. at the *current* entry, you can use the value of the variable
  14126. `org-scanner-tags' which will be much faster than getting the value
  14127. with `org-get-tags-at'. If your function gets properties with
  14128. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14129. to t around the call to `org-entry-properties' to get the same speedup.
  14130. Note that if your function moves around to retrieve tags and properties at
  14131. a *different* entry, you cannot use these techniques."
  14132. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14133. (not (org-region-active-p)))
  14134. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14135. (org-agenda-skip-archived-trees (memq 'archive skip))
  14136. (org-agenda-skip-comment-trees (memq 'comment skip))
  14137. (org-agenda-skip-function
  14138. (car (org-delete-all '(comment archive) skip)))
  14139. (org-tags-match-list-sublevels t)
  14140. (start-level (eq scope 'region-start-level))
  14141. matcher res
  14142. org-todo-keywords-for-agenda
  14143. org-done-keywords-for-agenda
  14144. org-todo-keyword-alist-for-agenda
  14145. org-tag-alist-for-agenda
  14146. org--matcher-tags-todo-only)
  14147. (cond
  14148. ((eq match t) (setq matcher t))
  14149. ((eq match nil) (setq matcher t))
  14150. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14151. (save-excursion
  14152. (save-restriction
  14153. (cond ((eq scope 'tree)
  14154. (org-back-to-heading t)
  14155. (org-narrow-to-subtree)
  14156. (setq scope nil))
  14157. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14158. (org-region-active-p))
  14159. ;; If needed, set start-level to a string like "2"
  14160. (when start-level
  14161. (save-excursion
  14162. (goto-char (region-beginning))
  14163. (unless (org-at-heading-p) (outline-next-heading))
  14164. (setq start-level (org-current-level))))
  14165. (narrow-to-region (region-beginning)
  14166. (save-excursion
  14167. (goto-char (region-end))
  14168. (unless (and (bolp) (org-at-heading-p))
  14169. (outline-next-heading))
  14170. (point)))
  14171. (setq scope nil)))
  14172. (if (not scope)
  14173. (progn
  14174. (org-agenda-prepare-buffers
  14175. (and buffer-file-name (list buffer-file-name)))
  14176. (setq res
  14177. (org-scan-tags
  14178. func matcher org--matcher-tags-todo-only start-level)))
  14179. ;; Get the right scope
  14180. (cond
  14181. ((and scope (listp scope) (symbolp (car scope)))
  14182. (setq scope (eval scope)))
  14183. ((eq scope 'agenda)
  14184. (setq scope (org-agenda-files t)))
  14185. ((eq scope 'agenda-with-archives)
  14186. (setq scope (org-agenda-files t))
  14187. (setq scope (org-add-archive-files scope)))
  14188. ((eq scope 'file)
  14189. (setq scope (and buffer-file-name (list buffer-file-name))))
  14190. ((eq scope 'file-with-archives)
  14191. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14192. (org-agenda-prepare-buffers scope)
  14193. (dolist (file scope)
  14194. (with-current-buffer (org-find-base-buffer-visiting file)
  14195. (org-with-wide-buffer
  14196. (goto-char (point-min))
  14197. (setq res
  14198. (append
  14199. res
  14200. (org-scan-tags
  14201. func matcher org--matcher-tags-todo-only)))))))))
  14202. res)))
  14203. ;;; Properties API
  14204. (defconst org-special-properties
  14205. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14206. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14207. "The special properties valid in Org mode.
  14208. These are properties that are not defined in the property drawer,
  14209. but in some other way.")
  14210. (defconst org-default-properties
  14211. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14212. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14213. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14214. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14215. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14216. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14217. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14218. "Some properties that are used by Org mode for various purposes.
  14219. Being in this list makes sure that they are offered for completion.")
  14220. (defun org--valid-property-p (property)
  14221. "Non nil when string PROPERTY is a valid property name."
  14222. (not
  14223. (or (equal property "")
  14224. (string-match-p "\\s-" property))))
  14225. (defun org--update-property-plist (key val props)
  14226. "Associate KEY to VAL in alist PROPS.
  14227. Modifications are made by side-effect. Return new alist."
  14228. (let* ((appending (string= (substring key -1) "+"))
  14229. (key (if appending (substring key 0 -1) key))
  14230. (old (assoc-string key props t)))
  14231. (if (not old) (cons (cons key val) props)
  14232. (setcdr old (if appending (concat (cdr old) " " val) val))
  14233. props)))
  14234. (defun org-get-property-block (&optional beg force)
  14235. "Return the (beg . end) range of the body of the property drawer.
  14236. BEG is the beginning of the current subtree, or of the part
  14237. before the first headline. If it is not given, it will be found.
  14238. If the drawer does not exist, create it if FORCE is non-nil, or
  14239. return nil."
  14240. (org-with-wide-buffer
  14241. (when beg (goto-char beg))
  14242. (unless (org-before-first-heading-p)
  14243. (let ((beg (cond (beg)
  14244. ((or (not (featurep 'org-inlinetask))
  14245. (org-inlinetask-in-task-p))
  14246. (org-back-to-heading t))
  14247. (t (org-with-limited-levels (org-back-to-heading t))))))
  14248. (forward-line)
  14249. (when (looking-at-p org-planning-line-re) (forward-line))
  14250. (cond ((looking-at org-property-drawer-re)
  14251. (forward-line)
  14252. (cons (point) (progn (goto-char (match-end 0))
  14253. (line-beginning-position))))
  14254. (force
  14255. (goto-char beg)
  14256. (org-insert-property-drawer)
  14257. (let ((pos (save-excursion (search-forward ":END:")
  14258. (line-beginning-position))))
  14259. (cons pos pos))))))))
  14260. (defun org-at-property-p ()
  14261. "Non-nil when point is inside a property drawer.
  14262. See `org-property-re' for match data, if applicable."
  14263. (save-excursion
  14264. (beginning-of-line)
  14265. (and (looking-at org-property-re)
  14266. (let ((property-drawer (save-match-data (org-get-property-block))))
  14267. (and property-drawer
  14268. (>= (point) (car property-drawer))
  14269. (< (point) (cdr property-drawer)))))))
  14270. (defun org-property-action ()
  14271. "Do an action on properties."
  14272. (interactive)
  14273. (unless (org-at-property-p) (user-error "Not at a property"))
  14274. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14275. (let ((c (read-char-exclusive)))
  14276. (cl-case c
  14277. (?s (call-interactively #'org-set-property))
  14278. (?d (call-interactively #'org-delete-property))
  14279. (?D (call-interactively #'org-delete-property-globally))
  14280. (?c (call-interactively #'org-compute-property-at-point))
  14281. (otherwise (user-error "No such property action %c" c)))))
  14282. (defun org-inc-effort ()
  14283. "Increment the value of the effort property in the current entry."
  14284. (interactive)
  14285. (org-set-effort nil t))
  14286. (defvar org-clock-effort) ; Defined in org-clock.el.
  14287. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14288. (defun org-set-effort (&optional value increment)
  14289. "Set the effort property of the current entry.
  14290. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14291. 10th allowed value.
  14292. When INCREMENT is non-nil, set the property to the next allowed value."
  14293. (interactive "P")
  14294. (when (equal value 0) (setq value 10))
  14295. (let* ((completion-ignore-case t)
  14296. (prop org-effort-property)
  14297. (cur (org-entry-get nil prop))
  14298. (allowed (org-property-get-allowed-values nil prop 'table))
  14299. (existing (mapcar 'list (org-property-values prop)))
  14300. (heading (nth 4 (org-heading-components)))
  14301. rpl
  14302. (val (cond
  14303. ((stringp value) value)
  14304. ((and allowed (integerp value))
  14305. (or (car (nth (1- value) allowed))
  14306. (car (org-last allowed))))
  14307. ((and allowed increment)
  14308. (or (cl-caadr (member (list cur) allowed))
  14309. (user-error "Allowed effort values are not set")))
  14310. (allowed
  14311. (message "Select 1-9,0, [RET%s]: %s"
  14312. (if cur (concat "=" cur) "")
  14313. (mapconcat 'car allowed " "))
  14314. (setq rpl (read-char-exclusive))
  14315. (if (equal rpl ?\r)
  14316. cur
  14317. (setq rpl (- rpl ?0))
  14318. (when (equal rpl 0) (setq rpl 10))
  14319. (if (and (> rpl 0) (<= rpl (length allowed)))
  14320. (car (nth (1- rpl) allowed))
  14321. (org-completing-read "Effort: " allowed nil))))
  14322. (t
  14323. (org-completing-read
  14324. (concat "Effort" (and cur (string-match "\\S-" cur)
  14325. (concat " [" cur "]"))
  14326. ": ")
  14327. existing nil nil "" nil cur)))))
  14328. (unless (equal (org-entry-get nil prop) val)
  14329. (org-entry-put nil prop val))
  14330. (org-refresh-property
  14331. '((effort . identity)
  14332. (effort-minutes . org-duration-string-to-minutes))
  14333. val)
  14334. (when (equal heading (bound-and-true-p org-clock-current-task))
  14335. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14336. (org-clock-update-mode-line))
  14337. (message "%s is now %s" prop val)))
  14338. (defun org-entry-properties (&optional pom which)
  14339. "Get all properties of the current entry.
  14340. When POM is a buffer position, get all properties from the entry
  14341. there instead.
  14342. This includes the TODO keyword, the tags, time strings for
  14343. deadline, scheduled, and clocking, and any additional properties
  14344. defined in the entry.
  14345. If WHICH is nil or `all', get all properties. If WHICH is
  14346. `special' or `standard', only get that subclass. If WHICH is
  14347. a string, only get that property.
  14348. Return value is an alist. Keys are properties, as upcased
  14349. strings."
  14350. (org-with-point-at pom
  14351. (when (and (derived-mode-p 'org-mode)
  14352. (ignore-errors (org-back-to-heading t)))
  14353. (catch 'exit
  14354. (let* ((beg (point))
  14355. (specific (and (stringp which) (upcase which)))
  14356. (which (cond ((not specific) which)
  14357. ((member specific org-special-properties) 'special)
  14358. (t 'standard)))
  14359. props)
  14360. ;; Get the special properties, like TODO and TAGS.
  14361. (when (memq which '(nil all special))
  14362. (when (or (not specific) (string= specific "CLOCKSUM"))
  14363. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14364. (when clocksum
  14365. (push (cons "CLOCKSUM"
  14366. (org-minutes-to-clocksum-string clocksum))
  14367. props)))
  14368. (when specific (throw 'exit props)))
  14369. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14370. (let ((clocksumt (get-text-property (point)
  14371. :org-clock-minutes-today)))
  14372. (when clocksumt
  14373. (push (cons "CLOCKSUM_T"
  14374. (org-minutes-to-clocksum-string clocksumt))
  14375. props)))
  14376. (when specific (throw 'exit props)))
  14377. (when (or (not specific) (string= specific "ITEM"))
  14378. (when (looking-at org-complex-heading-regexp)
  14379. (push (cons "ITEM"
  14380. (let ((title (match-string-no-properties 4)))
  14381. (if (org-string-nw-p title)
  14382. (org-remove-tabs title)
  14383. "")))
  14384. props))
  14385. (when specific (throw 'exit props)))
  14386. (when (or (not specific) (string= specific "TODO"))
  14387. (let ((case-fold-search nil))
  14388. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14389. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14390. (when specific (throw 'exit props)))
  14391. (when (or (not specific) (string= specific "PRIORITY"))
  14392. (push (cons "PRIORITY"
  14393. (if (looking-at org-priority-regexp)
  14394. (match-string-no-properties 2)
  14395. (char-to-string org-default-priority)))
  14396. props)
  14397. (when specific (throw 'exit props)))
  14398. (when (or (not specific) (string= specific "FILE"))
  14399. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14400. props)
  14401. (when specific (throw 'exit props)))
  14402. (when (or (not specific) (string= specific "TAGS"))
  14403. (let ((value (org-string-nw-p (org-get-tags-string))))
  14404. (when value (push (cons "TAGS" value) props)))
  14405. (when specific (throw 'exit props)))
  14406. (when (or (not specific) (string= specific "ALLTAGS"))
  14407. (let ((value (org-get-tags-at)))
  14408. (when value
  14409. (push (cons "ALLTAGS"
  14410. (format ":%s:" (mapconcat #'identity value ":")))
  14411. props)))
  14412. (when specific (throw 'exit props)))
  14413. (when (or (not specific) (string= specific "BLOCKED"))
  14414. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14415. (when specific (throw 'exit props)))
  14416. (when (or (not specific)
  14417. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14418. (forward-line)
  14419. (when (looking-at-p org-planning-line-re)
  14420. (end-of-line)
  14421. (let ((bol (line-beginning-position))
  14422. ;; Backward compatibility: time keywords used to
  14423. ;; be configurable (before 8.3). Make sure we
  14424. ;; get the correct keyword.
  14425. (key-assoc `(("CLOSED" . ,org-closed-string)
  14426. ("DEADLINE" . ,org-deadline-string)
  14427. ("SCHEDULED" . ,org-scheduled-string))))
  14428. (dolist (pair (if specific (list (assoc specific key-assoc))
  14429. key-assoc))
  14430. (save-excursion
  14431. (when (search-backward (cdr pair) bol t)
  14432. (goto-char (match-end 0))
  14433. (skip-chars-forward " \t")
  14434. (and (looking-at org-ts-regexp-both)
  14435. (push (cons (car pair)
  14436. (match-string-no-properties 0))
  14437. props)))))))
  14438. (when specific (throw 'exit props)))
  14439. (when (or (not specific)
  14440. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14441. (let ((find-ts
  14442. (lambda (end ts)
  14443. ;; Fix next time-stamp before END. TS is the
  14444. ;; list of time-stamps found so far.
  14445. (let ((ts ts)
  14446. (regexp (cond
  14447. ((string= specific "TIMESTAMP")
  14448. org-ts-regexp)
  14449. ((string= specific "TIMESTAMP_IA")
  14450. org-ts-regexp-inactive)
  14451. ((assoc "TIMESTAMP_IA" ts)
  14452. org-ts-regexp)
  14453. ((assoc "TIMESTAMP" ts)
  14454. org-ts-regexp-inactive)
  14455. (t org-ts-regexp-both))))
  14456. (catch 'next
  14457. (while (re-search-forward regexp end t)
  14458. (backward-char)
  14459. (let ((object (org-element-context)))
  14460. ;; Accept to match timestamps in node
  14461. ;; properties, too.
  14462. (when (memq (org-element-type object)
  14463. '(node-property timestamp))
  14464. (let ((type
  14465. (org-element-property :type object)))
  14466. (cond
  14467. ((and (memq type '(active active-range))
  14468. (not (equal specific "TIMESTAMP_IA")))
  14469. (unless (assoc "TIMESTAMP" ts)
  14470. (push (cons "TIMESTAMP"
  14471. (org-element-property
  14472. :raw-value object))
  14473. ts)
  14474. (when specific (throw 'exit ts))))
  14475. ((and (memq type '(inactive inactive-range))
  14476. (not (string= specific "TIMESTAMP")))
  14477. (unless (assoc "TIMESTAMP_IA" ts)
  14478. (push (cons "TIMESTAMP_IA"
  14479. (org-element-property
  14480. :raw-value object))
  14481. ts)
  14482. (when specific (throw 'exit ts))))))
  14483. ;; Both timestamp types are found,
  14484. ;; move to next part.
  14485. (when (= (length ts) 2) (throw 'next ts)))))
  14486. ts)))))
  14487. (goto-char beg)
  14488. ;; First look for timestamps within headline.
  14489. (let ((ts (funcall find-ts (line-end-position) nil)))
  14490. (if (= (length ts) 2) (setq props (nconc ts props))
  14491. (forward-line)
  14492. ;; Then find timestamps in the section, skipping
  14493. ;; planning line.
  14494. (when (looking-at-p org-planning-line-re)
  14495. (forward-line))
  14496. (let ((end (save-excursion (outline-next-heading))))
  14497. (setq props (nconc (funcall find-ts end ts) props))))))))
  14498. ;; Get the standard properties, like :PROP:.
  14499. (when (memq which '(nil all standard))
  14500. ;; If we are looking after a specific property, delegate
  14501. ;; to `org-entry-get', which is faster. However, make an
  14502. ;; exception for "CATEGORY", since it can be also set
  14503. ;; through keywords (i.e. #+CATEGORY).
  14504. (if (and specific (not (equal specific "CATEGORY")))
  14505. (let ((value (org-entry-get beg specific nil t)))
  14506. (throw 'exit (and value (list (cons specific value)))))
  14507. (let ((range (org-get-property-block beg)))
  14508. (when range
  14509. (let ((end (cdr range)) seen-base)
  14510. (goto-char (car range))
  14511. ;; Unlike to `org--update-property-plist', we
  14512. ;; handle the case where base values is found
  14513. ;; after its extension. We also forbid standard
  14514. ;; properties to be named as special properties.
  14515. (while (re-search-forward org-property-re end t)
  14516. (let* ((key (upcase (match-string-no-properties 2)))
  14517. (extendp (string-match-p "\\+\\'" key))
  14518. (key-base (if extendp (substring key 0 -1) key))
  14519. (value (match-string-no-properties 3)))
  14520. (cond
  14521. ((member-ignore-case key-base org-special-properties))
  14522. (extendp
  14523. (setq props
  14524. (org--update-property-plist key value props)))
  14525. ((member key seen-base))
  14526. (t (push key seen-base)
  14527. (let ((p (assoc-string key props t)))
  14528. (if p (setcdr p (concat value " " (cdr p)))
  14529. (push (cons key value) props))))))))))))
  14530. (unless (assoc "CATEGORY" props)
  14531. (push (cons "CATEGORY" (org-get-category beg)) props)
  14532. (when (string= specific "CATEGORY") (throw 'exit props)))
  14533. ;; Return value.
  14534. props)))))
  14535. (defun org-property--local-values (property literal-nil)
  14536. "Return value for PROPERTY in current entry.
  14537. Value is a list whose car is the base value for PROPERTY and cdr
  14538. a list of accumulated values. Return nil if neither is found in
  14539. the entry. Also return nil when PROPERTY is set to \"nil\",
  14540. unless LITERAL-NIL is non-nil."
  14541. (let ((range (org-get-property-block)))
  14542. (when range
  14543. (goto-char (car range))
  14544. (let* ((case-fold-search t)
  14545. (end (cdr range))
  14546. (value
  14547. ;; Base value.
  14548. (save-excursion
  14549. (let ((v (and (re-search-forward
  14550. (org-re-property property nil t) end t)
  14551. (match-string-no-properties 3))))
  14552. (list (if literal-nil v (org-not-nil v)))))))
  14553. ;; Find additional values.
  14554. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14555. (while (re-search-forward property+ end t)
  14556. (push (match-string-no-properties 3) value)))
  14557. ;; Return final values.
  14558. (and (not (equal value '(nil))) (nreverse value))))))
  14559. (defun org-entry-get (pom property &optional inherit literal-nil)
  14560. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14561. If INHERIT is non-nil and the entry does not have the property,
  14562. then also check higher levels of the hierarchy. If INHERIT is
  14563. the symbol `selective', use inheritance only if the setting in
  14564. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14565. If the property is present but empty, the return value is the
  14566. empty string. If the property is not present at all, nil is
  14567. returned. In any other case, return the value as a string.
  14568. Search is case-insensitive.
  14569. If LITERAL-NIL is set, return the string value \"nil\" as
  14570. a string, do not interpret it as the list atom nil. This is used
  14571. for inheritance when a \"nil\" value can supersede a non-nil
  14572. value higher up the hierarchy."
  14573. (org-with-point-at pom
  14574. (cond
  14575. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14576. ;; We need a special property. Use `org-entry-properties' to
  14577. ;; retrieve it, but specify the wanted property.
  14578. (cdr (assoc-string property (org-entry-properties nil property))))
  14579. ((and inherit
  14580. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14581. (org-entry-get-with-inheritance property literal-nil))
  14582. (t
  14583. (let* ((local (org-property--local-values property literal-nil))
  14584. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14585. (if literal-nil value (org-not-nil value)))))))
  14586. (defun org-property-or-variable-value (var &optional inherit)
  14587. "Check if there is a property fixing the value of VAR.
  14588. If yes, return this value. If not, return the current value of the variable."
  14589. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14590. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14591. (read prop)
  14592. (symbol-value var))))
  14593. (defun org-entry-delete (pom property)
  14594. "Delete PROPERTY from entry at point-or-marker POM.
  14595. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14596. non-nil when a property was removed."
  14597. (unless (member property org-special-properties)
  14598. (org-with-point-at pom
  14599. (let ((range (org-get-property-block)))
  14600. (when range
  14601. (let* ((begin (car range))
  14602. (origin (cdr range))
  14603. (end (copy-marker origin))
  14604. (re (org-re-property
  14605. (concat (regexp-quote property) "\\+?") t t)))
  14606. (goto-char begin)
  14607. (while (re-search-forward re end t)
  14608. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14609. ;; If drawer is empty, remove it altogether.
  14610. (when (= begin end)
  14611. (delete-region (line-beginning-position 0)
  14612. (line-beginning-position 2)))
  14613. ;; Return non-nil if some property was removed.
  14614. (prog1 (/= end origin) (set-marker end nil))))))))
  14615. ;; Multi-values properties are properties that contain multiple values
  14616. ;; These values are assumed to be single words, separated by whitespace.
  14617. (defun org-entry-add-to-multivalued-property (pom property value)
  14618. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14619. (let* ((old (org-entry-get pom property))
  14620. (values (and old (org-split-string old "[ \t]"))))
  14621. (setq value (org-entry-protect-space value))
  14622. (unless (member value values)
  14623. (setq values (append values (list value)))
  14624. (org-entry-put pom property
  14625. (mapconcat 'identity values " ")))))
  14626. (defun org-entry-remove-from-multivalued-property (pom property value)
  14627. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14628. (let* ((old (org-entry-get pom property))
  14629. (values (and old (org-split-string old "[ \t]"))))
  14630. (setq value (org-entry-protect-space value))
  14631. (when (member value values)
  14632. (setq values (delete value values))
  14633. (org-entry-put pom property
  14634. (mapconcat 'identity values " ")))))
  14635. (defun org-entry-member-in-multivalued-property (pom property value)
  14636. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14637. (let* ((old (org-entry-get pom property))
  14638. (values (and old (org-split-string old "[ \t]"))))
  14639. (setq value (org-entry-protect-space value))
  14640. (member value values)))
  14641. (defun org-entry-get-multivalued-property (pom property)
  14642. "Return a list of values in a multivalued property."
  14643. (let* ((value (org-entry-get pom property))
  14644. (values (and value (org-split-string value "[ \t]"))))
  14645. (mapcar 'org-entry-restore-space values)))
  14646. (defun org-entry-put-multivalued-property (pom property &rest values)
  14647. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14648. VALUES should be a list of strings. Spaces will be protected."
  14649. (org-entry-put pom property
  14650. (mapconcat 'org-entry-protect-space values " "))
  14651. (let* ((value (org-entry-get pom property))
  14652. (values (and value (org-split-string value "[ \t]"))))
  14653. (mapcar 'org-entry-restore-space values)))
  14654. (defun org-entry-protect-space (s)
  14655. "Protect spaces and newline in string S."
  14656. (while (string-match " " s)
  14657. (setq s (replace-match "%20" t t s)))
  14658. (while (string-match "\n" s)
  14659. (setq s (replace-match "%0A" t t s)))
  14660. s)
  14661. (defun org-entry-restore-space (s)
  14662. "Restore spaces and newline in string S."
  14663. (while (string-match "%20" s)
  14664. (setq s (replace-match " " t t s)))
  14665. (while (string-match "%0A" s)
  14666. (setq s (replace-match "\n" t t s)))
  14667. s)
  14668. (defvar org-entry-property-inherited-from (make-marker)
  14669. "Marker pointing to the entry from where a property was inherited.
  14670. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14671. location of the entry where the inheritance search matched. If there was
  14672. no match, the marker will point nowhere.
  14673. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14674. is set.")
  14675. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14676. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14677. The search will stop at the first ancestor which has the property defined.
  14678. If the value found is \"nil\", return nil to show that the property
  14679. should be considered as undefined (this is the meaning of nil here).
  14680. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14681. (move-marker org-entry-property-inherited-from nil)
  14682. (org-with-wide-buffer
  14683. (let (value)
  14684. (catch 'exit
  14685. (while t
  14686. (let ((v (org-property--local-values property literal-nil)))
  14687. (when v
  14688. (setq value
  14689. (concat (mapconcat #'identity (delq nil v) " ")
  14690. (and value " ")
  14691. value)))
  14692. (cond
  14693. ((car v)
  14694. (org-back-to-heading t)
  14695. (move-marker org-entry-property-inherited-from (point))
  14696. (throw 'exit nil))
  14697. ((org-up-heading-safe))
  14698. (t
  14699. (let ((global
  14700. (cdr (or (assoc-string property org-file-properties t)
  14701. (assoc-string property org-global-properties t)
  14702. (assoc-string property org-global-properties-fixed t)))))
  14703. (cond ((not global))
  14704. (value (setq value (concat global " " value)))
  14705. (t (setq value global))))
  14706. (throw 'exit nil))))))
  14707. (if literal-nil value (org-not-nil value)))))
  14708. (defvar org-property-changed-functions nil
  14709. "Hook called when the value of a property has changed.
  14710. Each hook function should accept two arguments, the name of the property
  14711. and the new value.")
  14712. (defun org-entry-put (pom property value)
  14713. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14714. If the value is nil, it is converted to the empty string. If it
  14715. is not a string, an error is raised. Also raise an error on
  14716. invalid property names.
  14717. PROPERTY can be any regular property (see
  14718. `org-special-properties'). It can also be \"TODO\",
  14719. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14720. For the last two properties, VALUE may have any of the special
  14721. values \"earlier\" and \"later\". The function then increases or
  14722. decreases scheduled or deadline date by one day."
  14723. (cond ((null value) (setq value ""))
  14724. ((not (stringp value)) (error "Properties values should be strings"))
  14725. ((not (org--valid-property-p property))
  14726. (user-error "Invalid property name: \"%s\"" property)))
  14727. (org-with-point-at pom
  14728. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14729. (org-back-to-heading t)
  14730. (org-with-limited-levels (org-back-to-heading t)))
  14731. (let ((beg (point)))
  14732. (cond
  14733. ((equal property "TODO")
  14734. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14735. ((not (member value org-todo-keywords-1))
  14736. (user-error "\"%s\" is not a valid TODO state" value)))
  14737. (org-todo value)
  14738. (org-set-tags nil 'align))
  14739. ((equal property "PRIORITY")
  14740. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14741. (org-set-tags nil 'align))
  14742. ((equal property "SCHEDULED")
  14743. (forward-line)
  14744. (if (and (looking-at-p org-planning-line-re)
  14745. (re-search-forward
  14746. org-scheduled-time-regexp (line-end-position) t))
  14747. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14748. ((string= value "later") (org-timestamp-change 1 'day))
  14749. ((string= value "") (org-schedule '(4)))
  14750. (t (org-schedule nil value)))
  14751. (if (member value '("earlier" "later" ""))
  14752. (call-interactively #'org-schedule)
  14753. (org-schedule nil value))))
  14754. ((equal property "DEADLINE")
  14755. (forward-line)
  14756. (if (and (looking-at-p org-planning-line-re)
  14757. (re-search-forward
  14758. org-deadline-time-regexp (line-end-position) t))
  14759. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14760. ((string= value "later") (org-timestamp-change 1 'day))
  14761. ((string= value "") (org-deadline '(4)))
  14762. (t (org-deadline nil value)))
  14763. (if (member value '("earlier" "later" ""))
  14764. (call-interactively #'org-deadline)
  14765. (org-deadline nil value))))
  14766. ((member property org-special-properties)
  14767. (error "The %s property cannot be set with `org-entry-put'" property))
  14768. (t
  14769. (let* ((range (org-get-property-block beg 'force))
  14770. (end (cdr range))
  14771. (case-fold-search t))
  14772. (goto-char (car range))
  14773. (if (re-search-forward (org-re-property property nil t) end t)
  14774. (progn (delete-region (match-beginning 0) (match-end 0))
  14775. (goto-char (match-beginning 0)))
  14776. (goto-char end)
  14777. (insert "\n")
  14778. (backward-char))
  14779. (insert ":" property ":")
  14780. (when value (insert " " value))
  14781. (org-indent-line)))))
  14782. (run-hook-with-args 'org-property-changed-functions property value)))
  14783. (defun org-buffer-property-keys
  14784. (&optional specials defaults columns ignore-malformed)
  14785. "Get all property keys in the current buffer.
  14786. When SPECIALS is non-nil, also list the special properties that
  14787. reflect things like tags and TODO state.
  14788. When DEFAULTS is non-nil, also include properties that has
  14789. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14790. DESCRIPTION, LOCATION, and LOGGING and others.
  14791. When COLUMNS in non-nil, also include property names given in
  14792. COLUMN formats in the current buffer.
  14793. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14794. automatically performed, such drawers will be silently ignored."
  14795. (let ((case-fold-search t)
  14796. (props (append
  14797. (and specials org-special-properties)
  14798. (and defaults (cons org-effort-property org-default-properties))
  14799. nil)))
  14800. (org-with-wide-buffer
  14801. (goto-char (point-min))
  14802. (while (re-search-forward org-property-start-re nil t)
  14803. (let ((range (org-get-property-block)))
  14804. (catch 'skip
  14805. (unless range
  14806. (when (and (not ignore-malformed)
  14807. (not (org-before-first-heading-p))
  14808. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14809. (line-beginning-position))))
  14810. (org-get-property-block nil t))
  14811. (throw 'skip nil))
  14812. (goto-char (car range))
  14813. (let ((begin (car range))
  14814. (end (cdr range)))
  14815. ;; Make sure that found property block is not located
  14816. ;; before current point, as it would generate an infloop.
  14817. ;; It can happen, for example, in the following
  14818. ;; situation:
  14819. ;;
  14820. ;; * Headline
  14821. ;; :PROPERTIES:
  14822. ;; ...
  14823. ;; :END:
  14824. ;; *************** Inlinetask
  14825. ;; #+BEGIN_EXAMPLE
  14826. ;; :PROPERTIES:
  14827. ;; #+END_EXAMPLE
  14828. ;;
  14829. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14830. (while (< (point) end)
  14831. (let ((p (progn (looking-at org-property-re)
  14832. (match-string-no-properties 2))))
  14833. ;; Only add true property name, not extension symbol.
  14834. (push (if (not (string-match-p "\\+\\'" p)) p
  14835. (substring p 0 -1))
  14836. props))
  14837. (forward-line))))
  14838. (outline-next-heading)))
  14839. (when columns
  14840. (goto-char (point-min))
  14841. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14842. (let ((element (org-element-at-point)))
  14843. (when (memq (org-element-type element) '(keyword node-property))
  14844. (let ((value (org-element-property :value element))
  14845. (start 0))
  14846. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14847. (setq start (match-end 0))
  14848. (let ((p (match-string-no-properties 1 value)))
  14849. (unless (member-ignore-case p org-special-properties)
  14850. (push p props))))))))))
  14851. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14852. (defun org-property-values (key)
  14853. "List all non-nil values of property KEY in current buffer."
  14854. (org-with-wide-buffer
  14855. (goto-char (point-min))
  14856. (let ((case-fold-search t)
  14857. (re (org-re-property key))
  14858. values)
  14859. (while (re-search-forward re nil t)
  14860. (push (org-entry-get (point) key) values))
  14861. (delete-dups values))))
  14862. (defun org-insert-property-drawer ()
  14863. "Insert a property drawer into the current entry."
  14864. (org-with-wide-buffer
  14865. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14866. (org-back-to-heading t)
  14867. (org-with-limited-levels (org-back-to-heading t)))
  14868. (forward-line)
  14869. (when (looking-at-p org-planning-line-re) (forward-line))
  14870. (unless (looking-at-p org-property-drawer-re)
  14871. ;; Make sure we start editing a line from current entry, not from
  14872. ;; next one. It prevents extending text properties or overlays
  14873. ;; belonging to the latter.
  14874. (when (bolp) (backward-char))
  14875. (let ((begin (1+ (point)))
  14876. (inhibit-read-only t))
  14877. (insert "\n:PROPERTIES:\n:END:")
  14878. (when (eobp) (insert "\n"))
  14879. (org-indent-region begin (point))))))
  14880. (defun org-insert-drawer (&optional arg drawer)
  14881. "Insert a drawer at point.
  14882. When optional argument ARG is non-nil, insert a property drawer.
  14883. Optional argument DRAWER, when non-nil, is a string representing
  14884. drawer's name. Otherwise, the user is prompted for a name.
  14885. If a region is active, insert the drawer around that region
  14886. instead.
  14887. Point is left between drawer's boundaries."
  14888. (interactive "P")
  14889. (let* ((drawer (if arg "PROPERTIES"
  14890. (or drawer (read-from-minibuffer "Drawer: ")))))
  14891. (cond
  14892. ;; With C-u, fall back on `org-insert-property-drawer'
  14893. (arg (org-insert-property-drawer))
  14894. ;; Check validity of suggested drawer's name.
  14895. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14896. (user-error "Invalid drawer name"))
  14897. ;; With an active region, insert a drawer at point.
  14898. ((not (org-region-active-p))
  14899. (progn
  14900. (unless (bolp) (insert "\n"))
  14901. (insert (format ":%s:\n\n:END:\n" drawer))
  14902. (forward-line -2)))
  14903. ;; Otherwise, insert the drawer at point
  14904. (t
  14905. (let ((rbeg (region-beginning))
  14906. (rend (copy-marker (region-end))))
  14907. (unwind-protect
  14908. (progn
  14909. (goto-char rbeg)
  14910. (beginning-of-line)
  14911. (when (save-excursion
  14912. (re-search-forward org-outline-regexp-bol rend t))
  14913. (user-error "Drawers cannot contain headlines"))
  14914. ;; Position point at the beginning of the first
  14915. ;; non-blank line in region. Insert drawer's opening
  14916. ;; there, then indent it.
  14917. (org-skip-whitespace)
  14918. (beginning-of-line)
  14919. (insert ":" drawer ":\n")
  14920. (forward-line -1)
  14921. (indent-for-tab-command)
  14922. ;; Move point to the beginning of the first blank line
  14923. ;; after the last non-blank line in region. Insert
  14924. ;; drawer's closing, then indent it.
  14925. (goto-char rend)
  14926. (skip-chars-backward " \r\t\n")
  14927. (insert "\n:END:")
  14928. (deactivate-mark t)
  14929. (indent-for-tab-command)
  14930. (unless (eolp) (insert "\n")))
  14931. ;; Clear marker, whatever the outcome of insertion is.
  14932. (set-marker rend nil)))))))
  14933. (defvar org-property-set-functions-alist nil
  14934. "Property set function alist.
  14935. Each entry should have the following format:
  14936. (PROPERTY . READ-FUNCTION)
  14937. The read function will be called with the same argument as
  14938. `org-completing-read'.")
  14939. (defun org-set-property-function (property)
  14940. "Get the function that should be used to set PROPERTY.
  14941. This is computed according to `org-property-set-functions-alist'."
  14942. (or (cdr (assoc property org-property-set-functions-alist))
  14943. 'org-completing-read))
  14944. (defun org-read-property-value (property)
  14945. "Read PROPERTY value from user."
  14946. (let* ((completion-ignore-case t)
  14947. (allowed (org-property-get-allowed-values nil property 'table))
  14948. (cur (org-entry-get nil property))
  14949. (prompt (concat property " value"
  14950. (if (and cur (string-match "\\S-" cur))
  14951. (concat " [" cur "]") "") ": "))
  14952. (set-function (org-set-property-function property))
  14953. (val (if allowed
  14954. (funcall set-function prompt allowed nil
  14955. (not (get-text-property 0 'org-unrestricted
  14956. (caar allowed))))
  14957. (funcall set-function prompt
  14958. (mapcar 'list (org-property-values property))
  14959. nil nil "" nil cur))))
  14960. (org-trim val)))
  14961. (defvar org-last-set-property nil)
  14962. (defvar org-last-set-property-value nil)
  14963. (defun org-read-property-name ()
  14964. "Read a property name."
  14965. (let ((completion-ignore-case t)
  14966. (default-prop (or (and (org-at-property-p)
  14967. (match-string-no-properties 2))
  14968. org-last-set-property)))
  14969. (org-completing-read
  14970. (concat "Property"
  14971. (if default-prop (concat " [" default-prop "]") "")
  14972. ": ")
  14973. (mapcar #'list (org-buffer-property-keys nil t t))
  14974. nil nil nil nil default-prop)))
  14975. (defun org-set-property-and-value (use-last)
  14976. "Allow to set [PROPERTY]: [value] direction from prompt.
  14977. When use-default, don't even ask, just use the last
  14978. \"[PROPERTY]: [value]\" string from the history."
  14979. (interactive "P")
  14980. (let* ((completion-ignore-case t)
  14981. (pv (or (and use-last org-last-set-property-value)
  14982. (org-completing-read
  14983. "Enter a \"[Property]: [value]\" pair: "
  14984. nil nil nil nil nil
  14985. org-last-set-property-value)))
  14986. prop val)
  14987. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14988. (setq prop (match-string 1 pv)
  14989. val (match-string 2 pv))
  14990. (org-set-property prop val))))
  14991. (defun org-set-property (property value)
  14992. "In the current entry, set PROPERTY to VALUE.
  14993. When called interactively, this will prompt for a property name, offering
  14994. completion on existing and default properties. And then it will prompt
  14995. for a value, offering completion either on allowed values (via an inherited
  14996. xxx_ALL property) or on existing values in other instances of this property
  14997. in the current file.
  14998. Throw an error when trying to set a property with an invalid name."
  14999. (interactive (list nil nil))
  15000. (let ((property (or property (org-read-property-name))))
  15001. ;; `org-entry-put' also makes the following check, but this one
  15002. ;; avoids polluting `org-last-set-property' and
  15003. ;; `org-last-set-property-value' needlessly.
  15004. (unless (org--valid-property-p property)
  15005. (user-error "Invalid property name: \"%s\"" property))
  15006. (let ((value (or value (org-read-property-value property)))
  15007. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15008. (setq org-last-set-property property)
  15009. (setq org-last-set-property-value (concat property ": " value))
  15010. ;; Possibly postprocess the inserted value:
  15011. (when fn (setq value (funcall fn value)))
  15012. (unless (equal (org-entry-get nil property) value)
  15013. (org-entry-put nil property value)))))
  15014. (defun org-find-property (property &optional value)
  15015. "Find first entry in buffer that sets PROPERTY.
  15016. When optional argument VALUE is non-nil, only consider an entry
  15017. if it contains PROPERTY set to this value. If PROPERTY should be
  15018. explicitly set to nil, use string \"nil\" for VALUE.
  15019. Return position where the entry begins, or nil if there is no
  15020. such entry. If narrowing is in effect, only search the visible
  15021. part of the buffer."
  15022. (save-excursion
  15023. (goto-char (point-min))
  15024. (let ((case-fold-search t)
  15025. (re (org-re-property property nil (not value) value)))
  15026. (catch 'exit
  15027. (while (re-search-forward re nil t)
  15028. (when (if value (org-at-property-p)
  15029. (org-entry-get (point) property nil t))
  15030. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15031. (defun org-delete-property (property)
  15032. "In the current entry, delete PROPERTY."
  15033. (interactive
  15034. (let* ((completion-ignore-case t)
  15035. (cat (org-entry-get (point) "CATEGORY"))
  15036. (props0 (org-entry-properties nil 'standard))
  15037. (props (if cat props0
  15038. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15039. (prop (if (< 1 (length props))
  15040. (completing-read "Property: " props nil t)
  15041. (caar props))))
  15042. (list prop)))
  15043. (if (not property)
  15044. (message "No property to delete in this entry")
  15045. (org-entry-delete nil property)
  15046. (message "Property \"%s\" deleted" property)))
  15047. (defun org-delete-property-globally (property)
  15048. "Remove PROPERTY globally, from all entries.
  15049. This function ignores narrowing, if any."
  15050. (interactive
  15051. (let* ((completion-ignore-case t)
  15052. (prop (completing-read
  15053. "Globally remove property: "
  15054. (mapcar #'list (org-buffer-property-keys)))))
  15055. (list prop)))
  15056. (org-with-wide-buffer
  15057. (goto-char (point-min))
  15058. (let ((count 0)
  15059. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15060. (while (re-search-forward re nil t)
  15061. (when (org-entry-delete (point) property) (cl-incf count)))
  15062. (message "Property \"%s\" removed from %d entries" property count))))
  15063. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15064. (defun org-compute-property-at-point ()
  15065. "Compute the property at point.
  15066. This looks for an enclosing column format, extracts the operator and
  15067. then applies it to the property in the column format's scope."
  15068. (interactive)
  15069. (unless (org-at-property-p)
  15070. (user-error "Not at a property"))
  15071. (let ((prop (match-string-no-properties 2)))
  15072. (org-columns-get-format-and-top-level)
  15073. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15074. (user-error "No operator defined for property %s" prop))
  15075. (org-columns-compute prop)))
  15076. (defvar org-property-allowed-value-functions nil
  15077. "Hook for functions supplying allowed values for a specific property.
  15078. The functions must take a single argument, the name of the property, and
  15079. return a flat list of allowed values. If \":ETC\" is one of
  15080. the values, this means that these values are intended as defaults for
  15081. completion, but that other values should be allowed too.
  15082. The functions must return nil if they are not responsible for this
  15083. property.")
  15084. (defun org-property-get-allowed-values (pom property &optional table)
  15085. "Get allowed values for the property PROPERTY.
  15086. When TABLE is non-nil, return an alist that can directly be used for
  15087. completion."
  15088. (let (vals)
  15089. (cond
  15090. ((equal property "TODO")
  15091. (setq vals (org-with-point-at pom
  15092. (append org-todo-keywords-1 '("")))))
  15093. ((equal property "PRIORITY")
  15094. (let ((n org-lowest-priority))
  15095. (while (>= n org-highest-priority)
  15096. (push (char-to-string n) vals)
  15097. (setq n (1- n)))))
  15098. ((equal property "CATEGORY"))
  15099. ((member property org-special-properties))
  15100. ((setq vals (run-hook-with-args-until-success
  15101. 'org-property-allowed-value-functions property)))
  15102. (t
  15103. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15104. (when (and vals (string-match "\\S-" vals))
  15105. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15106. (setq vals (mapcar (lambda (x)
  15107. (cond ((stringp x) x)
  15108. ((numberp x) (number-to-string x))
  15109. ((symbolp x) (symbol-name x))
  15110. (t "???")))
  15111. vals)))))
  15112. (when (member ":ETC" vals)
  15113. (setq vals (remove ":ETC" vals))
  15114. (org-add-props (car vals) '(org-unrestricted t)))
  15115. (if table (mapcar 'list vals) vals)))
  15116. (defun org-property-previous-allowed-value (&optional _previous)
  15117. "Switch to the next allowed value for this property."
  15118. (interactive)
  15119. (org-property-next-allowed-value t))
  15120. (defun org-property-next-allowed-value (&optional previous)
  15121. "Switch to the next allowed value for this property."
  15122. (interactive)
  15123. (unless (org-at-property-p)
  15124. (user-error "Not at a property"))
  15125. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15126. (key (match-string 2))
  15127. (value (match-string 3))
  15128. (allowed (or (org-property-get-allowed-values (point) key)
  15129. (and (member value '("[ ]" "[-]" "[X]"))
  15130. '("[ ]" "[X]"))))
  15131. (heading (save-match-data (nth 4 (org-heading-components))))
  15132. nval)
  15133. (unless allowed
  15134. (user-error "Allowed values for this property have not been defined"))
  15135. (when previous (setq allowed (reverse allowed)))
  15136. (when (member value allowed)
  15137. (setq nval (car (cdr (member value allowed)))))
  15138. (setq nval (or nval (car allowed)))
  15139. (when (equal nval value)
  15140. (user-error "Only one allowed value for this property"))
  15141. (org-at-property-p)
  15142. (replace-match (concat " :" key ": " nval) t t)
  15143. (org-indent-line)
  15144. (beginning-of-line 1)
  15145. (skip-chars-forward " \t")
  15146. (when (equal prop org-effort-property)
  15147. (org-refresh-property
  15148. '((effort . identity)
  15149. (effort-minutes . org-duration-string-to-minutes))
  15150. nval)
  15151. (when (string= org-clock-current-task heading)
  15152. (setq org-clock-effort nval)
  15153. (org-clock-update-mode-line)))
  15154. (run-hook-with-args 'org-property-changed-functions key nval)))
  15155. (defun org-find-olp (path &optional this-buffer)
  15156. "Return a marker pointing to the entry at outline path OLP.
  15157. If anything goes wrong, throw an error.
  15158. You can wrap this call to catch the error like this:
  15159. \(condition-case msg
  15160. \(org-mobile-locate-entry (match-string 4))
  15161. \(error (nth 1 msg)))
  15162. The return value will then be either a string with the error message,
  15163. or a marker if everything is OK.
  15164. If THIS-BUFFER is set, the outline path does not contain a file,
  15165. only headings."
  15166. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15167. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15168. (level 1)
  15169. (lmin 1)
  15170. (lmax 1)
  15171. end found flevel)
  15172. (unless buffer (error "File not found :%s" file))
  15173. (with-current-buffer buffer
  15174. (org-with-wide-buffer
  15175. (goto-char (point-min))
  15176. (dolist (heading path)
  15177. (let ((re (format org-complex-heading-regexp-format
  15178. (regexp-quote heading)))
  15179. (cnt 0))
  15180. (while (re-search-forward re end t)
  15181. (setq level (- (match-end 1) (match-beginning 1)))
  15182. (when (and (>= level lmin) (<= level lmax))
  15183. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15184. (when (= cnt 0)
  15185. (error "Heading not found on level %d: %s" lmax heading))
  15186. (when (> cnt 1)
  15187. (error "Heading not unique on level %d: %s" lmax heading))
  15188. (goto-char found)
  15189. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15190. (setq end (save-excursion (org-end-of-subtree t t)))))
  15191. (when (org-at-heading-p)
  15192. (point-marker))))))
  15193. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15194. "Find node HEADING in BUFFER.
  15195. Return a marker to the heading if it was found, or nil if not.
  15196. If POS-ONLY is set, return just the position instead of a marker.
  15197. The heading text must match exact, but it may have a TODO keyword,
  15198. a priority cookie and tags in the standard locations."
  15199. (with-current-buffer (or buffer (current-buffer))
  15200. (org-with-wide-buffer
  15201. (goto-char (point-min))
  15202. (let (case-fold-search)
  15203. (when (re-search-forward
  15204. (format org-complex-heading-regexp-format
  15205. (regexp-quote heading)) nil t)
  15206. (if pos-only
  15207. (match-beginning 0)
  15208. (move-marker (make-marker) (match-beginning 0))))))))
  15209. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15210. "Find Org node headline HEADING in all .org files in directory DIR.
  15211. When the target headline is found, return a marker to this location."
  15212. (let ((files (directory-files (or dir default-directory)
  15213. t "\\`[^.#].*\\.org\\'"))
  15214. visiting m buffer)
  15215. (catch 'found
  15216. (dolist (file files)
  15217. (message "trying %s" file)
  15218. (setq visiting (org-find-base-buffer-visiting file))
  15219. (setq buffer (or visiting (find-file-noselect file)))
  15220. (setq m (org-find-exact-headline-in-buffer
  15221. heading buffer))
  15222. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15223. (and m (throw 'found m))))))
  15224. (defun org-find-entry-with-id (ident)
  15225. "Locate the entry that contains the ID property with exact value IDENT.
  15226. IDENT can be a string, a symbol or a number, this function will search for
  15227. the string representation of it.
  15228. Return the position where this entry starts, or nil if there is no such entry."
  15229. (interactive "sID: ")
  15230. (let ((id (cond
  15231. ((stringp ident) ident)
  15232. ((symbolp ident) (symbol-name ident))
  15233. ((numberp ident) (number-to-string ident))
  15234. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15235. (org-with-wide-buffer (org-find-property "ID" id))))
  15236. ;;;; Timestamps
  15237. (defvar org-last-changed-timestamp nil)
  15238. (defvar org-last-inserted-timestamp nil
  15239. "The last time stamp inserted with `org-insert-time-stamp'.")
  15240. (defvar org-ts-what) ; dynamically scoped parameter
  15241. (defun org-time-stamp (arg &optional inactive)
  15242. "Prompt for a date/time and insert a time stamp.
  15243. If the user specifies a time like HH:MM or if this command is
  15244. called with at least one prefix argument, the time stamp contains
  15245. the date and the time. Otherwise, only the date is included.
  15246. All parts of a date not specified by the user are filled in from
  15247. the timestamp at point, if any, or the current date/time
  15248. otherwise.
  15249. If there is already a timestamp at the cursor, it is replaced.
  15250. With two universal prefix arguments, insert an active timestamp
  15251. with the current time without prompting the user.
  15252. When called from lisp, the timestamp is inactive if INACTIVE is
  15253. non-nil."
  15254. (interactive "P")
  15255. (let* ((ts (cond
  15256. ((org-at-date-range-p t)
  15257. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15258. ((org-at-timestamp-p t) (match-string 0))))
  15259. ;; Default time is either the timestamp at point or today.
  15260. ;; When entering a range, only the range start is considered.
  15261. (default-time (if (not ts) (current-time)
  15262. (apply #'encode-time (org-parse-time-string ts))))
  15263. (default-input (and ts (org-get-compact-tod ts)))
  15264. (repeater (and ts
  15265. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15266. (match-string 0 ts)))
  15267. org-time-was-given
  15268. org-end-time-was-given
  15269. (time
  15270. (and (if (equal arg '(16)) (current-time)
  15271. ;; Preserve `this-command' and `last-command'.
  15272. (let ((this-command this-command)
  15273. (last-command last-command))
  15274. (org-read-date
  15275. arg 'totime nil nil default-time default-input
  15276. inactive))))))
  15277. (cond
  15278. ((and ts
  15279. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15280. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15281. (insert "--")
  15282. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15283. (ts
  15284. ;; Make sure we're on a timestamp. When in the middle of a date
  15285. ;; range, move arbitrarily to range end.
  15286. (unless (org-at-timestamp-p t)
  15287. (skip-chars-forward "-")
  15288. (org-at-timestamp-p t))
  15289. (replace-match "")
  15290. (setq org-last-changed-timestamp
  15291. (org-insert-time-stamp
  15292. time (or org-time-was-given arg)
  15293. inactive nil nil (list org-end-time-was-given)))
  15294. (when repeater
  15295. (backward-char)
  15296. (insert " " repeater)
  15297. (setq org-last-changed-timestamp
  15298. (concat (substring org-last-inserted-timestamp 0 -1)
  15299. " " repeater ">")))
  15300. (message "Timestamp updated"))
  15301. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15302. (t (org-insert-time-stamp
  15303. time (or org-time-was-given arg) inactive nil nil
  15304. (list org-end-time-was-given))))))
  15305. ;; FIXME: can we use this for something else, like computing time differences?
  15306. (defun org-get-compact-tod (s)
  15307. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15308. (let* ((t1 (match-string 1 s))
  15309. (h1 (string-to-number (match-string 2 s)))
  15310. (m1 (string-to-number (match-string 3 s)))
  15311. (t2 (and (match-end 4) (match-string 5 s)))
  15312. (h2 (and t2 (string-to-number (match-string 6 s))))
  15313. (m2 (and t2 (string-to-number (match-string 7 s))))
  15314. dh dm)
  15315. (if (not t2)
  15316. t1
  15317. (setq dh (- h2 h1) dm (- m2 m1))
  15318. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15319. (concat t1 "+" (number-to-string dh)
  15320. (and (/= 0 dm) (format ":%02d" dm)))))))
  15321. (defun org-time-stamp-inactive (&optional arg)
  15322. "Insert an inactive time stamp.
  15323. An inactive time stamp is enclosed in square brackets instead of angle
  15324. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15325. does not link to the calendar and cannot be changed with the S-cursor keys.
  15326. So these are more for recording a certain time/date."
  15327. (interactive "P")
  15328. (org-time-stamp arg 'inactive))
  15329. (defvar org-date-ovl (make-overlay 1 1))
  15330. (overlay-put org-date-ovl 'face 'org-date-selected)
  15331. (delete-overlay org-date-ovl)
  15332. (defvar org-ans1) ; dynamically scoped parameter
  15333. (defvar org-ans2) ; dynamically scoped parameter
  15334. (defvar org-plain-time-of-day-regexp) ; defined below
  15335. (defvar org-overriding-default-time nil) ; dynamically scoped
  15336. (defvar org-read-date-overlay nil)
  15337. (defvar org-dcst nil) ; dynamically scoped
  15338. (defvar org-read-date-history nil)
  15339. (defvar org-read-date-final-answer nil)
  15340. (defvar org-read-date-analyze-futurep nil)
  15341. (defvar org-read-date-analyze-forced-year nil)
  15342. (defvar org-read-date-inactive)
  15343. (defvar org-read-date-minibuffer-local-map
  15344. (let* ((map (make-sparse-keymap)))
  15345. (set-keymap-parent map minibuffer-local-map)
  15346. (org-defkey map (kbd ".")
  15347. (lambda () (interactive)
  15348. ;; Are we at the beginning of the prompt?
  15349. (if (looking-back "^[^:]+: "
  15350. (let ((inhibit-field-text-motion t))
  15351. (line-beginning-position)))
  15352. (org-eval-in-calendar '(calendar-goto-today))
  15353. (insert "."))))
  15354. (org-defkey map (kbd "C-.")
  15355. (lambda () (interactive)
  15356. (org-eval-in-calendar '(calendar-goto-today))))
  15357. (org-defkey map [(meta shift left)]
  15358. (lambda () (interactive)
  15359. (org-eval-in-calendar '(calendar-backward-month 1))))
  15360. (org-defkey map [(meta shift right)]
  15361. (lambda () (interactive)
  15362. (org-eval-in-calendar '(calendar-forward-month 1))))
  15363. (org-defkey map [(meta shift up)]
  15364. (lambda () (interactive)
  15365. (org-eval-in-calendar '(calendar-backward-year 1))))
  15366. (org-defkey map [(meta shift down)]
  15367. (lambda () (interactive)
  15368. (org-eval-in-calendar '(calendar-forward-year 1))))
  15369. (org-defkey map [?\e (shift left)]
  15370. (lambda () (interactive)
  15371. (org-eval-in-calendar '(calendar-backward-month 1))))
  15372. (org-defkey map [?\e (shift right)]
  15373. (lambda () (interactive)
  15374. (org-eval-in-calendar '(calendar-forward-month 1))))
  15375. (org-defkey map [?\e (shift up)]
  15376. (lambda () (interactive)
  15377. (org-eval-in-calendar '(calendar-backward-year 1))))
  15378. (org-defkey map [?\e (shift down)]
  15379. (lambda () (interactive)
  15380. (org-eval-in-calendar '(calendar-forward-year 1))))
  15381. (org-defkey map [(shift up)]
  15382. (lambda () (interactive)
  15383. (org-eval-in-calendar '(calendar-backward-week 1))))
  15384. (org-defkey map [(shift down)]
  15385. (lambda () (interactive)
  15386. (org-eval-in-calendar '(calendar-forward-week 1))))
  15387. (org-defkey map [(shift left)]
  15388. (lambda () (interactive)
  15389. (org-eval-in-calendar '(calendar-backward-day 1))))
  15390. (org-defkey map [(shift right)]
  15391. (lambda () (interactive)
  15392. (org-eval-in-calendar '(calendar-forward-day 1))))
  15393. (org-defkey map "!"
  15394. (lambda () (interactive)
  15395. (org-eval-in-calendar '(diary-view-entries))
  15396. (message "")))
  15397. (org-defkey map ">"
  15398. (lambda () (interactive)
  15399. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15400. (org-defkey map "<"
  15401. (lambda () (interactive)
  15402. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15403. (org-defkey map "\C-v"
  15404. (lambda () (interactive)
  15405. (org-eval-in-calendar
  15406. '(calendar-scroll-left-three-months 1))))
  15407. (org-defkey map "\M-v"
  15408. (lambda () (interactive)
  15409. (org-eval-in-calendar
  15410. '(calendar-scroll-right-three-months 1))))
  15411. map)
  15412. "Keymap for minibuffer commands when using `org-read-date'.")
  15413. (defvar org-def)
  15414. (defvar org-defdecode)
  15415. (defvar org-with-time)
  15416. (defvar calendar-setup) ; Dynamically scoped.
  15417. (defun org-read-date (&optional with-time to-time from-string prompt
  15418. default-time default-input inactive)
  15419. "Read a date, possibly a time, and make things smooth for the user.
  15420. The prompt will suggest to enter an ISO date, but you can also enter anything
  15421. which will at least partially be understood by `parse-time-string'.
  15422. Unrecognized parts of the date will default to the current day, month, year,
  15423. hour and minute. If this command is called to replace a timestamp at point,
  15424. or to enter the second timestamp of a range, the default time is taken
  15425. from the existing stamp. Furthermore, the command prefers the future,
  15426. so if you are giving a date where the year is not given, and the day-month
  15427. combination is already past in the current year, it will assume you
  15428. mean next year. For details, see the manual. A few examples:
  15429. 3-2-5 --> 2003-02-05
  15430. feb 15 --> currentyear-02-15
  15431. 2/15 --> currentyear-02-15
  15432. sep 12 9 --> 2009-09-12
  15433. 12:45 --> today 12:45
  15434. 22 sept 0:34 --> currentyear-09-22 0:34
  15435. 12 --> currentyear-currentmonth-12
  15436. Fri --> nearest Friday after today
  15437. -Tue --> last Tuesday
  15438. etc.
  15439. Furthermore you can specify a relative date by giving, as the *first* thing
  15440. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15441. change in days weeks, months, years.
  15442. With a single plus or minus, the date is relative to today. With a double
  15443. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15444. +4d --> four days from today
  15445. +4 --> same as above
  15446. +2w --> two weeks from today
  15447. ++5 --> five days from default date
  15448. The function understands only English month and weekday abbreviations.
  15449. While prompting, a calendar is popped up - you can also select the
  15450. date with the mouse (button 1). The calendar shows a period of three
  15451. months. To scroll it to other months, use the keys `>' and `<'.
  15452. If you don't like the calendar, turn it off with
  15453. (setq org-read-date-popup-calendar nil)
  15454. With optional argument TO-TIME, the date will immediately be converted
  15455. to an internal time.
  15456. With an optional argument WITH-TIME, the prompt will suggest to
  15457. also insert a time. Note that when WITH-TIME is not set, you can
  15458. still enter a time, and this function will inform the calling routine
  15459. about this change. The calling routine may then choose to change the
  15460. format used to insert the time stamp into the buffer to include the time.
  15461. With optional argument FROM-STRING, read from this string instead from
  15462. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15463. the time/date that is used for everything that is not specified by the
  15464. user."
  15465. (require 'parse-time)
  15466. (let* ((org-with-time with-time)
  15467. (org-time-stamp-rounding-minutes
  15468. (if (equal org-with-time '(16))
  15469. '(0 0)
  15470. org-time-stamp-rounding-minutes))
  15471. (org-dcst org-display-custom-times)
  15472. (ct (org-current-time))
  15473. (org-def (or org-overriding-default-time default-time ct))
  15474. (org-defdecode (decode-time org-def))
  15475. (cur-frame (selected-frame))
  15476. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15477. (calendar-setup
  15478. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15479. (calendar-move-hook nil)
  15480. (calendar-view-diary-initially-flag nil)
  15481. (calendar-view-holidays-initially-flag nil)
  15482. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15483. ;; Rationalize `org-def' and `org-defdecode', if required.
  15484. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15485. (setf (nth 2 org-defdecode) -1)
  15486. (setf (nth 1 org-defdecode) 59)
  15487. (setq org-def (apply #'encode-time org-defdecode))
  15488. (setq org-defdecode (decode-time org-def)))
  15489. (let* ((timestr (format-time-string
  15490. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15491. org-def))
  15492. (prompt (concat (if prompt (concat prompt " ") "")
  15493. (format "Date+time [%s]: " timestr))))
  15494. (cond
  15495. (from-string (setq ans from-string))
  15496. (org-read-date-popup-calendar
  15497. (save-excursion
  15498. (save-window-excursion
  15499. (calendar)
  15500. (when (eq calendar-setup 'calendar-only)
  15501. (setq cal-frame
  15502. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15503. (select-frame cal-frame))
  15504. (org-eval-in-calendar '(setq cursor-type nil) t)
  15505. (unwind-protect
  15506. (progn
  15507. (calendar-forward-day (- (time-to-days org-def)
  15508. (calendar-absolute-from-gregorian
  15509. (calendar-current-date))))
  15510. (org-eval-in-calendar nil t)
  15511. (let* ((old-map (current-local-map))
  15512. (map (copy-keymap calendar-mode-map))
  15513. (minibuffer-local-map
  15514. (copy-keymap org-read-date-minibuffer-local-map)))
  15515. (org-defkey map (kbd "RET") 'org-calendar-select)
  15516. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15517. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15518. (unwind-protect
  15519. (progn
  15520. (use-local-map map)
  15521. (setq org-read-date-inactive inactive)
  15522. (add-hook 'post-command-hook 'org-read-date-display)
  15523. (setq org-ans0
  15524. (read-string prompt
  15525. default-input
  15526. 'org-read-date-history
  15527. nil))
  15528. ;; org-ans0: from prompt
  15529. ;; org-ans1: from mouse click
  15530. ;; org-ans2: from calendar motion
  15531. (setq ans
  15532. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15533. (remove-hook 'post-command-hook 'org-read-date-display)
  15534. (use-local-map old-map)
  15535. (when org-read-date-overlay
  15536. (delete-overlay org-read-date-overlay)
  15537. (setq org-read-date-overlay nil)))))
  15538. (bury-buffer "*Calendar*")
  15539. (when cal-frame
  15540. (delete-frame cal-frame)
  15541. (select-frame-set-input-focus cur-frame))))))
  15542. (t ; Naked prompt only
  15543. (unwind-protect
  15544. (setq ans (read-string prompt default-input
  15545. 'org-read-date-history timestr))
  15546. (when org-read-date-overlay
  15547. (delete-overlay org-read-date-overlay)
  15548. (setq org-read-date-overlay nil))))))
  15549. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15550. (when org-read-date-analyze-forced-year
  15551. (message "Year was forced into %s"
  15552. (if org-read-date-force-compatible-dates
  15553. "compatible range (1970-2037)"
  15554. "range representable on this machine"))
  15555. (ding))
  15556. ;; One round trip to get rid of 34th of August and stuff like that....
  15557. (setq final (decode-time (apply 'encode-time final)))
  15558. (setq org-read-date-final-answer ans)
  15559. (if to-time
  15560. (apply 'encode-time final)
  15561. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15562. (format "%04d-%02d-%02d %02d:%02d"
  15563. (nth 5 final) (nth 4 final) (nth 3 final)
  15564. (nth 2 final) (nth 1 final))
  15565. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15566. (defun org-read-date-display ()
  15567. "Display the current date prompt interpretation in the minibuffer."
  15568. (when org-read-date-display-live
  15569. (when org-read-date-overlay
  15570. (delete-overlay org-read-date-overlay))
  15571. (when (minibufferp (current-buffer))
  15572. (save-excursion
  15573. (end-of-line 1)
  15574. (while (not (equal (buffer-substring
  15575. (max (point-min) (- (point) 4)) (point))
  15576. " "))
  15577. (insert " ")))
  15578. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15579. " " (or org-ans1 org-ans2)))
  15580. (org-end-time-was-given nil)
  15581. (f (org-read-date-analyze ans org-def org-defdecode))
  15582. (fmts (if org-dcst
  15583. org-time-stamp-custom-formats
  15584. org-time-stamp-formats))
  15585. (fmt (if (or org-with-time
  15586. (and (boundp 'org-time-was-given) org-time-was-given))
  15587. (cdr fmts)
  15588. (car fmts)))
  15589. (txt (format-time-string fmt (apply 'encode-time f)))
  15590. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15591. (txt (concat "=> " txt)))
  15592. (when (and org-end-time-was-given
  15593. (string-match org-plain-time-of-day-regexp txt))
  15594. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15595. org-end-time-was-given
  15596. (substring txt (match-end 0)))))
  15597. (when org-read-date-analyze-futurep
  15598. (setq txt (concat txt " (=>F)")))
  15599. (setq org-read-date-overlay
  15600. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15601. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15602. (defun org-read-date-analyze (ans def defdecode)
  15603. "Analyze the combined answer of the date prompt."
  15604. ;; FIXME: cleanup and comment
  15605. ;; Pass `current-time' result to `decode-time' (instead of calling
  15606. ;; without arguments) so that only `current-time' has to be
  15607. ;; overriden in tests.
  15608. (let ((org-def def)
  15609. (org-defdecode defdecode)
  15610. (nowdecode (decode-time (current-time)))
  15611. delta deltan deltaw deltadef year month day
  15612. hour minute second wday pm h2 m2 tl wday1
  15613. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15614. (setq org-read-date-analyze-futurep nil
  15615. org-read-date-analyze-forced-year nil)
  15616. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15617. (setq ans "+0"))
  15618. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15619. (setq ans (replace-match "" t t ans)
  15620. deltan (car delta)
  15621. deltaw (nth 1 delta)
  15622. deltadef (nth 2 delta)))
  15623. ;; Check if there is an iso week date in there. If yes, store the
  15624. ;; info and postpone interpreting it until the rest of the parsing
  15625. ;; is done.
  15626. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15627. (setq iso-year (when (match-end 1)
  15628. (org-small-year-to-year
  15629. (string-to-number (match-string 1 ans))))
  15630. iso-weekday (when (match-end 3)
  15631. (string-to-number (match-string 3 ans)))
  15632. iso-week (string-to-number (match-string 2 ans)))
  15633. (setq ans (replace-match "" t t ans)))
  15634. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15635. (when (string-match
  15636. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15637. (setq year (if (match-end 2)
  15638. (string-to-number (match-string 2 ans))
  15639. (progn (setq kill-year t)
  15640. (string-to-number (format-time-string "%Y"))))
  15641. month (string-to-number (match-string 3 ans))
  15642. day (string-to-number (match-string 4 ans)))
  15643. (setq year (org-small-year-to-year year))
  15644. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15645. t nil ans)))
  15646. ;; Help matching dotted european dates
  15647. (when (string-match
  15648. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15649. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15650. (setq kill-year t)
  15651. (string-to-number (format-time-string "%Y")))
  15652. day (string-to-number (match-string 1 ans))
  15653. month (string-to-number (match-string 2 ans))
  15654. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15655. t nil ans)))
  15656. ;; Help matching american dates, like 5/30 or 5/30/7
  15657. (when (string-match
  15658. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15659. (setq year (if (match-end 4)
  15660. (string-to-number (match-string 4 ans))
  15661. (progn (setq kill-year t)
  15662. (string-to-number (format-time-string "%Y"))))
  15663. month (string-to-number (match-string 1 ans))
  15664. day (string-to-number (match-string 2 ans)))
  15665. (setq year (org-small-year-to-year year))
  15666. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15667. t nil ans)))
  15668. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15669. ;; If there is a time with am/pm, and *no* time without it, we convert
  15670. ;; so that matching will be successful.
  15671. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15672. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15673. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15674. (setq hour (string-to-number (match-string 1 ans))
  15675. minute (if (match-end 3)
  15676. (string-to-number (match-string 3 ans))
  15677. 0)
  15678. pm (equal ?p
  15679. (string-to-char (downcase (match-string 4 ans)))))
  15680. (if (and (= hour 12) (not pm))
  15681. (setq hour 0)
  15682. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15683. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15684. t t ans))))
  15685. ;; Check if a time range is given as a duration
  15686. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15687. (setq hour (string-to-number (match-string 1 ans))
  15688. h2 (+ hour (string-to-number (match-string 3 ans)))
  15689. minute (string-to-number (match-string 2 ans))
  15690. m2 (+ minute (if (match-end 5) (string-to-number
  15691. (match-string 5 ans))0)))
  15692. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15693. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15694. t t ans)))
  15695. ;; Check if there is a time range
  15696. (when (boundp 'org-end-time-was-given)
  15697. (setq org-time-was-given nil)
  15698. (when (and (string-match org-plain-time-of-day-regexp ans)
  15699. (match-end 8))
  15700. (setq org-end-time-was-given (match-string 8 ans))
  15701. (setq ans (concat (substring ans 0 (match-beginning 7))
  15702. (substring ans (match-end 7))))))
  15703. (setq tl (parse-time-string ans)
  15704. day (or (nth 3 tl) (nth 3 org-defdecode))
  15705. month
  15706. (cond ((nth 4 tl))
  15707. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15708. ;; Day was specified. Make sure DAY+MONTH
  15709. ;; combination happens in the future.
  15710. ((nth 3 tl)
  15711. (setq futurep t)
  15712. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15713. (nth 4 nowdecode)))
  15714. (t (nth 4 org-defdecode)))
  15715. year
  15716. (cond ((and (not kill-year) (nth 5 tl)))
  15717. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15718. ;; Month was guessed in the future and is at least
  15719. ;; equal to NOWDECODE's. Fix year accordingly.
  15720. (futurep
  15721. (if (or (> month (nth 4 nowdecode))
  15722. (>= day (nth 3 nowdecode)))
  15723. (nth 5 nowdecode)
  15724. (1+ (nth 5 nowdecode))))
  15725. ;; Month was specified. Make sure MONTH+YEAR
  15726. ;; combination happens in the future.
  15727. ((nth 4 tl)
  15728. (setq futurep t)
  15729. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15730. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15731. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15732. (t (nth 5 nowdecode))))
  15733. (t (nth 5 org-defdecode)))
  15734. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15735. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15736. second (or (nth 0 tl) 0)
  15737. wday (nth 6 tl))
  15738. (when (and (eq org-read-date-prefer-future 'time)
  15739. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15740. (equal day (nth 3 nowdecode))
  15741. (equal month (nth 4 nowdecode))
  15742. (equal year (nth 5 nowdecode))
  15743. (nth 2 tl)
  15744. (or (< (nth 2 tl) (nth 2 nowdecode))
  15745. (and (= (nth 2 tl) (nth 2 nowdecode))
  15746. (nth 1 tl)
  15747. (< (nth 1 tl) (nth 1 nowdecode)))))
  15748. (setq day (1+ day)
  15749. futurep t))
  15750. ;; Special date definitions below
  15751. (cond
  15752. (iso-week
  15753. ;; There was an iso week
  15754. (require 'cal-iso)
  15755. (setq futurep nil)
  15756. (setq year (or iso-year year)
  15757. day (or iso-weekday wday 1)
  15758. wday nil ; to make sure that the trigger below does not match
  15759. iso-date (calendar-gregorian-from-absolute
  15760. (calendar-iso-to-absolute
  15761. (list iso-week day year))))
  15762. ; FIXME: Should we also push ISO weeks into the future?
  15763. ; (when (and org-read-date-prefer-future
  15764. ; (not iso-year)
  15765. ; (< (calendar-absolute-from-gregorian iso-date)
  15766. ; (time-to-days (current-time))))
  15767. ; (setq year (1+ year)
  15768. ; iso-date (calendar-gregorian-from-absolute
  15769. ; (calendar-iso-to-absolute
  15770. ; (list iso-week day year)))))
  15771. (setq month (car iso-date)
  15772. year (nth 2 iso-date)
  15773. day (nth 1 iso-date)))
  15774. (deltan
  15775. (setq futurep nil)
  15776. (unless deltadef
  15777. ;; Pass `current-time' result to `decode-time' (instead of
  15778. ;; calling without arguments) so that only `current-time' has
  15779. ;; to be overriden in tests.
  15780. (let ((now (decode-time (current-time))))
  15781. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15782. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15783. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15784. ((equal deltaw "m") (setq month (+ month deltan)))
  15785. ((equal deltaw "y") (setq year (+ year deltan)))))
  15786. ((and wday (not (nth 3 tl)))
  15787. ;; Weekday was given, but no day, so pick that day in the week
  15788. ;; on or after the derived date.
  15789. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15790. (unless (equal wday wday1)
  15791. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15792. (when (and (boundp 'org-time-was-given)
  15793. (nth 2 tl))
  15794. (setq org-time-was-given t))
  15795. (when (< year 100) (setq year (+ 2000 year)))
  15796. ;; Check of the date is representable
  15797. (if org-read-date-force-compatible-dates
  15798. (progn
  15799. (when (< year 1970)
  15800. (setq year 1970 org-read-date-analyze-forced-year t))
  15801. (when (> year 2037)
  15802. (setq year 2037 org-read-date-analyze-forced-year t)))
  15803. (condition-case nil
  15804. (ignore (encode-time second minute hour day month year))
  15805. (error
  15806. (setq year (nth 5 org-defdecode))
  15807. (setq org-read-date-analyze-forced-year t))))
  15808. (setq org-read-date-analyze-futurep futurep)
  15809. (list second minute hour day month year)))
  15810. (defvar parse-time-weekdays)
  15811. (defun org-read-date-get-relative (s today default)
  15812. "Check string S for special relative date string.
  15813. TODAY and DEFAULT are internal times, for today and for a default.
  15814. Return shift list (N what def-flag)
  15815. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15816. N is the number of WHATs to shift.
  15817. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15818. the DEFAULT date rather than TODAY."
  15819. (require 'parse-time)
  15820. (when (and
  15821. (string-match
  15822. (concat
  15823. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15824. "\\([0-9]+\\)?"
  15825. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15826. "\\([ \t]\\|$\\)") s)
  15827. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15828. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15829. (string-to-char (substring (match-string 1 s) -1))
  15830. ?+))
  15831. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15832. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15833. (what (if (match-end 3) (match-string 3 s) "d"))
  15834. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15835. (date (if rel default today))
  15836. (wday (nth 6 (decode-time date)))
  15837. delta)
  15838. (if wday1
  15839. (progn
  15840. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15841. (when (= delta 0) (setq delta 7))
  15842. (when (= dir ?-)
  15843. (setq delta (- delta 7))
  15844. (when (= delta 0) (setq delta -7)))
  15845. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15846. (list delta "d" rel))
  15847. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15848. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15849. "Turn a user-specified date into the internal representation.
  15850. The internal representation needed by the calendar is (month day year).
  15851. This is a wrapper to handle the brain-dead convention in calendar that
  15852. user function argument order change dependent on argument order."
  15853. (pcase calendar-date-style
  15854. (`american (list arg1 arg2 arg3))
  15855. (`european (list arg2 arg1 arg3))
  15856. (`iso (list arg2 arg3 arg1))))
  15857. (defun org-eval-in-calendar (form &optional keepdate)
  15858. "Eval FORM in the calendar window and return to current window.
  15859. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15860. (let ((sf (selected-frame))
  15861. (sw (selected-window)))
  15862. (select-window (get-buffer-window "*Calendar*" t))
  15863. (eval form)
  15864. (when (and (not keepdate) (calendar-cursor-to-date))
  15865. (let* ((date (calendar-cursor-to-date))
  15866. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15867. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15868. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15869. (select-window sw)
  15870. (select-frame-set-input-focus sf)))
  15871. (defun org-calendar-select ()
  15872. "Return to `org-read-date' with the date currently selected.
  15873. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15874. (interactive)
  15875. (when (calendar-cursor-to-date)
  15876. (let* ((date (calendar-cursor-to-date))
  15877. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15878. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15879. (when (active-minibuffer-window) (exit-minibuffer))))
  15880. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15881. "Insert a date stamp for the date given by the internal TIME.
  15882. See `format-time-string' for the format of TIME.
  15883. WITH-HM means use the stamp format that includes the time of the day.
  15884. INACTIVE means use square brackets instead of angular ones, so that the
  15885. stamp will not contribute to the agenda.
  15886. PRE and POST are optional strings to be inserted before and after the
  15887. stamp.
  15888. The command returns the inserted time stamp."
  15889. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15890. stamp)
  15891. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15892. (insert-before-markers (or pre ""))
  15893. (when (listp extra)
  15894. (setq extra (car extra))
  15895. (if (and (stringp extra)
  15896. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15897. (setq extra (format "-%02d:%02d"
  15898. (string-to-number (match-string 1 extra))
  15899. (string-to-number (match-string 2 extra))))
  15900. (setq extra nil)))
  15901. (when extra
  15902. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15903. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15904. (insert-before-markers (or post ""))
  15905. (setq org-last-inserted-timestamp stamp)))
  15906. (defun org-toggle-time-stamp-overlays ()
  15907. "Toggle the use of custom time stamp formats."
  15908. (interactive)
  15909. (setq org-display-custom-times (not org-display-custom-times))
  15910. (unless org-display-custom-times
  15911. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15912. (while (setq p (next-single-property-change p 'display))
  15913. (when (and (get-text-property p 'display)
  15914. (eq (get-text-property p 'face) 'org-date))
  15915. (remove-text-properties
  15916. p (setq p (next-single-property-change p 'display))
  15917. '(display t))))
  15918. (set-buffer-modified-p bmp)))
  15919. (org-restart-font-lock)
  15920. (setq org-table-may-need-update t)
  15921. (if org-display-custom-times
  15922. (message "Time stamps are overlaid with custom format")
  15923. (message "Time stamp overlays removed")))
  15924. (defun org-display-custom-time (beg end)
  15925. "Overlay modified time stamp format over timestamp between BEG and END."
  15926. (let* ((ts (buffer-substring beg end))
  15927. t1 w1 with-hm tf time str w2 (off 0))
  15928. (save-match-data
  15929. (setq t1 (org-parse-time-string ts t))
  15930. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15931. (setq off (- (match-end 0) (match-beginning 0)))))
  15932. (setq end (- end off))
  15933. (setq w1 (- end beg)
  15934. with-hm (and (nth 1 t1) (nth 2 t1))
  15935. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15936. time (org-fix-decoded-time t1)
  15937. str (org-add-props
  15938. (format-time-string
  15939. (substring tf 1 -1) (apply 'encode-time time))
  15940. nil 'mouse-face 'highlight)
  15941. w2 (length str))
  15942. (unless (= w2 w1)
  15943. (add-text-properties (1+ beg) (+ 2 beg)
  15944. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15945. (put-text-property beg end 'display str)))
  15946. (defun org-fix-decoded-time (time)
  15947. "Set 0 instead of nil for the first 6 elements of time.
  15948. Don't touch the rest."
  15949. (let ((n 0))
  15950. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15951. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15952. "Difference between TIMESTAMP-STRING and now in days.
  15953. If SECONDS is non-nil, return the difference in seconds."
  15954. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15955. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15956. (funcall fdiff (current-time)))))
  15957. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15958. "Is the time in TIMESTAMP-STRING close to the current date?"
  15959. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15960. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15961. (not (org-entry-is-done-p))))
  15962. (defun org-get-wdays (ts &optional delay zero-delay)
  15963. "Get the deadline lead time appropriate for timestring TS.
  15964. When DELAY is non-nil, get the delay time for scheduled items
  15965. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15966. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15967. don't try to find the delay cookie in the scheduled timestamp."
  15968. (let ((tv (if delay org-scheduled-delay-days
  15969. org-deadline-warning-days)))
  15970. (cond
  15971. ((or (and delay (< tv 0))
  15972. (and delay zero-delay (<= tv 0))
  15973. (and (not delay) (<= tv 0)))
  15974. ;; Enforce this value no matter what
  15975. (- tv))
  15976. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15977. ;; lead time is specified.
  15978. (floor (* (string-to-number (match-string 1 ts))
  15979. (cdr (assoc (match-string 2 ts)
  15980. '(("d" . 1) ("w" . 7)
  15981. ("m" . 30.4) ("y" . 365.25)
  15982. ("h" . 0.041667)))))))
  15983. ;; go for the default.
  15984. (t tv))))
  15985. (defun org-calendar-select-mouse (ev)
  15986. "Return to `org-read-date' with the date currently selected.
  15987. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15988. (interactive "e")
  15989. (mouse-set-point ev)
  15990. (when (calendar-cursor-to-date)
  15991. (let* ((date (calendar-cursor-to-date))
  15992. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15993. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15994. (when (active-minibuffer-window) (exit-minibuffer))))
  15995. (defun org-check-deadlines (ndays)
  15996. "Check if there are any deadlines due or past due.
  15997. A deadline is considered due if it happens within `org-deadline-warning-days'
  15998. days from today's date. If the deadline appears in an entry marked DONE,
  15999. it is not shown. The prefix arg NDAYS can be used to test that many
  16000. days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
  16001. (interactive "P")
  16002. (let* ((org-warn-days
  16003. (cond
  16004. ((equal ndays '(4)) 100000)
  16005. (ndays (prefix-numeric-value ndays))
  16006. (t (abs org-deadline-warning-days))))
  16007. (case-fold-search nil)
  16008. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16009. (callback
  16010. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16011. (message "%d deadlines past-due or due within %d days"
  16012. (org-occur regexp nil callback)
  16013. org-warn-days)))
  16014. (defsubst org-re-timestamp (type)
  16015. "Return a regexp for timestamp TYPE.
  16016. Allowed values for TYPE are:
  16017. all: all timestamps
  16018. active: only active timestamps (<...>)
  16019. inactive: only inactive timestamps ([...])
  16020. scheduled: only scheduled timestamps
  16021. deadline: only deadline timestamps
  16022. closed: only closed time-stamps
  16023. When TYPE is nil, fall back on returning a regexp that matches
  16024. both scheduled and deadline timestamps."
  16025. (cl-case type
  16026. (all org-ts-regexp-both)
  16027. (active org-ts-regexp)
  16028. (inactive org-ts-regexp-inactive)
  16029. (scheduled org-scheduled-time-regexp)
  16030. (deadline org-deadline-time-regexp)
  16031. (closed org-closed-time-regexp)
  16032. (otherwise
  16033. (concat "\\<"
  16034. (regexp-opt (list org-deadline-string org-scheduled-string))
  16035. " *<\\([^>]+\\)>"))))
  16036. (defun org-check-before-date (d)
  16037. "Check if there are deadlines or scheduled entries before date D."
  16038. (interactive (list (org-read-date)))
  16039. (let* ((case-fold-search nil)
  16040. (regexp (org-re-timestamp org-ts-type))
  16041. (ts-type org-ts-type)
  16042. (callback
  16043. (lambda ()
  16044. (let ((match (match-string 1)))
  16045. (and (if (memq ts-type '(active inactive all))
  16046. (eq (org-element-type (save-excursion
  16047. (backward-char)
  16048. (org-element-context)))
  16049. 'timestamp)
  16050. (org-at-planning-p))
  16051. (time-less-p
  16052. (org-time-string-to-time match)
  16053. (org-time-string-to-time d)))))))
  16054. (message "%d entries before %s"
  16055. (org-occur regexp nil callback)
  16056. d)))
  16057. (defun org-check-after-date (d)
  16058. "Check if there are deadlines or scheduled entries after date D."
  16059. (interactive (list (org-read-date)))
  16060. (let* ((case-fold-search nil)
  16061. (regexp (org-re-timestamp org-ts-type))
  16062. (ts-type org-ts-type)
  16063. (callback
  16064. (lambda ()
  16065. (let ((match (match-string 1)))
  16066. (and (if (memq ts-type '(active inactive all))
  16067. (eq (org-element-type (save-excursion
  16068. (backward-char)
  16069. (org-element-context)))
  16070. 'timestamp)
  16071. (org-at-planning-p))
  16072. (not (time-less-p
  16073. (org-time-string-to-time match)
  16074. (org-time-string-to-time d))))))))
  16075. (message "%d entries after %s"
  16076. (org-occur regexp nil callback)
  16077. d)))
  16078. (defun org-check-dates-range (start-date end-date)
  16079. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16080. (interactive (list (org-read-date nil nil nil "Range starts")
  16081. (org-read-date nil nil nil "Range end")))
  16082. (let ((case-fold-search nil)
  16083. (regexp (org-re-timestamp org-ts-type))
  16084. (callback
  16085. (let ((type org-ts-type))
  16086. (lambda ()
  16087. (let ((match (match-string 1)))
  16088. (and
  16089. (if (memq type '(active inactive all))
  16090. (eq (org-element-type (save-excursion
  16091. (backward-char)
  16092. (org-element-context)))
  16093. 'timestamp)
  16094. (org-at-planning-p))
  16095. (not (time-less-p
  16096. (org-time-string-to-time match)
  16097. (org-time-string-to-time start-date)))
  16098. (time-less-p
  16099. (org-time-string-to-time match)
  16100. (org-time-string-to-time end-date))))))))
  16101. (message "%d entries between %s and %s"
  16102. (org-occur regexp nil callback) start-date end-date)))
  16103. (defun org-evaluate-time-range (&optional to-buffer)
  16104. "Evaluate a time range by computing the difference between start and end.
  16105. Normally the result is just printed in the echo area, but with prefix arg
  16106. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16107. If the time range is actually in a table, the result is inserted into the
  16108. next column.
  16109. For time difference computation, a year is assumed to be exactly 365
  16110. days in order to avoid rounding problems."
  16111. (interactive "P")
  16112. (or
  16113. (org-clock-update-time-maybe)
  16114. (save-excursion
  16115. (unless (org-at-date-range-p t)
  16116. (goto-char (point-at-bol))
  16117. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16118. (unless (org-at-date-range-p t)
  16119. (user-error "Not at a time-stamp range, and none found in current line")))
  16120. (let* ((ts1 (match-string 1))
  16121. (ts2 (match-string 2))
  16122. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16123. (match-end (match-end 0))
  16124. (time1 (org-time-string-to-time ts1))
  16125. (time2 (org-time-string-to-time ts2))
  16126. (t1 (float-time time1))
  16127. (t2 (float-time time2))
  16128. (diff (abs (- t2 t1)))
  16129. (negative (< (- t2 t1) 0))
  16130. ;; (ys (floor (* 365 24 60 60)))
  16131. (ds (* 24 60 60))
  16132. (hs (* 60 60))
  16133. (fy "%dy %dd %02d:%02d")
  16134. (fy1 "%dy %dd")
  16135. (fd "%dd %02d:%02d")
  16136. (fd1 "%dd")
  16137. (fh "%02d:%02d")
  16138. y d h m align)
  16139. (if havetime
  16140. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16141. y 0
  16142. d (floor (/ diff ds)) diff (mod diff ds)
  16143. h (floor (/ diff hs)) diff (mod diff hs)
  16144. m (floor (/ diff 60)))
  16145. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16146. y 0
  16147. d (floor (+ (/ diff ds) 0.5))
  16148. h 0 m 0))
  16149. (if (not to-buffer)
  16150. (message "%s" (org-make-tdiff-string y d h m))
  16151. (if (org-at-table-p)
  16152. (progn
  16153. (goto-char match-end)
  16154. (setq align t)
  16155. (and (looking-at " *|") (goto-char (match-end 0))))
  16156. (goto-char match-end))
  16157. (when (looking-at
  16158. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16159. (replace-match ""))
  16160. (when negative (insert " -"))
  16161. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16162. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16163. (insert " " (format fh h m))))
  16164. (when align (org-table-align))
  16165. (message "Time difference inserted")))))
  16166. (defun org-make-tdiff-string (y d h m)
  16167. (let ((fmt "")
  16168. (l nil))
  16169. (when (> y 0)
  16170. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16171. (push y l))
  16172. (when (> d 0)
  16173. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16174. (push d l))
  16175. (when (> h 0)
  16176. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16177. (push h l))
  16178. (when (> m 0)
  16179. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16180. (push m l))
  16181. (apply 'format fmt (nreverse l))))
  16182. (defun org-time-string-to-time (s &optional buffer pos)
  16183. "Convert a timestamp string into internal time."
  16184. (condition-case errdata
  16185. (apply 'encode-time (org-parse-time-string s))
  16186. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16187. s (if (not (and buffer pos))
  16188. ""
  16189. (format-message " at %d in buffer `%s'" pos buffer))
  16190. (cdr errdata)))))
  16191. (defun org-time-string-to-seconds (s)
  16192. "Convert a timestamp string to a number of seconds."
  16193. (float-time (org-time-string-to-time s)))
  16194. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16195. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16196. "Convert time stamp S to an absolute day number.
  16197. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16198. stamp, get the closest date to DAYNR. If PREFER is
  16199. `past' (respectively `future') return a date past (respectively
  16200. after) or equal to DAYNR.
  16201. POS is the location of time stamp S, as a buffer position in
  16202. BUFFER.
  16203. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16204. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16205. signalled."
  16206. (cond
  16207. ((string-match "\\`%%\\((.*)\\)" s)
  16208. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16209. ;; only able to match individual dates. If it fails, raise an
  16210. ;; error.
  16211. (if (and daynr
  16212. (org-diary-sexp-entry
  16213. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16214. daynr
  16215. (signal 'org-diary-sexp-no-match (list s))))
  16216. ((and daynr show-all) (org-closest-date s daynr prefer))
  16217. (t (time-to-days
  16218. (condition-case errdata
  16219. (apply #'encode-time (org-parse-time-string s))
  16220. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16221. s
  16222. (if (not (and buffer pos)) ""
  16223. (format-message " at %d in buffer `%s'" pos buffer))
  16224. (cdr errdata))))))))
  16225. (defun org-days-to-iso-week (days)
  16226. "Return the iso week number."
  16227. (require 'cal-iso)
  16228. (car (calendar-iso-from-absolute days)))
  16229. (defun org-small-year-to-year (year)
  16230. "Convert 2-digit years into 4-digit years.
  16231. YEAR is expanded into one of the 30 next years, if possible, or
  16232. into a past one. Any year larger than 99 is returned unchanged."
  16233. (if (>= year 100) year
  16234. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16235. (century (/ current 100))
  16236. (offset (- year (% current 100))))
  16237. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16238. ((> offset -70) (+ (* century 100) year))
  16239. (t (+ (* (1+ century) 100) year))))))
  16240. (defun org-time-from-absolute (d)
  16241. "Return the time corresponding to date D.
  16242. D may be an absolute day number, or a calendar-type list (month day year)."
  16243. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16244. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16245. (defvar org-agenda-current-date)
  16246. (defun org-calendar-holiday ()
  16247. "List of holidays, for Diary display in Org mode."
  16248. (require 'holidays)
  16249. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16250. (and hl (mapconcat #'identity hl "; "))))
  16251. (defun org-diary-sexp-entry (sexp entry d)
  16252. "Process a SEXP diary ENTRY for date D."
  16253. (require 'diary-lib)
  16254. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16255. ;; dynamically.
  16256. (let* ((sexp `(let ((entry ,entry)
  16257. (date ',d))
  16258. ,(car (read-from-string sexp))))
  16259. (result (if calendar-debug-sexp (eval sexp)
  16260. (condition-case nil
  16261. (eval sexp)
  16262. (error
  16263. (beep)
  16264. (message "Bad sexp at line %d in %s: %s"
  16265. (org-current-line)
  16266. (buffer-file-name) sexp)
  16267. (sleep-for 2))))))
  16268. (cond ((stringp result) (split-string result "; "))
  16269. ((and (consp result)
  16270. (not (consp (cdr result)))
  16271. (stringp (cdr result))) (cdr result))
  16272. ((and (consp result)
  16273. (stringp (car result))) result)
  16274. (result entry))))
  16275. (defun org-diary-to-ical-string (frombuf)
  16276. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16277. This uses the icalendar.el library."
  16278. (let* ((tmpdir temporary-file-directory)
  16279. (tmpfile (make-temp-name
  16280. (expand-file-name "orgics" tmpdir)))
  16281. buf rtn b e)
  16282. (with-current-buffer frombuf
  16283. (icalendar-export-region (point-min) (point-max) tmpfile)
  16284. (setq buf (find-buffer-visiting tmpfile))
  16285. (set-buffer buf)
  16286. (goto-char (point-min))
  16287. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16288. (setq b (match-beginning 0)))
  16289. (goto-char (point-max))
  16290. (when (re-search-backward "^END:VEVENT" nil t)
  16291. (setq e (match-end 0)))
  16292. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16293. (kill-buffer buf)
  16294. (delete-file tmpfile)
  16295. rtn))
  16296. (defun org-closest-date (start current prefer)
  16297. "Return closest date to CURRENT starting from START.
  16298. CURRENT and START are both time stamps.
  16299. When PREFER is `past', return a date that is either CURRENT or
  16300. past. When PREFER is `future', return a date that is either
  16301. CURRENT or future.
  16302. Only time stamps with a repeater are modified. Any other time
  16303. stamp stay unchanged. In any case, return value is an absolute
  16304. day number."
  16305. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16306. ;; No repeater. Do not shift time stamp.
  16307. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16308. (let ((value (string-to-number (match-string 1 start)))
  16309. (type (match-string 2 start)))
  16310. (if (= 0 value)
  16311. ;; Repeater with a 0-value is considered as void.
  16312. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16313. (let* ((base (org-date-to-gregorian start))
  16314. (target (org-date-to-gregorian current))
  16315. (sday (calendar-absolute-from-gregorian base))
  16316. (cday (calendar-absolute-from-gregorian target))
  16317. n1 n2)
  16318. ;; If START is already past CURRENT, just return START.
  16319. (if (<= cday sday) sday
  16320. ;; Compute closest date before (N1) and closest date past
  16321. ;; (N2) CURRENT.
  16322. (pcase type
  16323. ("h"
  16324. (let ((missing-hours
  16325. (mod (+ (- (* 24 (- cday sday))
  16326. (nth 2 (org-parse-time-string start)))
  16327. org-extend-today-until)
  16328. value)))
  16329. (setf n1 (if (= missing-hours 0) cday
  16330. (- cday (1+ (/ missing-hours 24)))))
  16331. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16332. ((or "d" "w")
  16333. (let ((value (if (equal type "w") (* 7 value) value)))
  16334. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16335. (setf n2 (+ n1 value))))
  16336. ("m"
  16337. (let* ((add-months
  16338. (lambda (d n)
  16339. ;; Add N months to gregorian date D, i.e.,
  16340. ;; a list (MONTH DAY YEAR). Return a valid
  16341. ;; gregorian date.
  16342. (let ((m (+ (nth 0 d) n)))
  16343. (list (mod m 12)
  16344. (nth 1 d)
  16345. (+ (/ m 12) (nth 2 d))))))
  16346. (months ; Complete months to TARGET.
  16347. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16348. (- (nth 0 target) (nth 0 base))
  16349. ;; If START's day is greater than
  16350. ;; TARGET's, remove incomplete month.
  16351. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16352. value)
  16353. value))
  16354. (before (funcall add-months base months)))
  16355. (setf n1 (calendar-absolute-from-gregorian before))
  16356. (setf n2
  16357. (calendar-absolute-from-gregorian
  16358. (funcall add-months before value)))))
  16359. (_
  16360. (let* ((d (nth 1 base))
  16361. (m (nth 0 base))
  16362. (y (nth 2 base))
  16363. (years ; Complete years to TARGET.
  16364. (* (/ (- (nth 2 target)
  16365. y
  16366. ;; If START's month and day are
  16367. ;; greater than TARGET's, remove
  16368. ;; incomplete year.
  16369. (if (or (> (nth 0 target) m)
  16370. (and (= (nth 0 target) m)
  16371. (> (nth 1 target) d)))
  16372. 0
  16373. 1))
  16374. value)
  16375. value))
  16376. (before (list m d (+ y years))))
  16377. (setf n1 (calendar-absolute-from-gregorian before))
  16378. (setf n2 (calendar-absolute-from-gregorian
  16379. (list m d (+ (nth 2 before) value)))))))
  16380. ;; Handle PREFER parameter, if any.
  16381. (cond
  16382. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16383. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16384. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16385. (defun org-date-to-gregorian (d)
  16386. "Turn any specification of date D into a Gregorian date for the calendar."
  16387. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16388. ((and (listp d) (= (length d) 3)) d)
  16389. ((stringp d)
  16390. (let ((d (org-parse-time-string d)))
  16391. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16392. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16393. (defun org-parse-time-string (s &optional nodefault)
  16394. "Parse the standard Org time string.
  16395. This should be a lot faster than the normal `parse-time-string'.
  16396. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16397. hour and minute fields will be nil if not given."
  16398. (cond ((string-match org-ts-regexp0 s)
  16399. (list 0
  16400. (when (or (match-beginning 8) (not nodefault))
  16401. (string-to-number (or (match-string 8 s) "0")))
  16402. (when (or (match-beginning 7) (not nodefault))
  16403. (string-to-number (or (match-string 7 s) "0")))
  16404. (string-to-number (match-string 4 s))
  16405. (string-to-number (match-string 3 s))
  16406. (string-to-number (match-string 2 s))
  16407. nil nil nil))
  16408. ((string-match "^<[^>]+>$" s)
  16409. (decode-time (seconds-to-time (org-matcher-time s))))
  16410. (t (error "Not a standard Org time string: %s" s))))
  16411. (defun org-timestamp-up (&optional arg)
  16412. "Increase the date item at the cursor by one.
  16413. If the cursor is on the year, change the year. If it is on the month,
  16414. the day or the time, change that.
  16415. With prefix ARG, change by that many units."
  16416. (interactive "p")
  16417. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16418. (defun org-timestamp-down (&optional arg)
  16419. "Decrease the date item at the cursor by one.
  16420. If the cursor is on the year, change the year. If it is on the month,
  16421. the day or the time, change that.
  16422. With prefix ARG, change by that many units."
  16423. (interactive "p")
  16424. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16425. (defun org-timestamp-up-day (&optional arg)
  16426. "Increase the date in the time stamp by one day.
  16427. With prefix ARG, change that many days."
  16428. (interactive "p")
  16429. (if (and (not (org-at-timestamp-p t))
  16430. (org-at-heading-p))
  16431. (org-todo 'up)
  16432. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16433. (defun org-timestamp-down-day (&optional arg)
  16434. "Decrease the date in the time stamp by one day.
  16435. With prefix ARG, change that many days."
  16436. (interactive "p")
  16437. (if (and (not (org-at-timestamp-p t))
  16438. (org-at-heading-p))
  16439. (org-todo 'down)
  16440. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16441. (defun org-at-timestamp-p (&optional inactive-ok)
  16442. "Non-nil if point is inside a timestamp.
  16443. When optional argument INACTIVE-OK is non-nil, also consider
  16444. inactive timestamps.
  16445. When this function returns a non-nil value, match data is set
  16446. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16447. INACTIVE-OK."
  16448. (interactive)
  16449. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16450. (pos (point))
  16451. (ans (or (looking-at tsr)
  16452. (save-excursion
  16453. (skip-chars-backward "^[<\n\r\t")
  16454. (when (> (point) (point-min)) (backward-char 1))
  16455. (and (looking-at tsr)
  16456. (> (- (match-end 0) pos) -1))))))
  16457. (and ans
  16458. (boundp 'org-ts-what)
  16459. (setq org-ts-what
  16460. (cond
  16461. ((= pos (match-beginning 0)) 'bracket)
  16462. ;; Point is considered to be "on the bracket" whether
  16463. ;; it's really on it or right after it.
  16464. ((= pos (1- (match-end 0))) 'bracket)
  16465. ((= pos (match-end 0)) 'after)
  16466. ((org-pos-in-match-range pos 2) 'year)
  16467. ((org-pos-in-match-range pos 3) 'month)
  16468. ((org-pos-in-match-range pos 7) 'hour)
  16469. ((org-pos-in-match-range pos 8) 'minute)
  16470. ((or (org-pos-in-match-range pos 4)
  16471. (org-pos-in-match-range pos 5)) 'day)
  16472. ((and (> pos (or (match-end 8) (match-end 5)))
  16473. (< pos (match-end 0)))
  16474. (- pos (or (match-end 8) (match-end 5))))
  16475. (t 'day))))
  16476. ans))
  16477. (defun org-toggle-timestamp-type ()
  16478. "Toggle the type (<active> or [inactive]) of a time stamp."
  16479. (interactive)
  16480. (when (org-at-timestamp-p t)
  16481. (let ((beg (match-beginning 0)) (end (match-end 0))
  16482. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16483. (save-excursion
  16484. (goto-char beg)
  16485. (while (re-search-forward "[][<>]" end t)
  16486. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16487. t t)))
  16488. (message "Timestamp is now %sactive"
  16489. (if (equal (char-after beg) ?<) "" "in")))))
  16490. (defun org-at-clock-log-p nil
  16491. "Is the cursor on the clock log line?"
  16492. (save-excursion
  16493. (move-beginning-of-line 1)
  16494. (looking-at org-clock-line-re)))
  16495. (defvar org-clock-history) ; defined in org-clock.el
  16496. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16497. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16498. "Change the date in the time stamp at point.
  16499. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16500. `year', `minute', `second'. If WHAT is not given, the cursor position
  16501. in the timestamp determines what will be changed.
  16502. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16503. (let ((origin (point)) origin-cat
  16504. with-hm inactive
  16505. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16506. org-ts-what
  16507. extra rem
  16508. ts time time0 fixnext clrgx)
  16509. (unless (org-at-timestamp-p t)
  16510. (user-error "Not at a timestamp"))
  16511. (if (and (not what) (eq org-ts-what 'bracket))
  16512. (org-toggle-timestamp-type)
  16513. ;; Point isn't on brackets. Remember the part of the time-stamp
  16514. ;; the point was in. Indeed, size of time-stamps may change,
  16515. ;; but point must be kept in the same category nonetheless.
  16516. (setq origin-cat org-ts-what)
  16517. (when (and (not what) (not (eq org-ts-what 'day))
  16518. org-display-custom-times
  16519. (get-text-property (point) 'display)
  16520. (not (get-text-property (1- (point)) 'display)))
  16521. (setq org-ts-what 'day))
  16522. (setq org-ts-what (or what org-ts-what)
  16523. inactive (= (char-after (match-beginning 0)) ?\[)
  16524. ts (match-string 0))
  16525. (replace-match "")
  16526. (when (string-match
  16527. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16528. ts)
  16529. (setq extra (match-string 1 ts))
  16530. (when suppress-tmp-delay
  16531. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16532. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16533. (setq with-hm t))
  16534. (setq time0 (org-parse-time-string ts))
  16535. (when (and updown
  16536. (eq org-ts-what 'minute)
  16537. (not current-prefix-arg))
  16538. ;; This looks like s-up and s-down. Change by one rounding step.
  16539. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16540. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16541. (setcar (cdr time0) (+ (nth 1 time0)
  16542. (if (> n 0) (- rem) (- dm rem))))))
  16543. (setq time
  16544. (apply #'encode-time
  16545. (or (car time0) 0)
  16546. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16547. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16548. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16549. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16550. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16551. (nthcdr 6 time0)))
  16552. (when (and (member org-ts-what '(hour minute))
  16553. extra
  16554. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16555. (setq extra (org-modify-ts-extra
  16556. extra
  16557. (if (eq org-ts-what 'hour) 2 5)
  16558. n dm)))
  16559. (when (integerp org-ts-what)
  16560. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16561. (when (eq what 'calendar)
  16562. (let ((cal-date (org-get-date-from-calendar)))
  16563. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16564. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16565. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16566. (setcar time0 (or (car time0) 0))
  16567. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16568. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16569. (setq time (apply 'encode-time time0))))
  16570. ;; Insert the new time-stamp, and ensure point stays in the same
  16571. ;; category as before (i.e. not after the last position in that
  16572. ;; category).
  16573. (let ((pos (point)))
  16574. ;; Stay before inserted string. `save-excursion' is of no use.
  16575. (setq org-last-changed-timestamp
  16576. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16577. (goto-char pos))
  16578. (save-match-data
  16579. (looking-at org-ts-regexp3)
  16580. (goto-char (cond
  16581. ;; `day' category ends before `hour' if any, or at
  16582. ;; the end of the day name.
  16583. ((eq origin-cat 'day)
  16584. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16585. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16586. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16587. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16588. ;; `year' and `month' have both fixed size: point
  16589. ;; couldn't have moved into another part.
  16590. (t origin))))
  16591. ;; Update clock if on a CLOCK line.
  16592. (org-clock-update-time-maybe)
  16593. ;; Maybe adjust the closest clock in `org-clock-history'
  16594. (when org-clock-adjust-closest
  16595. (if (not (and (org-at-clock-log-p)
  16596. (< 1 (length (delq nil (mapcar 'marker-position
  16597. org-clock-history))))))
  16598. (message "No clock to adjust")
  16599. (cond ((save-excursion ; fix previous clock?
  16600. (re-search-backward org-ts-regexp0 nil t)
  16601. (looking-back (concat org-clock-string " \\[")
  16602. (line-beginning-position)))
  16603. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16604. ((save-excursion ; fix next clock?
  16605. (re-search-backward org-ts-regexp0 nil t)
  16606. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16607. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16608. (save-window-excursion
  16609. ;; Find closest clock to point, adjust the previous/next one in history
  16610. (let* ((p (save-excursion (org-back-to-heading t)))
  16611. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16612. (clfixnth
  16613. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16614. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16615. (if (not clfixpos)
  16616. (message "No clock to adjust")
  16617. (save-excursion
  16618. (org-goto-marker-or-bmk clfixpos)
  16619. (org-show-subtree)
  16620. (when (re-search-forward clrgx nil t)
  16621. (goto-char (match-beginning 1))
  16622. (let (org-clock-adjust-closest)
  16623. (org-timestamp-change n org-ts-what updown))
  16624. (message "Clock adjusted in %s for heading: %s"
  16625. (file-name-nondirectory (buffer-file-name))
  16626. (org-get-heading t t)))))))))
  16627. ;; Try to recenter the calendar window, if any.
  16628. (when (and org-calendar-follow-timestamp-change
  16629. (get-buffer-window "*Calendar*" t)
  16630. (memq org-ts-what '(day month year)))
  16631. (org-recenter-calendar (time-to-days time))))))
  16632. (defun org-modify-ts-extra (s pos n dm)
  16633. "Change the different parts of the lead-time and repeat fields in timestamp."
  16634. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16635. ng h m new rem)
  16636. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16637. (cond
  16638. ((or (org-pos-in-match-range pos 2)
  16639. (org-pos-in-match-range pos 3))
  16640. (setq m (string-to-number (match-string 3 s))
  16641. h (string-to-number (match-string 2 s)))
  16642. (if (org-pos-in-match-range pos 2)
  16643. (setq h (+ h n))
  16644. (setq n (* dm (with-no-warnings (signum n))))
  16645. (unless (= 0 (setq rem (% m dm)))
  16646. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16647. (setq m (+ m n)))
  16648. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16649. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16650. (setq h (mod h 24))
  16651. (setq ng 1 new (format "-%02d:%02d" h m)))
  16652. ((org-pos-in-match-range pos 6)
  16653. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16654. ((org-pos-in-match-range pos 5)
  16655. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16656. ((org-pos-in-match-range pos 9)
  16657. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16658. ((org-pos-in-match-range pos 8)
  16659. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16660. (when ng
  16661. (setq s (concat
  16662. (substring s 0 (match-beginning ng))
  16663. new
  16664. (substring s (match-end ng))))))
  16665. s))
  16666. (defun org-recenter-calendar (d)
  16667. "If the calendar is visible, recenter it to date D."
  16668. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16669. (when cwin
  16670. (let ((calendar-move-hook nil))
  16671. (with-selected-window cwin
  16672. (calendar-goto-date
  16673. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16674. (defun org-goto-calendar (&optional arg)
  16675. "Go to the Emacs calendar at the current date.
  16676. If there is a time stamp in the current line, go to that date.
  16677. A prefix ARG can be used to force the current date."
  16678. (interactive "P")
  16679. (let ((tsr org-ts-regexp) diff
  16680. (calendar-move-hook nil)
  16681. (calendar-view-holidays-initially-flag nil)
  16682. (calendar-view-diary-initially-flag nil))
  16683. (when (or (org-at-timestamp-p)
  16684. (save-excursion
  16685. (beginning-of-line 1)
  16686. (looking-at (concat ".*" tsr))))
  16687. (let ((d1 (time-to-days (current-time)))
  16688. (d2 (time-to-days
  16689. (org-time-string-to-time (match-string 1)))))
  16690. (setq diff (- d2 d1))))
  16691. (calendar)
  16692. (calendar-goto-today)
  16693. (when (and diff (not arg)) (calendar-forward-day diff))))
  16694. (defun org-get-date-from-calendar ()
  16695. "Return a list (month day year) of date at point in calendar."
  16696. (with-current-buffer "*Calendar*"
  16697. (save-match-data
  16698. (calendar-cursor-to-date))))
  16699. (defun org-date-from-calendar ()
  16700. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16701. If there is already a time stamp at the cursor position, update it."
  16702. (interactive)
  16703. (if (org-at-timestamp-p t)
  16704. (org-timestamp-change 0 'calendar)
  16705. (let ((cal-date (org-get-date-from-calendar)))
  16706. (org-insert-time-stamp
  16707. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16708. (defcustom org-effort-durations
  16709. `(("min" . 1)
  16710. ("h" . 60)
  16711. ("d" . ,(* 60 8))
  16712. ("w" . ,(* 60 8 5))
  16713. ("m" . ,(* 60 8 5 4))
  16714. ("y" . ,(* 60 8 5 40)))
  16715. "Conversion factor to minutes for an effort modifier.
  16716. Each entry has the form (MODIFIER . MINUTES).
  16717. In an effort string, a number followed by MODIFIER is multiplied
  16718. by the specified number of MINUTES to obtain an effort in
  16719. minutes.
  16720. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16721. effort string \"2hours\" is equivalent to 120 minutes."
  16722. :group 'org-agenda
  16723. :version "25.1"
  16724. :package-version '(Org . "8.3")
  16725. :type '(alist :key-type (string :tag "Modifier")
  16726. :value-type (number :tag "Minutes")))
  16727. (defun org-minutes-to-clocksum-string (m)
  16728. "Format number of minutes as a clocksum string.
  16729. The format is determined by `org-time-clocksum-format',
  16730. `org-time-clocksum-use-fractional' and
  16731. `org-time-clocksum-fractional-format' and
  16732. `org-time-clocksum-use-effort-durations'."
  16733. (let ((clocksum "")
  16734. (m (round m)) ; Don't allow fractions of minutes
  16735. h d w mo y fmt n)
  16736. (setq h (if org-time-clocksum-use-effort-durations
  16737. (cdr (assoc "h" org-effort-durations)) 60)
  16738. d (if org-time-clocksum-use-effort-durations
  16739. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16740. w (if org-time-clocksum-use-effort-durations
  16741. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16742. mo (if org-time-clocksum-use-effort-durations
  16743. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16744. y (if org-time-clocksum-use-effort-durations
  16745. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16746. ;; fractional format
  16747. (if org-time-clocksum-use-fractional
  16748. (cond
  16749. ;; single format string
  16750. ((stringp org-time-clocksum-fractional-format)
  16751. (format org-time-clocksum-fractional-format (/ m (float h))))
  16752. ;; choice of fractional formats for different time units
  16753. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16754. (> (/ (truncate m) (* y d h)) 0))
  16755. (format fmt (/ m (* y d (float h)))))
  16756. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16757. (> (/ (truncate m) (* mo d h)) 0))
  16758. (format fmt (/ m (* mo d (float h)))))
  16759. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16760. (> (/ (truncate m) (* w d h)) 0))
  16761. (format fmt (/ m (* w d (float h)))))
  16762. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16763. (> (/ (truncate m) (* d h)) 0))
  16764. (format fmt (/ m (* d (float h)))))
  16765. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16766. (> (/ (truncate m) h) 0))
  16767. (format fmt (/ m (float h))))
  16768. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16769. (format fmt m))
  16770. ;; fall back to smallest time unit with a format
  16771. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16772. (format fmt (/ m (float h))))
  16773. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16774. (format fmt (/ m (* d (float h)))))
  16775. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16776. (format fmt (/ m (* w d (float h)))))
  16777. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16778. (format fmt (/ m (* mo d (float h)))))
  16779. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16780. (format fmt (/ m (* y d (float h))))))
  16781. ;; standard (non-fractional) format, with single format string
  16782. (if (stringp org-time-clocksum-format)
  16783. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16784. ;; separate formats components
  16785. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16786. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16787. (plist-get org-time-clocksum-format :require-years))
  16788. (setq clocksum (concat clocksum (format fmt n))
  16789. m (- m (* n y d h))))
  16790. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16791. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16792. (plist-get org-time-clocksum-format :require-months))
  16793. (setq clocksum (concat clocksum (format fmt n))
  16794. m (- m (* n mo d h))))
  16795. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16796. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16797. (plist-get org-time-clocksum-format :require-weeks))
  16798. (setq clocksum (concat clocksum (format fmt n))
  16799. m (- m (* n w d h))))
  16800. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16801. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16802. (plist-get org-time-clocksum-format :require-days))
  16803. (setq clocksum (concat clocksum (format fmt n))
  16804. m (- m (* n d h))))
  16805. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16806. (or (> (setq n (/ (truncate m) h)) 0)
  16807. (plist-get org-time-clocksum-format :require-hours))
  16808. (setq clocksum (concat clocksum (format fmt n))
  16809. m (- m (* n h))))
  16810. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16811. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16812. (setq clocksum (concat clocksum (format fmt m))))
  16813. ;; return formatted time duration
  16814. clocksum))))
  16815. (defun org-hours-to-clocksum-string (n)
  16816. (org-minutes-to-clocksum-string (* n 60)))
  16817. (defun org-hh:mm-string-to-minutes (s)
  16818. "Convert a string H:MM to a number of minutes.
  16819. If the string is just a number, interpret it as minutes.
  16820. In fact, the first hh:mm or number in the string will be taken,
  16821. there can be extra stuff in the string.
  16822. If no number is found, the return value is 0."
  16823. (cond
  16824. ((integerp s) s)
  16825. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16826. (+ (* (string-to-number (match-string 1 s)) 60)
  16827. (string-to-number (match-string 2 s))))
  16828. ((string-match "\\([0-9]+\\)" s)
  16829. (string-to-number (match-string 1 s)))
  16830. (t 0)))
  16831. (defcustom org-image-actual-width t
  16832. "Should we use the actual width of images when inlining them?
  16833. When set to t, always use the image width.
  16834. When set to a number, use imagemagick (when available) to set
  16835. the image's width to this value.
  16836. When set to a number in a list, try to get the width from any
  16837. #+ATTR.* keyword if it matches a width specification like
  16838. #+ATTR_HTML: :width 300px
  16839. and fall back on that number if none is found.
  16840. When set to nil, try to get the width from an #+ATTR.* keyword
  16841. and fall back on the original width if none is found.
  16842. This requires Emacs >= 24.1, build with imagemagick support."
  16843. :group 'org-appearance
  16844. :version "24.4"
  16845. :package-version '(Org . "8.0")
  16846. :type '(choice
  16847. (const :tag "Use the image width" t)
  16848. (integer :tag "Use a number of pixels")
  16849. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16850. (const :tag "Use #+ATTR* or don't resize" nil)))
  16851. (defcustom org-agenda-inhibit-startup nil
  16852. "Inhibit startup when preparing agenda buffers.
  16853. When this variable is t, the initialization of the Org agenda
  16854. buffers is inhibited: e.g. the visibility state is not set, the
  16855. tables are not re-aligned, etc."
  16856. :type 'boolean
  16857. :version "24.3"
  16858. :group 'org-agenda)
  16859. (defcustom org-agenda-ignore-properties nil
  16860. "Avoid updating text properties when building the agenda.
  16861. Properties are used to prepare buffers for effort estimates,
  16862. appointments, statistics and subtree-local categories.
  16863. If you don't use these in the agenda, you can add them to this
  16864. list and agenda building will be a bit faster.
  16865. The value is a list, with zero or more of the symbols `effort', `appt',
  16866. `stats' or `category'."
  16867. :type '(set :greedy t
  16868. (const effort)
  16869. (const appt)
  16870. (const stats)
  16871. (const category))
  16872. :version "25.1"
  16873. :package-version '(Org . "8.3")
  16874. :group 'org-agenda)
  16875. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16876. "Convert a duration string S to minutes.
  16877. A bare number is interpreted as minutes, modifiers can be set by
  16878. customizing `org-effort-durations' (which see).
  16879. Entries containing a colon are interpreted as H:MM by
  16880. `org-hh:mm-string-to-minutes'."
  16881. (let ((result 0)
  16882. (re (concat "\\([0-9.]+\\) *\\("
  16883. (regexp-opt (mapcar 'car org-effort-durations))
  16884. "\\)")))
  16885. (while (string-match re s)
  16886. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16887. (string-to-number (match-string 1 s))))
  16888. (setq s (replace-match "" nil t s)))
  16889. (setq result (floor result))
  16890. (cl-incf result (org-hh:mm-string-to-minutes s))
  16891. (if output-to-string (number-to-string result) result)))
  16892. ;;;; Files
  16893. (defun org-save-all-org-buffers ()
  16894. "Save all Org buffers without user confirmation."
  16895. (interactive)
  16896. (message "Saving all Org buffers...")
  16897. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16898. (when (featurep 'org-id) (org-id-locations-save))
  16899. (message "Saving all Org buffers... done"))
  16900. (defun org-revert-all-org-buffers ()
  16901. "Revert all Org buffers.
  16902. Prompt for confirmation when there are unsaved changes.
  16903. Be sure you know what you are doing before letting this function
  16904. overwrite your changes.
  16905. This function is useful in a setup where one tracks org files
  16906. with a version control system, to revert on one machine after pulling
  16907. changes from another. I believe the procedure must be like this:
  16908. 1. M-x org-save-all-org-buffers
  16909. 2. Pull changes from the other machine, resolve conflicts
  16910. 3. M-x org-revert-all-org-buffers"
  16911. (interactive)
  16912. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16913. (user-error "Abort"))
  16914. (save-excursion
  16915. (save-window-excursion
  16916. (dolist (b (buffer-list))
  16917. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16918. (with-current-buffer b buffer-file-name))
  16919. (pop-to-buffer-same-window b)
  16920. (revert-buffer t 'no-confirm)))
  16921. (when (and (featurep 'org-id) org-id-track-globally)
  16922. (org-id-locations-load)))))
  16923. ;;;; Agenda files
  16924. ;;;###autoload
  16925. (defun org-switchb (&optional arg)
  16926. "Switch between Org buffers.
  16927. With \\[universal-argument] prefix, restrict available buffers to files.
  16928. With \\[universal-argument] \\[universal-argument] \
  16929. prefix, restrict available buffers to agenda files."
  16930. (interactive "P")
  16931. (let ((blist (org-buffer-list
  16932. (cond ((equal arg '(4)) 'files)
  16933. ((equal arg '(16)) 'agenda)))))
  16934. (pop-to-buffer-same-window
  16935. (completing-read "Org buffer: "
  16936. (mapcar #'list (mapcar #'buffer-name blist))
  16937. nil t))))
  16938. (defun org-buffer-list (&optional predicate exclude-tmp)
  16939. "Return a list of Org buffers.
  16940. PREDICATE can be `export', `files' or `agenda'.
  16941. export restrict the list to Export buffers.
  16942. files restrict the list to buffers visiting Org files.
  16943. agenda restrict the list to buffers visiting agenda files.
  16944. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16945. (let* ((bfn nil)
  16946. (agenda-files (and (eq predicate 'agenda)
  16947. (mapcar 'file-truename (org-agenda-files t))))
  16948. (filter
  16949. (cond
  16950. ((eq predicate 'files)
  16951. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16952. ((eq predicate 'export)
  16953. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16954. ((eq predicate 'agenda)
  16955. (lambda (b)
  16956. (with-current-buffer b
  16957. (and (derived-mode-p 'org-mode)
  16958. (setq bfn (buffer-file-name b))
  16959. (member (file-truename bfn) agenda-files)))))
  16960. (t (lambda (b) (with-current-buffer b
  16961. (or (derived-mode-p 'org-mode)
  16962. (string-match "\\*Org .*Export"
  16963. (buffer-name b)))))))))
  16964. (delq nil
  16965. (mapcar
  16966. (lambda(b)
  16967. (if (and (funcall filter b)
  16968. (or (not exclude-tmp)
  16969. (not (string-match "tmp" (buffer-name b)))))
  16970. b
  16971. nil))
  16972. (buffer-list)))))
  16973. (defun org-agenda-files (&optional unrestricted archives)
  16974. "Get the list of agenda files.
  16975. Optional UNRESTRICTED means return the full list even if a restriction
  16976. is currently in place.
  16977. When ARCHIVES is t, include all archive files that are really being
  16978. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16979. `org-agenda-archives-mode' is t."
  16980. (let ((files
  16981. (cond
  16982. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16983. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16984. ((listp org-agenda-files) org-agenda-files)
  16985. (t (error "Invalid value of `org-agenda-files'")))))
  16986. (setq files (apply 'append
  16987. (mapcar (lambda (f)
  16988. (if (file-directory-p f)
  16989. (directory-files
  16990. f t org-agenda-file-regexp)
  16991. (list f)))
  16992. files)))
  16993. (when org-agenda-skip-unavailable-files
  16994. (setq files (delq nil
  16995. (mapcar (function
  16996. (lambda (file)
  16997. (and (file-readable-p file) file)))
  16998. files))))
  16999. (when (or (eq archives t)
  17000. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17001. (setq files (org-add-archive-files files)))
  17002. files))
  17003. (defun org-agenda-file-p (&optional file)
  17004. "Return non-nil, if FILE is an agenda file.
  17005. If FILE is omitted, use the file associated with the current
  17006. buffer."
  17007. (let ((fname (or file (buffer-file-name))))
  17008. (and fname
  17009. (member (file-truename fname)
  17010. (mapcar #'file-truename (org-agenda-files t))))))
  17011. (defun org-edit-agenda-file-list ()
  17012. "Edit the list of agenda files.
  17013. Depending on setup, this either uses customize to edit the variable
  17014. `org-agenda-files', or it visits the file that is holding the list. In the
  17015. latter case, the buffer is set up in a way that saving it automatically kills
  17016. the buffer and restores the previous window configuration."
  17017. (interactive)
  17018. (if (stringp org-agenda-files)
  17019. (let ((cw (current-window-configuration)))
  17020. (find-file org-agenda-files)
  17021. (setq-local org-window-configuration cw)
  17022. (add-hook 'after-save-hook
  17023. (lambda ()
  17024. (set-window-configuration
  17025. (prog1 org-window-configuration
  17026. (kill-buffer (current-buffer))))
  17027. (org-install-agenda-files-menu)
  17028. (message "New agenda file list installed"))
  17029. nil 'local)
  17030. (message "%s" (substitute-command-keys
  17031. "Edit list and finish with \\[save-buffer]")))
  17032. (customize-variable 'org-agenda-files)))
  17033. (defun org-store-new-agenda-file-list (list)
  17034. "Set new value for the agenda file list and save it correctly."
  17035. (if (stringp org-agenda-files)
  17036. (let ((fe (org-read-agenda-file-list t)) b u)
  17037. (while (setq b (find-buffer-visiting org-agenda-files))
  17038. (kill-buffer b))
  17039. (with-temp-file org-agenda-files
  17040. (insert
  17041. (mapconcat
  17042. (lambda (f) ;; Keep un-expanded entries.
  17043. (if (setq u (assoc f fe))
  17044. (cdr u)
  17045. f))
  17046. list "\n")
  17047. "\n")))
  17048. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17049. (org-insert-mode-line-in-empty-file nil))
  17050. (setq org-agenda-files list)
  17051. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17052. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17053. "Read the list of agenda files from a file.
  17054. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17055. filenames, used by `org-store-new-agenda-file-list' to write back
  17056. un-expanded file names."
  17057. (when (file-directory-p org-agenda-files)
  17058. (error "`org-agenda-files' cannot be a single directory"))
  17059. (when (stringp org-agenda-files)
  17060. (with-temp-buffer
  17061. (insert-file-contents org-agenda-files)
  17062. (mapcar
  17063. (lambda (f)
  17064. (let ((e (expand-file-name (substitute-in-file-name f)
  17065. org-directory)))
  17066. (if pair-with-expansion
  17067. (cons e f)
  17068. e)))
  17069. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17070. ;;;###autoload
  17071. (defun org-cycle-agenda-files ()
  17072. "Cycle through the files in `org-agenda-files'.
  17073. If the current buffer visits an agenda file, find the next one in the list.
  17074. If the current buffer does not, find the first agenda file."
  17075. (interactive)
  17076. (let* ((fs (or (org-agenda-files t)
  17077. (user-error "No agenda files")))
  17078. (files (copy-sequence fs))
  17079. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17080. file)
  17081. (when tcf
  17082. (while (and (setq file (pop files))
  17083. (not (equal (file-truename file) tcf)))))
  17084. (find-file (car (or files fs)))
  17085. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17086. (defun org-agenda-file-to-front (&optional to-end)
  17087. "Move/add the current file to the top of the agenda file list.
  17088. If the file is not present in the list, it is added to the front. If it is
  17089. present, it is moved there. With optional argument TO-END, add/move to the
  17090. end of the list."
  17091. (interactive "P")
  17092. (let ((org-agenda-skip-unavailable-files nil)
  17093. (file-alist (mapcar (lambda (x)
  17094. (cons (file-truename x) x))
  17095. (org-agenda-files t)))
  17096. (ctf (file-truename
  17097. (or buffer-file-name
  17098. (user-error "Please save the current buffer to a file"))))
  17099. x had)
  17100. (setq x (assoc ctf file-alist) had x)
  17101. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17102. (if to-end
  17103. (setq file-alist (append (delq x file-alist) (list x)))
  17104. (setq file-alist (cons x (delq x file-alist))))
  17105. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17106. (org-install-agenda-files-menu)
  17107. (message "File %s to %s of agenda file list"
  17108. (if had "moved" "added") (if to-end "end" "front"))))
  17109. (defun org-remove-file (&optional file)
  17110. "Remove current file from the list of files in variable `org-agenda-files'.
  17111. These are the files which are being checked for agenda entries.
  17112. Optional argument FILE means use this file instead of the current."
  17113. (interactive)
  17114. (let* ((org-agenda-skip-unavailable-files nil)
  17115. (file (or file buffer-file-name
  17116. (user-error "Current buffer does not visit a file")))
  17117. (true-file (file-truename file))
  17118. (afile (abbreviate-file-name file))
  17119. (files (delq nil (mapcar
  17120. (lambda (x)
  17121. (unless (equal true-file
  17122. (file-truename x))
  17123. x))
  17124. (org-agenda-files t)))))
  17125. (if (not (= (length files) (length (org-agenda-files t))))
  17126. (progn
  17127. (org-store-new-agenda-file-list files)
  17128. (org-install-agenda-files-menu)
  17129. (message "Removed from Org Agenda list: %s" afile))
  17130. (message "File was not in list: %s (not removed)" afile))))
  17131. (defun org-file-menu-entry (file)
  17132. (vector file (list 'find-file file) t))
  17133. (defun org-check-agenda-file (file)
  17134. "Make sure FILE exists. If not, ask user what to do."
  17135. (unless (file-exists-p file)
  17136. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17137. (abbreviate-file-name file))
  17138. (let ((r (downcase (read-char-exclusive))))
  17139. (cond
  17140. ((equal r ?r)
  17141. (org-remove-file file)
  17142. (throw 'nextfile t))
  17143. (t (user-error "Abort"))))))
  17144. (defun org-get-agenda-file-buffer (file)
  17145. "Get an agenda buffer visiting FILE.
  17146. If the buffer needs to be created, add it to the list of buffers
  17147. which might be released later."
  17148. (let ((buf (org-find-base-buffer-visiting file)))
  17149. (if buf
  17150. buf ; just return it
  17151. ;; Make a new buffer and remember it
  17152. (setq buf (find-file-noselect file))
  17153. (when buf (push buf org-agenda-new-buffers))
  17154. buf)))
  17155. (defun org-release-buffers (blist)
  17156. "Release all buffers in list, asking the user for confirmation when needed.
  17157. When a buffer is unmodified, it is just killed. When modified, it is saved
  17158. \(if the user agrees) and then killed."
  17159. (let (file)
  17160. (dolist (buf blist)
  17161. (setq file (buffer-file-name buf))
  17162. (when (and (buffer-modified-p buf)
  17163. file
  17164. (y-or-n-p (format "Save file %s? " file)))
  17165. (with-current-buffer buf (save-buffer)))
  17166. (kill-buffer buf))))
  17167. (defun org-agenda-prepare-buffers (files)
  17168. "Create buffers for all agenda files, protect archived trees and comments."
  17169. (interactive)
  17170. (let ((pa '(:org-archived t))
  17171. (pc '(:org-comment t))
  17172. (pall '(:org-archived t :org-comment t))
  17173. (inhibit-read-only t)
  17174. (org-inhibit-startup org-agenda-inhibit-startup)
  17175. (rea (concat ":" org-archive-tag ":"))
  17176. re pos)
  17177. (setq org-tag-alist-for-agenda nil
  17178. org-tag-groups-alist-for-agenda nil)
  17179. (save-excursion
  17180. (save-restriction
  17181. (dolist (file files)
  17182. (catch 'nextfile
  17183. (if (bufferp file)
  17184. (set-buffer file)
  17185. (org-check-agenda-file file)
  17186. (set-buffer (org-get-agenda-file-buffer file)))
  17187. (widen)
  17188. (org-set-regexps-and-options 'tags-only)
  17189. (setq pos (point))
  17190. (or (memq 'category org-agenda-ignore-properties)
  17191. (org-refresh-category-properties))
  17192. (or (memq 'stats org-agenda-ignore-properties)
  17193. (org-refresh-stats-properties))
  17194. (or (memq 'effort org-agenda-ignore-properties)
  17195. (org-refresh-effort-properties))
  17196. (or (memq 'appt org-agenda-ignore-properties)
  17197. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17198. (setq org-todo-keywords-for-agenda
  17199. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17200. (setq org-done-keywords-for-agenda
  17201. (append org-done-keywords-for-agenda org-done-keywords))
  17202. (setq org-todo-keyword-alist-for-agenda
  17203. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17204. (setq org-tag-alist-for-agenda
  17205. (org-uniquify
  17206. (append org-tag-alist-for-agenda
  17207. org-current-tag-alist)))
  17208. ;; Merge current file's tag groups into global
  17209. ;; `org-tag-groups-alist-for-agenda'.
  17210. (when org-group-tags
  17211. (dolist (alist org-tag-groups-alist)
  17212. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17213. (if old
  17214. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17215. (push alist org-tag-groups-alist-for-agenda)))))
  17216. (org-with-silent-modifications
  17217. (save-excursion
  17218. (remove-text-properties (point-min) (point-max) pall)
  17219. (when org-agenda-skip-archived-trees
  17220. (goto-char (point-min))
  17221. (while (re-search-forward rea nil t)
  17222. (when (org-at-heading-p t)
  17223. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17224. (goto-char (point-min))
  17225. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17226. (while (re-search-forward re nil t)
  17227. (when (save-match-data (org-in-commented-heading-p t))
  17228. (add-text-properties
  17229. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17230. (goto-char pos)))))
  17231. (setq org-todo-keywords-for-agenda
  17232. (org-uniquify org-todo-keywords-for-agenda))
  17233. (setq org-todo-keyword-alist-for-agenda
  17234. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17235. ;;;; CDLaTeX minor mode
  17236. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17237. "Keymap for the minor `org-cdlatex-mode'.")
  17238. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17239. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17240. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17241. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17242. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17243. (defvar org-cdlatex-texmathp-advice-is-done nil
  17244. "Flag remembering if we have applied the advice to texmathp already.")
  17245. (define-minor-mode org-cdlatex-mode
  17246. "Toggle the minor `org-cdlatex-mode'.
  17247. This mode supports entering LaTeX environment and math in LaTeX fragments
  17248. in Org-mode.
  17249. \\{org-cdlatex-mode-map}"
  17250. nil " OCDL" nil
  17251. (when org-cdlatex-mode
  17252. (require 'cdlatex)
  17253. (run-hooks 'cdlatex-mode-hook)
  17254. (cdlatex-compute-tables))
  17255. (unless org-cdlatex-texmathp-advice-is-done
  17256. (setq org-cdlatex-texmathp-advice-is-done t)
  17257. (defadvice texmathp (around org-math-always-on activate)
  17258. "Always return t in Org buffers.
  17259. This is because we want to insert math symbols without dollars even outside
  17260. the LaTeX math segments. If Orgmode thinks that point is actually inside
  17261. an embedded LaTeX fragment, let texmathp do its job.
  17262. \\[org-cdlatex-mode-map]"
  17263. (interactive)
  17264. (let (p)
  17265. (cond
  17266. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17267. ((eq this-command 'cdlatex-math-symbol)
  17268. (setq ad-return-value t
  17269. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17270. (t
  17271. (let ((p (org-inside-LaTeX-fragment-p)))
  17272. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17273. (setq ad-return-value t
  17274. texmathp-why '("Org-mode embedded math" . 0))
  17275. (when p ad-do-it)))))))))
  17276. (defun turn-on-org-cdlatex ()
  17277. "Unconditionally turn on `org-cdlatex-mode'."
  17278. (org-cdlatex-mode 1))
  17279. (defun org-try-cdlatex-tab ()
  17280. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17281. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17282. - inside a LaTeX fragment, or
  17283. - after the first word in a line, where an abbreviation expansion could
  17284. insert a LaTeX environment."
  17285. (when org-cdlatex-mode
  17286. (cond
  17287. ;; Before any word on the line: No expansion possible.
  17288. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17289. ;; Just after first word on the line: Expand it. Make sure it
  17290. ;; cannot happen on headlines, though.
  17291. ((save-excursion
  17292. (skip-chars-backward "a-zA-Z0-9*")
  17293. (skip-chars-backward " \t")
  17294. (and (bolp) (not (org-at-heading-p))))
  17295. (cdlatex-tab) t)
  17296. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17297. (defun org-cdlatex-underscore-caret (&optional _arg)
  17298. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17299. Revert to the normal definition outside of these fragments."
  17300. (interactive "P")
  17301. (if (org-inside-LaTeX-fragment-p)
  17302. (call-interactively 'cdlatex-sub-superscript)
  17303. (let (org-cdlatex-mode)
  17304. (call-interactively (key-binding (vector last-input-event))))))
  17305. (defun org-cdlatex-math-modify (&optional _arg)
  17306. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17307. Revert to the normal definition outside of these fragments."
  17308. (interactive "P")
  17309. (if (org-inside-LaTeX-fragment-p)
  17310. (call-interactively 'cdlatex-math-modify)
  17311. (let (org-cdlatex-mode)
  17312. (call-interactively (key-binding (vector last-input-event))))))
  17313. (defun org-cdlatex-environment-indent (&optional environment item)
  17314. "Execute `cdlatex-environment' and indent the inserted environment.
  17315. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17316. The inserted environment is indented to current indentation
  17317. unless point is at the beginning of the line, in which the
  17318. environment remains unintended."
  17319. (interactive)
  17320. ;; cdlatex-environment always return nil. Therefore, capture output
  17321. ;; first and determine if an environment was selected.
  17322. (let* ((beg (point-marker))
  17323. (end (copy-marker (point) t))
  17324. (inserted (progn
  17325. (ignore-errors (cdlatex-environment environment item))
  17326. (< beg end)))
  17327. ;; Figure out how many lines to move forward after the
  17328. ;; environment has been inserted.
  17329. (lines (when inserted
  17330. (save-excursion
  17331. (- (cl-loop while (< beg (point))
  17332. with x = 0
  17333. do (forward-line -1)
  17334. (cl-incf x)
  17335. finally return x)
  17336. (if (progn (goto-char beg)
  17337. (and (progn (skip-chars-forward " \t") (eolp))
  17338. (progn (skip-chars-backward " \t") (bolp))))
  17339. 1 0)))))
  17340. (env (org-trim (delete-and-extract-region beg end))))
  17341. (when inserted
  17342. ;; Get indentation of next line unless at column 0.
  17343. (let ((ind (if (bolp) 0
  17344. (save-excursion
  17345. (org-return-indent)
  17346. (prog1 (org-get-indentation)
  17347. (when (progn (skip-chars-forward " \t") (eolp))
  17348. (delete-region beg (point)))))))
  17349. (bol (progn (skip-chars-backward " \t") (bolp))))
  17350. ;; Insert a newline before environment unless at column zero
  17351. ;; to "escape" the current line. Insert a newline if
  17352. ;; something is one the same line as \end{ENVIRONMENT}.
  17353. (insert
  17354. (concat (unless bol "\n") env
  17355. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17356. (unless (zerop ind)
  17357. (save-excursion
  17358. (goto-char beg)
  17359. (while (< (point) end)
  17360. (unless (eolp) (indent-line-to ind))
  17361. (forward-line))))
  17362. (goto-char beg)
  17363. (forward-line lines)
  17364. (indent-line-to ind)))
  17365. (set-marker beg nil)
  17366. (set-marker end nil)))
  17367. ;;;; LaTeX fragments
  17368. (defun org-inside-LaTeX-fragment-p ()
  17369. "Test if point is inside a LaTeX fragment.
  17370. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17371. sequence appearing also before point.
  17372. Even though the matchers for math are configurable, this function assumes
  17373. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17374. delimiters are skipped when they have been removed by customization.
  17375. The return value is nil, or a cons cell with the delimiter and the
  17376. position of this delimiter.
  17377. This function does a reasonably good job, but can locally be fooled by
  17378. for example currency specifications. For example it will assume being in
  17379. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17380. fragments that are properly closed, but during editing, we have to live
  17381. with the uncertainty caused by missing closing delimiters. This function
  17382. looks only before point, not after."
  17383. (catch 'exit
  17384. (let ((pos (point))
  17385. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17386. (lim (progn
  17387. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17388. (point)))
  17389. dd-on str (start 0) m re)
  17390. (goto-char pos)
  17391. (when dodollar
  17392. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17393. re (nth 1 (assoc "$" org-latex-regexps)))
  17394. (while (string-match re str start)
  17395. (cond
  17396. ((= (match-end 0) (length str))
  17397. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17398. ((= (match-end 0) (- (length str) 5))
  17399. (throw 'exit nil))
  17400. (t (setq start (match-end 0))))))
  17401. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17402. (goto-char pos)
  17403. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17404. (and (match-beginning 2) (throw 'exit nil))
  17405. ;; count $$
  17406. (while (re-search-backward "\\$\\$" lim t)
  17407. (setq dd-on (not dd-on)))
  17408. (goto-char pos)
  17409. (when dd-on (cons "$$" m))))))
  17410. (defun org-inside-latex-macro-p ()
  17411. "Is point inside a LaTeX macro or its arguments?"
  17412. (save-match-data
  17413. (org-in-regexp
  17414. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17415. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17416. "Build an overlay between BEG and END using IMAGE file.
  17417. Argument IMAGETYPE is the extension of the displayed image,
  17418. as a string. It defaults to \"png\"."
  17419. (let ((ov (make-overlay beg end))
  17420. (imagetype (or (intern imagetype) 'png)))
  17421. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17422. (overlay-put ov 'evaporate t)
  17423. (overlay-put ov
  17424. 'modification-hooks
  17425. (list (lambda (o _flag _beg _end &optional _l)
  17426. (delete-overlay o))))
  17427. (overlay-put ov
  17428. 'display
  17429. (list 'image :type imagetype :file image :ascent 'center))))
  17430. (defun org--list-latex-overlays (&optional beg end)
  17431. "List all Org LaTeX overlays in current buffer.
  17432. Limit to overlays between BEG and END when those are provided."
  17433. (cl-remove-if-not
  17434. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17435. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17436. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17437. "Remove all overlays with LaTeX fragment images in current buffer.
  17438. When optional arguments BEG and END are non-nil, remove all
  17439. overlays between them instead. Return a non-nil value when some
  17440. overlays were removed, nil otherwise."
  17441. (let ((overlays (org--list-latex-overlays beg end)))
  17442. (mapc #'delete-overlay overlays)
  17443. overlays))
  17444. (defun org-toggle-latex-fragment (&optional arg)
  17445. "Preview the LaTeX fragment at point, or all locally or globally.
  17446. If the cursor is on a LaTeX fragment, create the image and overlay
  17447. it over the source code, if there is none. Remove it otherwise.
  17448. If there is no fragment at point, display all fragments in the
  17449. current section.
  17450. With prefix ARG, preview or clear image for all fragments in the
  17451. current subtree or in the whole buffer when used before the first
  17452. headline. With a double prefix ARG \\[universal-argument] \
  17453. \\[universal-argument] preview or clear images
  17454. for all fragments in the buffer."
  17455. (interactive "P")
  17456. (when (display-graphic-p)
  17457. (catch 'exit
  17458. (save-excursion
  17459. (let (beg end msg)
  17460. (cond
  17461. ((or (equal arg '(16))
  17462. (and (equal arg '(4))
  17463. (org-with-limited-levels (org-before-first-heading-p))))
  17464. (if (org-remove-latex-fragment-image-overlays)
  17465. (progn (message "LaTeX fragments images removed from buffer")
  17466. (throw 'exit nil))
  17467. (setq msg "Creating images for buffer...")))
  17468. ((equal arg '(4))
  17469. (org-with-limited-levels (org-back-to-heading t))
  17470. (setq beg (point))
  17471. (setq end (progn (org-end-of-subtree t) (point)))
  17472. (if (org-remove-latex-fragment-image-overlays beg end)
  17473. (progn
  17474. (message "LaTeX fragment images removed from subtree")
  17475. (throw 'exit nil))
  17476. (setq msg "Creating images for subtree...")))
  17477. ((let ((datum (org-element-context)))
  17478. (when (memq (org-element-type datum)
  17479. '(latex-environment latex-fragment))
  17480. (setq beg (org-element-property :begin datum))
  17481. (setq end (org-element-property :end datum))
  17482. (if (org-remove-latex-fragment-image-overlays beg end)
  17483. (progn (message "LaTeX fragment image removed")
  17484. (throw 'exit nil))
  17485. (setq msg "Creating image...")))))
  17486. (t
  17487. (org-with-limited-levels
  17488. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17489. (outline-previous-heading)
  17490. (point)))
  17491. (setq end (progn (outline-next-heading) (point)))
  17492. (if (org-remove-latex-fragment-image-overlays beg end)
  17493. (progn
  17494. (message "LaTeX fragment images removed from section")
  17495. (throw 'exit nil))
  17496. (setq msg "Creating images for section...")))))
  17497. (let ((file (buffer-file-name (buffer-base-buffer))))
  17498. (org-format-latex
  17499. (concat org-preview-latex-image-directory "org-ltximg")
  17500. beg end
  17501. ;; Emacs cannot overlay images from remote hosts. Create
  17502. ;; it in `temporary-file-directory' instead.
  17503. (if (or (not file) (file-remote-p file))
  17504. temporary-file-directory
  17505. default-directory)
  17506. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17507. (message (concat msg "done")))))))
  17508. (defun org-format-latex
  17509. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17510. "Replace LaTeX fragments with links to an image.
  17511. The function takes care of creating the replacement image.
  17512. Only consider fragments between BEG and END when those are
  17513. provided.
  17514. When optional argument OVERLAYS is non-nil, display the image on
  17515. top of the fragment instead of replacing it.
  17516. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17517. Some of the options can be changed using the variable
  17518. `org-format-latex-options', which see."
  17519. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17520. (unless (eq processing-type 'verbatim)
  17521. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17522. (cnt 0)
  17523. checkdir-flag)
  17524. (goto-char (or beg (point-min)))
  17525. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17526. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17527. (overlay-recenter (or end (point-max))))
  17528. (while (re-search-forward math-regexp end t)
  17529. (unless (and overlays
  17530. (eq (get-char-property (point) 'org-overlay-type)
  17531. 'org-latex-overlay))
  17532. (let* ((context (org-element-context))
  17533. (type (org-element-type context)))
  17534. (when (memq type '(latex-environment latex-fragment))
  17535. (let ((block-type (eq type 'latex-environment))
  17536. (value (org-element-property :value context))
  17537. (beg (org-element-property :begin context))
  17538. (end (save-excursion
  17539. (goto-char (org-element-property :end context))
  17540. (skip-chars-backward " \r\t\n")
  17541. (point))))
  17542. (cond
  17543. ((eq processing-type 'mathjax)
  17544. ;; Prepare for MathJax processing.
  17545. (if (not (string-match "\\`\\$\\$?" value))
  17546. (goto-char end)
  17547. (delete-region beg end)
  17548. (if (string= (match-string 0 value) "$$")
  17549. (insert "\\[" (substring value 2 -2) "\\]")
  17550. (insert "\\(" (substring value 1 -1) "\\)"))))
  17551. ((assq processing-type org-preview-latex-process-alist)
  17552. ;; Process to an image.
  17553. (cl-incf cnt)
  17554. (goto-char beg)
  17555. (let* ((processing-info
  17556. (cdr (assq processing-type org-preview-latex-process-alist)))
  17557. (face (face-at-point))
  17558. ;; Get the colors from the face at point.
  17559. (fg
  17560. (let ((color (plist-get org-format-latex-options
  17561. :foreground)))
  17562. (if (and forbuffer (eq color 'auto))
  17563. (face-attribute face :foreground nil 'default)
  17564. color)))
  17565. (bg
  17566. (let ((color (plist-get org-format-latex-options
  17567. :background)))
  17568. (if (and forbuffer (eq color 'auto))
  17569. (face-attribute face :background nil 'default)
  17570. color)))
  17571. (hash (sha1 (prin1-to-string
  17572. (list org-format-latex-header
  17573. org-latex-default-packages-alist
  17574. org-latex-packages-alist
  17575. org-format-latex-options
  17576. forbuffer value fg bg))))
  17577. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17578. (absprefix (expand-file-name prefix dir))
  17579. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17580. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17581. (sep (and block-type "\n\n"))
  17582. (link (concat sep "[[file:" linkfile "]]" sep))
  17583. (options
  17584. (org-combine-plists
  17585. org-format-latex-options
  17586. `(:foreground ,fg :background ,bg))))
  17587. (when msg (message msg cnt))
  17588. (unless checkdir-flag ; Ensure the directory exists.
  17589. (setq checkdir-flag t)
  17590. (let ((todir (file-name-directory absprefix)))
  17591. (unless (file-directory-p todir)
  17592. (make-directory todir t))))
  17593. (unless (file-exists-p movefile)
  17594. (org-create-formula-image
  17595. value movefile options forbuffer processing-type))
  17596. (if overlays
  17597. (progn
  17598. (dolist (o (overlays-in beg end))
  17599. (when (eq (overlay-get o 'org-overlay-type)
  17600. 'org-latex-overlay)
  17601. (delete-overlay o)))
  17602. (org--format-latex-make-overlay beg end movefile imagetype)
  17603. (goto-char end))
  17604. (delete-region beg end)
  17605. (insert
  17606. (org-add-props link
  17607. (list 'org-latex-src
  17608. (replace-regexp-in-string "\"" "" value)
  17609. 'org-latex-src-embed-type
  17610. (if block-type 'paragraph 'character)))))))
  17611. ((eq processing-type 'mathml)
  17612. ;; Process to MathML.
  17613. (unless (org-format-latex-mathml-available-p)
  17614. (user-error "LaTeX to MathML converter not configured"))
  17615. (cl-incf cnt)
  17616. (when msg (message msg cnt))
  17617. (goto-char beg)
  17618. (delete-region beg end)
  17619. (insert (org-format-latex-as-mathml
  17620. value block-type prefix dir)))
  17621. (t
  17622. (error "Unknown conversion process %s for LaTeX fragments"
  17623. processing-type)))))))))))
  17624. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17625. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17626. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17627. sucessful, return the portion between \"<math...> </math>\"
  17628. elements otherwise return nil. When MATHML-FILE is specified,
  17629. write the results in to that file. When invoked as an
  17630. interactive command, prompt for LATEX-FRAG, with initial value
  17631. set to the current active region and echo the results for user
  17632. inspection."
  17633. (interactive (list (let ((frag (when (org-region-active-p)
  17634. (buffer-substring-no-properties
  17635. (region-beginning) (region-end)))))
  17636. (read-string "LaTeX Fragment: " frag nil frag))))
  17637. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17638. (let* ((tmp-in-file
  17639. (let ((file (file-relative-name
  17640. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17641. (write-region latex-frag nil file)
  17642. file))
  17643. (tmp-out-file (file-relative-name
  17644. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17645. (cmd (format-spec
  17646. org-latex-to-mathml-convert-command
  17647. `((?j . ,(and org-latex-to-mathml-jar-file
  17648. (shell-quote-argument
  17649. (expand-file-name
  17650. org-latex-to-mathml-jar-file))))
  17651. (?I . ,(shell-quote-argument tmp-in-file))
  17652. (?i . ,latex-frag)
  17653. (?o . ,(shell-quote-argument tmp-out-file)))))
  17654. mathml shell-command-output)
  17655. (when (called-interactively-p 'any)
  17656. (unless (org-format-latex-mathml-available-p)
  17657. (user-error "LaTeX to MathML converter not configured")))
  17658. (message "Running %s" cmd)
  17659. (setq shell-command-output (shell-command-to-string cmd))
  17660. (setq mathml
  17661. (when (file-readable-p tmp-out-file)
  17662. (with-current-buffer (find-file-noselect tmp-out-file t)
  17663. (goto-char (point-min))
  17664. (when (re-search-forward
  17665. (concat
  17666. (regexp-quote
  17667. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17668. "[^>]*?>"
  17669. "\\(.\\|\n\\)*"
  17670. "</math>")
  17671. nil t)
  17672. (prog1 (match-string 0) (kill-buffer))))))
  17673. (cond
  17674. (mathml
  17675. (setq mathml
  17676. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17677. (when mathml-file
  17678. (write-region mathml nil mathml-file))
  17679. (when (called-interactively-p 'any)
  17680. (message mathml)))
  17681. ((message "LaTeX to MathML conversion failed")
  17682. (message shell-command-output)))
  17683. (delete-file tmp-in-file)
  17684. (when (file-exists-p tmp-out-file)
  17685. (delete-file tmp-out-file))
  17686. mathml))
  17687. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17688. prefix &optional dir)
  17689. "Use `org-create-math-formula' but check local cache first."
  17690. (let* ((absprefix (expand-file-name prefix dir))
  17691. (print-length nil) (print-level nil)
  17692. (formula-id (concat
  17693. "formula-"
  17694. (sha1
  17695. (prin1-to-string
  17696. (list latex-frag
  17697. org-latex-to-mathml-convert-command)))))
  17698. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17699. (formula-cache-dir (file-name-directory formula-cache)))
  17700. (unless (file-directory-p formula-cache-dir)
  17701. (make-directory formula-cache-dir t))
  17702. (unless (file-exists-p formula-cache)
  17703. (org-create-math-formula latex-frag formula-cache))
  17704. (if (file-exists-p formula-cache)
  17705. ;; Successful conversion. Return the link to MathML file.
  17706. (org-add-props
  17707. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17708. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17709. 'org-latex-src-embed-type (if latex-frag-type
  17710. 'paragraph 'character)))
  17711. ;; Failed conversion. Return the LaTeX fragment verbatim
  17712. latex-frag)))
  17713. (declare-function org-export-get-backend "ox" (name))
  17714. (declare-function org-export--get-global-options "ox" (&optional backend))
  17715. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17716. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17717. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17718. (defun org-create-formula--latex-header ()
  17719. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17720. (let ((info (org-combine-plists (org-export--get-global-options
  17721. (org-export-get-backend 'latex))
  17722. (org-export--get-inbuffer-options
  17723. (org-export-get-backend 'latex)))))
  17724. (org-latex-guess-babel-language
  17725. (org-latex-guess-inputenc
  17726. (org-splice-latex-header
  17727. org-format-latex-header
  17728. org-latex-default-packages-alist
  17729. org-latex-packages-alist t
  17730. (plist-get info :latex-header)))
  17731. info)))
  17732. (defun org--get-display-dpi ()
  17733. "Get the DPI of the display.
  17734. Assumes that the display has the same pixel width in the
  17735. horizontal and vertical directions."
  17736. (if (display-graphic-p)
  17737. (round (/ (display-pixel-height)
  17738. (/ (display-mm-height) 25.4)))
  17739. (error "Attempt to calculate the dpi of a non-graphic display")))
  17740. (defun org-create-formula-image
  17741. (string tofile options buffer &optional processing-type)
  17742. "Create an image from LaTeX source using external processes.
  17743. The LaTeX STRING is saved to a temporary LaTeX file, then
  17744. converted to an image file by process PROCESSING-TYPE defined in
  17745. `org-preview-latex-process-alist'. A nil value defaults to
  17746. `org-preview-latex-default-process'.
  17747. The generated image file is eventually moved to TOFILE.
  17748. The OPTIONS argument controls the size, foreground color and
  17749. background color of the generated image.
  17750. When BUFFER non-nil, this function is used for LaTeX previewing.
  17751. Otherwise, it is used to deal with LaTeX snippets showed in
  17752. a HTML file."
  17753. (let* ((processing-type (or processing-type
  17754. org-preview-latex-default-process))
  17755. (processing-info
  17756. (cdr (assq processing-type org-preview-latex-process-alist)))
  17757. (programs (plist-get processing-info :programs))
  17758. (error-message (or (plist-get processing-info :message) ""))
  17759. (use-xcolor (plist-get processing-info :use-xcolor))
  17760. (image-input-type (plist-get processing-info :image-input-type))
  17761. (image-output-type (plist-get processing-info :image-output-type))
  17762. (post-clean (or (plist-get processing-info :post-clean)
  17763. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17764. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17765. (latex-header (or (plist-get processing-info :latex-header)
  17766. (org-create-formula--latex-header)))
  17767. (latex-compiler (plist-get processing-info :latex-compiler))
  17768. (image-converter (plist-get processing-info :image-converter))
  17769. (tmpdir temporary-file-directory)
  17770. (texfilebase (make-temp-name
  17771. (expand-file-name "orgtex" tmpdir)))
  17772. (texfile (concat texfilebase ".tex"))
  17773. (font-height (face-attribute 'default :height nil))
  17774. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17775. '(1.0 . 1.0)))
  17776. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17777. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17778. (dpi (* scale (floor (if buffer font-height 140.0))))
  17779. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17780. "Black"))
  17781. (bg (or (plist-get options (if buffer :background :html-background))
  17782. "Transparent"))
  17783. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17784. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17785. (dolist (program programs)
  17786. (org-check-external-command program error-message))
  17787. (if use-xcolor
  17788. (progn (if (eq fg 'default)
  17789. (setq fg (org-latex-color :foreground))
  17790. (setq fg (org-latex-color-format fg)))
  17791. (if (eq bg 'default)
  17792. (setq bg (org-latex-color :background))
  17793. (setq bg (org-latex-color-format
  17794. (if (string= bg "Transparent") "white" bg))))
  17795. (with-temp-file texfile
  17796. (insert latex-header)
  17797. (insert "\n\\begin{document}\n"
  17798. "\\definecolor{fg}{rgb}{" fg "}\n"
  17799. "\\definecolor{bg}{rgb}{" bg "}\n"
  17800. "\n\\pagecolor{bg}\n"
  17801. "\n{\\color{fg}\n"
  17802. string
  17803. "\n}\n"
  17804. "\n\\end{document}\n")))
  17805. (if (eq fg 'default)
  17806. (setq fg (org-dvipng-color :foreground))
  17807. (unless (string= fg "Transparent")
  17808. (setq fg (org-dvipng-color-format fg))))
  17809. (if (eq bg 'default)
  17810. (setq bg (org-dvipng-color :background))
  17811. (unless (string= bg "Transparent")
  17812. (setq bg (org-dvipng-color-format bg))))
  17813. (with-temp-file texfile
  17814. (insert latex-header)
  17815. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17816. (let* ((err-msg (format "Please adjust '%s' part of \
  17817. `org-preview-latex-process-alist'."
  17818. processing-type))
  17819. (image-input-file
  17820. (org-compile-file
  17821. texfile latex-compiler image-input-type err-msg log-buf))
  17822. (image-output-file
  17823. (org-compile-file
  17824. image-input-file image-converter image-output-type err-msg log-buf
  17825. `((?F . ,(shell-quote-argument fg))
  17826. (?B . ,(shell-quote-argument bg))
  17827. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17828. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17829. (copy-file image-output-file tofile 'replace)
  17830. (dolist (e post-clean)
  17831. (when (file-exists-p (concat texfilebase e))
  17832. (delete-file (concat texfilebase e))))
  17833. image-output-file)))
  17834. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17835. "Fill a LaTeX header template TPL.
  17836. In the template, the following place holders will be recognized:
  17837. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17838. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17839. [PACKAGES] \\usepackage statements for PKG
  17840. [NO-PACKAGES] do not include PKG
  17841. [EXTRA] the string EXTRA
  17842. [NO-EXTRA] do not include EXTRA
  17843. For backward compatibility, if both the positive and the negative place
  17844. holder is missing, the positive one (without the \"NO-\") will be
  17845. assumed to be present at the end of the template.
  17846. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17847. EXTRA is a string.
  17848. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17849. (let (rpl (end ""))
  17850. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17851. (setq rpl (if (or (match-end 1) (not def-pkg))
  17852. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17853. tpl (replace-match rpl t t tpl))
  17854. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17855. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17856. (setq rpl (if (or (match-end 1) (not pkg))
  17857. "" (org-latex-packages-to-string pkg snippets-p t))
  17858. tpl (replace-match rpl t t tpl))
  17859. (when pkg (setq end
  17860. (concat end "\n"
  17861. (org-latex-packages-to-string pkg snippets-p)))))
  17862. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17863. (setq rpl (if (or (match-end 1) (not extra))
  17864. "" (concat extra "\n"))
  17865. tpl (replace-match rpl t t tpl))
  17866. (when (and extra (string-match "\\S-" extra))
  17867. (setq end (concat end "\n" extra))))
  17868. (if (string-match "\\S-" end)
  17869. (concat tpl "\n" end)
  17870. tpl)))
  17871. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17872. "Turn an alist of packages into a string with the \\usepackage macros."
  17873. (setq pkg (mapconcat (lambda(p)
  17874. (cond
  17875. ((stringp p) p)
  17876. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17877. (format "%% Package %s omitted" (cadr p)))
  17878. ((equal "" (car p))
  17879. (format "\\usepackage{%s}" (cadr p)))
  17880. (t
  17881. (format "\\usepackage[%s]{%s}"
  17882. (car p) (cadr p)))))
  17883. pkg
  17884. "\n"))
  17885. (if newline (concat pkg "\n") pkg))
  17886. (defun org-dvipng-color (attr)
  17887. "Return a RGB color specification for dvipng."
  17888. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17889. (defun org-dvipng-color-format (color-name)
  17890. "Convert COLOR-NAME to a RGB color value for dvipng."
  17891. (apply #'format "rgb %s %s %s"
  17892. (mapcar 'org-normalize-color
  17893. (color-values color-name))))
  17894. (defun org-latex-color (attr)
  17895. "Return a RGB color for the LaTeX color package."
  17896. (org-latex-color-format (face-attribute 'default attr nil)))
  17897. (defun org-latex-color-format (color-name)
  17898. "Convert COLOR-NAME to a RGB color value."
  17899. (apply #'format "%s,%s,%s"
  17900. (mapcar 'org-normalize-color
  17901. (color-values color-name))))
  17902. (defun org-normalize-color (value)
  17903. "Return string to be used as color value for an RGB component."
  17904. (format "%g" (/ value 65535.0)))
  17905. ;; Image display
  17906. (defvar-local org-inline-image-overlays nil)
  17907. (defun org-toggle-inline-images (&optional include-linked)
  17908. "Toggle the display of inline images.
  17909. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17910. (interactive "P")
  17911. (if org-inline-image-overlays
  17912. (progn
  17913. (org-remove-inline-images)
  17914. (when (called-interactively-p 'interactive)
  17915. (message "Inline image display turned off")))
  17916. (org-display-inline-images include-linked)
  17917. (when (called-interactively-p 'interactive)
  17918. (message (if org-inline-image-overlays
  17919. (format "%d images displayed inline"
  17920. (length org-inline-image-overlays))
  17921. "No images to display inline")))))
  17922. (defun org-redisplay-inline-images ()
  17923. "Refresh the display of inline images."
  17924. (interactive)
  17925. (if (not org-inline-image-overlays)
  17926. (org-toggle-inline-images)
  17927. (org-toggle-inline-images)
  17928. (org-toggle-inline-images)))
  17929. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17930. "Display inline images.
  17931. An inline image is a link which follows either of these
  17932. conventions:
  17933. 1. Its path is a file with an extension matching return value
  17934. from `image-file-name-regexp' and it has no contents.
  17935. 2. Its description consists in a single link of the previous
  17936. type.
  17937. When optional argument INCLUDE-LINKED is non-nil, also links with
  17938. a text description part will be inlined. This can be nice for
  17939. a quick look at those images, but it does not reflect what
  17940. exported files will look like.
  17941. When optional argument REFRESH is non-nil, refresh existing
  17942. images between BEG and END. This will create new image displays
  17943. only if necessary. BEG and END default to the buffer
  17944. boundaries."
  17945. (interactive "P")
  17946. (when (display-graphic-p)
  17947. (unless refresh
  17948. (org-remove-inline-images)
  17949. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17950. (org-with-wide-buffer
  17951. (goto-char (or beg (point-min)))
  17952. (let ((case-fold-search t)
  17953. (file-extension-re (image-file-name-regexp)))
  17954. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17955. (let ((link (save-match-data (org-element-context))))
  17956. ;; Check if we're at an inline image.
  17957. (when (and (equal (org-element-property :type link) "file")
  17958. (or include-linked
  17959. (not (org-element-property :contents-begin link)))
  17960. (let ((parent (org-element-property :parent link)))
  17961. (or (not (eq (org-element-type parent) 'link))
  17962. (not (cdr (org-element-contents parent)))))
  17963. (string-match-p file-extension-re
  17964. (org-element-property :path link)))
  17965. (let ((file (expand-file-name
  17966. (org-link-unescape
  17967. (org-element-property :path link)))))
  17968. (when (file-exists-p file)
  17969. (let ((width
  17970. ;; Apply `org-image-actual-width' specifications.
  17971. (cond
  17972. ((not (image-type-available-p 'imagemagick)) nil)
  17973. ((eq org-image-actual-width t) nil)
  17974. ((listp org-image-actual-width)
  17975. (or
  17976. ;; First try to find a width among
  17977. ;; attributes associated to the paragraph
  17978. ;; containing link.
  17979. (let ((paragraph
  17980. (let ((e link))
  17981. (while (and (setq e (org-element-property
  17982. :parent e))
  17983. (not (eq (org-element-type e)
  17984. 'paragraph))))
  17985. e)))
  17986. (when paragraph
  17987. (save-excursion
  17988. (goto-char (org-element-property :begin paragraph))
  17989. (when
  17990. (re-search-forward
  17991. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17992. (org-element-property
  17993. :post-affiliated paragraph)
  17994. t)
  17995. (string-to-number (match-string 1))))))
  17996. ;; Otherwise, fall-back to provided number.
  17997. (car org-image-actual-width)))
  17998. ((numberp org-image-actual-width)
  17999. org-image-actual-width)))
  18000. (old (get-char-property-and-overlay
  18001. (org-element-property :begin link)
  18002. 'org-image-overlay)))
  18003. (if (and (car-safe old) refresh)
  18004. (image-refresh (overlay-get (cdr old) 'display))
  18005. (let ((image (create-image file
  18006. (and width 'imagemagick)
  18007. nil
  18008. :width width)))
  18009. (when image
  18010. (let* ((link
  18011. ;; If inline image is the description
  18012. ;; of another link, be sure to
  18013. ;; consider the latter as the one to
  18014. ;; apply the overlay on.
  18015. (let ((parent
  18016. (org-element-property :parent link)))
  18017. (if (eq (org-element-type parent) 'link)
  18018. parent
  18019. link)))
  18020. (ov (make-overlay
  18021. (org-element-property :begin link)
  18022. (progn
  18023. (goto-char
  18024. (org-element-property :end link))
  18025. (skip-chars-backward " \t")
  18026. (point)))))
  18027. (overlay-put ov 'display image)
  18028. (overlay-put ov 'face 'default)
  18029. (overlay-put ov 'org-image-overlay t)
  18030. (overlay-put
  18031. ov 'modification-hooks
  18032. (list 'org-display-inline-remove-overlay))
  18033. (push ov org-inline-image-overlays)))))))))))))))
  18034. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18035. "Remove inline-display overlay if a corresponding region is modified."
  18036. (let ((inhibit-modification-hooks t))
  18037. (when (and ov after)
  18038. (delete ov org-inline-image-overlays)
  18039. (delete-overlay ov))))
  18040. (defun org-remove-inline-images ()
  18041. "Remove inline display of images."
  18042. (interactive)
  18043. (mapc #'delete-overlay org-inline-image-overlays)
  18044. (setq org-inline-image-overlays nil))
  18045. ;;;; Key bindings
  18046. ;; Outline functions from `outline-mode-prefix-map'
  18047. ;; that can be remapped in Org:
  18048. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18049. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18050. (define-key org-mode-map [remap outline-forward-same-level]
  18051. 'org-forward-heading-same-level)
  18052. (define-key org-mode-map [remap outline-backward-same-level]
  18053. 'org-backward-heading-same-level)
  18054. (define-key org-mode-map [remap outline-show-branches]
  18055. 'org-kill-note-or-show-branches)
  18056. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18057. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18058. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18059. (define-key org-mode-map [remap outline-next-visible-heading]
  18060. 'org-next-visible-heading)
  18061. (define-key org-mode-map [remap outline-previous-visible-heading]
  18062. 'org-previous-visible-heading)
  18063. (define-key org-mode-map [remap show-children] 'org-show-children)
  18064. ;; Outline functions from `outline-mode-prefix-map' that can not
  18065. ;; be remapped in Org:
  18066. ;; - the column "key binding" shows whether the Outline function is still
  18067. ;; available in Org mode on the same key that it has been bound to in
  18068. ;; Outline mode:
  18069. ;; - "overridden": key used for a different functionality in Org mode
  18070. ;; - else: key still bound to the same Outline function in Org mode
  18071. ;; | Outline function | key binding | Org replacement |
  18072. ;; |------------------------------------+-------------+--------------------------|
  18073. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18074. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18075. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18076. ;; | `show-entry' | overridden | no replacement |
  18077. ;; | `show-branches' | `C-c C-k' | still same function |
  18078. ;; | `show-subtree' | overridden | visibility cycling |
  18079. ;; | `show-all' | overridden | no replacement |
  18080. ;; | `hide-subtree' | overridden | visibility cycling |
  18081. ;; | `hide-body' | overridden | no replacement |
  18082. ;; | `hide-entry' | overridden | visibility cycling |
  18083. ;; | `hide-leaves' | overridden | no replacement |
  18084. ;; | `hide-sublevels' | overridden | no replacement |
  18085. ;; | `hide-other' | overridden | no replacement |
  18086. ;; Make `C-c C-x' a prefix key
  18087. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18088. ;; TAB key with modifiers
  18089. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18090. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18091. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18092. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18093. ;; The following line is necessary under Suse GNU/Linux
  18094. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18095. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18096. (define-key org-mode-map [backtab] 'org-shifttab)
  18097. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18098. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18099. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18100. ;; Cursor keys with modifiers
  18101. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18102. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18103. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18104. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18105. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18106. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18107. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18108. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18109. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18110. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18111. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18112. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18113. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18114. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18115. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18116. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18117. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18118. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18119. ;; Babel keys
  18120. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18121. (dolist (pair org-babel-key-bindings)
  18122. (define-key org-babel-map (car pair) (cdr pair)))
  18123. ;;; Extra keys for tty access.
  18124. ;; We only set them when really needed because otherwise the
  18125. ;; menus don't show the simple keys
  18126. (when (or org-use-extra-keys (not window-system))
  18127. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18128. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18129. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18130. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18131. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18132. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18133. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18134. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18135. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18136. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18137. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18138. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18139. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18140. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18141. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18142. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18143. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18144. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18145. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18146. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18147. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18148. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18149. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18150. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18151. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18152. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18153. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18154. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18155. ;; All the other keys
  18156. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18157. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18158. (if (boundp 'narrow-map)
  18159. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18160. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18161. (if (boundp 'narrow-map)
  18162. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18163. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18164. (if (boundp 'narrow-map)
  18165. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18166. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18167. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18168. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18169. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18170. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18171. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18172. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18173. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18174. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18175. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18176. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18177. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18178. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18179. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18180. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18181. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18182. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18183. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18184. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18185. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18186. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18187. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18188. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18189. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18190. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18191. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18192. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18193. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18194. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18195. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18196. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18197. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18198. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18199. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18200. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18201. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18202. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18203. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18204. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18205. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18206. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18207. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18208. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18209. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18210. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18211. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18212. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18213. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18214. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18215. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18216. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18217. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18218. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18219. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18220. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18221. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18222. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18223. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18224. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18225. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18226. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18227. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18228. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18229. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18230. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18231. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18232. (org-defkey org-mode-map "\C-m" 'org-return)
  18233. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18234. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18235. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18236. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18237. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18238. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18239. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18240. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18241. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18242. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18243. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18244. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18245. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18246. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18247. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18248. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18249. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18250. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18251. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18252. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18253. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18254. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18255. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18256. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18257. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18258. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18259. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18260. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18261. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18262. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18263. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18264. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18265. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18266. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18267. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18268. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18269. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18270. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18271. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18272. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18273. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18274. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18275. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18276. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18277. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18278. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18279. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18280. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18281. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18282. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18283. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18284. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18285. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18286. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18287. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18288. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18289. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18290. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18291. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18292. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18293. (defconst org-speed-commands-default
  18294. '(
  18295. ("Outline Navigation")
  18296. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18297. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18298. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18299. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18300. ("F" . org-next-block)
  18301. ("B" . org-previous-block)
  18302. ("u" . (org-speed-move-safe 'outline-up-heading))
  18303. ("j" . org-goto)
  18304. ("g" . (org-refile t))
  18305. ("Outline Visibility")
  18306. ("c" . org-cycle)
  18307. ("C" . org-shifttab)
  18308. (" " . org-display-outline-path)
  18309. ("s" . org-narrow-to-subtree)
  18310. ("=" . org-columns)
  18311. ("Outline Structure Editing")
  18312. ("U" . org-metaup)
  18313. ("D" . org-metadown)
  18314. ("r" . org-metaright)
  18315. ("l" . org-metaleft)
  18316. ("R" . org-shiftmetaright)
  18317. ("L" . org-shiftmetaleft)
  18318. ("i" . (progn (forward-char 1) (call-interactively
  18319. 'org-insert-heading-respect-content)))
  18320. ("^" . org-sort)
  18321. ("w" . org-refile)
  18322. ("a" . org-archive-subtree-default-with-confirmation)
  18323. ("@" . org-mark-subtree)
  18324. ("#" . org-toggle-comment)
  18325. ("Clock Commands")
  18326. ("I" . org-clock-in)
  18327. ("O" . org-clock-out)
  18328. ("Meta Data Editing")
  18329. ("t" . org-todo)
  18330. ("," . (org-priority))
  18331. ("0" . (org-priority ?\ ))
  18332. ("1" . (org-priority ?A))
  18333. ("2" . (org-priority ?B))
  18334. ("3" . (org-priority ?C))
  18335. (":" . org-set-tags-command)
  18336. ("e" . org-set-effort)
  18337. ("E" . org-inc-effort)
  18338. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18339. (org-entry-put (point) "APPT_WARNTIME" m)))
  18340. ("Agenda Views etc")
  18341. ("v" . org-agenda)
  18342. ("/" . org-sparse-tree)
  18343. ("Misc")
  18344. ("o" . org-open-at-point)
  18345. ("?" . org-speed-command-help)
  18346. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18347. (">" . (org-agenda-remove-restriction-lock))
  18348. )
  18349. "The default speed commands.")
  18350. (defun org-print-speed-command (e)
  18351. (if (> (length (car e)) 1)
  18352. (progn
  18353. (princ "\n")
  18354. (princ (car e))
  18355. (princ "\n")
  18356. (princ (make-string (length (car e)) ?-))
  18357. (princ "\n"))
  18358. (princ (car e))
  18359. (princ " ")
  18360. (if (symbolp (cdr e))
  18361. (princ (symbol-name (cdr e)))
  18362. (prin1 (cdr e)))
  18363. (princ "\n")))
  18364. (defun org-speed-command-help ()
  18365. "Show the available speed commands."
  18366. (interactive)
  18367. (if (not org-use-speed-commands)
  18368. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18369. (with-output-to-temp-buffer "*Help*"
  18370. (princ "User-defined Speed commands\n===========================\n")
  18371. (mapc #'org-print-speed-command org-speed-commands-user)
  18372. (princ "\n")
  18373. (princ "Built-in Speed commands\n=======================\n")
  18374. (mapc #'org-print-speed-command org-speed-commands-default))
  18375. (with-current-buffer "*Help*"
  18376. (setq truncate-lines t))))
  18377. (defun org-speed-move-safe (cmd)
  18378. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18379. If not, return to the original position and throw an error."
  18380. (interactive)
  18381. (let ((pos (point)))
  18382. (call-interactively cmd)
  18383. (unless (and (bolp) (org-at-heading-p))
  18384. (goto-char pos)
  18385. (error "Boundary reached while executing %s" cmd))))
  18386. (defvar org-self-insert-command-undo-counter 0)
  18387. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18388. (defvar org-speed-command nil)
  18389. (defun org-speed-command-activate (keys)
  18390. "Hook for activating single-letter speed commands.
  18391. `org-speed-commands-default' specifies a minimal command set.
  18392. Use `org-speed-commands-user' for further customization."
  18393. (when (or (and (bolp) (looking-at org-outline-regexp))
  18394. (and (functionp org-use-speed-commands)
  18395. (funcall org-use-speed-commands)))
  18396. (cdr (assoc keys (append org-speed-commands-user
  18397. org-speed-commands-default)))))
  18398. (defun org-babel-speed-command-activate (keys)
  18399. "Hook for activating single-letter code block commands."
  18400. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18401. (cdr (assoc keys org-babel-key-bindings))))
  18402. (defcustom org-speed-command-hook
  18403. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18404. "Hook for activating speed commands at strategic locations.
  18405. Hook functions are called in sequence until a valid handler is
  18406. found.
  18407. Each hook takes a single argument, a user-pressed command key
  18408. which is also a `self-insert-command' from the global map.
  18409. Within the hook, examine the cursor position and the command key
  18410. and return nil or a valid handler as appropriate. Handler could
  18411. be one of an interactive command, a function, or a form.
  18412. Set `org-use-speed-commands' to non-nil value to enable this
  18413. hook. The default setting is `org-speed-command-activate'."
  18414. :group 'org-structure
  18415. :version "24.1"
  18416. :type 'hook)
  18417. (defun org-self-insert-command (N)
  18418. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18419. If the cursor is in a table looking at whitespace, the whitespace is
  18420. overwritten, and the table is not marked as requiring realignment."
  18421. (interactive "p")
  18422. (org-check-before-invisible-edit 'insert)
  18423. (cond
  18424. ((and org-use-speed-commands
  18425. (let ((kv (this-command-keys-vector)))
  18426. (setq org-speed-command
  18427. (run-hook-with-args-until-success
  18428. 'org-speed-command-hook
  18429. (make-string 1 (aref kv (1- (length kv))))))))
  18430. (cond
  18431. ((commandp org-speed-command)
  18432. (setq this-command org-speed-command)
  18433. (call-interactively org-speed-command))
  18434. ((functionp org-speed-command)
  18435. (funcall org-speed-command))
  18436. ((and org-speed-command (listp org-speed-command))
  18437. (eval org-speed-command))
  18438. (t (let (org-use-speed-commands)
  18439. (call-interactively 'org-self-insert-command)))))
  18440. ((and
  18441. (org-at-table-p)
  18442. (progn
  18443. ;; Check if we blank the field, and if that triggers align.
  18444. (and (featurep 'org-table) org-table-auto-blank-field
  18445. (memq last-command
  18446. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18447. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18448. ;; Got extra space, this field does not determine
  18449. ;; column width.
  18450. (let (org-table-may-need-update) (org-table-blank-field))
  18451. ;; No extra space, this field may determine column
  18452. ;; width.
  18453. (org-table-blank-field)))
  18454. t)
  18455. (eq N 1)
  18456. (looking-at "[^|\n]* \\( \\)|"))
  18457. ;; There is room for insertion without re-aligning the table.
  18458. (delete-region (match-beginning 1) (match-end 1))
  18459. (self-insert-command N))
  18460. (t
  18461. (setq org-table-may-need-update t)
  18462. (self-insert-command N)
  18463. (org-fix-tags-on-the-fly)
  18464. (when org-self-insert-cluster-for-undo
  18465. (if (not (eq last-command 'org-self-insert-command))
  18466. (setq org-self-insert-command-undo-counter 1)
  18467. (if (>= org-self-insert-command-undo-counter 20)
  18468. (setq org-self-insert-command-undo-counter 1)
  18469. (and (> org-self-insert-command-undo-counter 0)
  18470. buffer-undo-list (listp buffer-undo-list)
  18471. (not (cadr buffer-undo-list)) ; remove nil entry
  18472. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18473. (setq org-self-insert-command-undo-counter
  18474. (1+ org-self-insert-command-undo-counter))))))))
  18475. (defun org-check-before-invisible-edit (kind)
  18476. "Check is editing if kind KIND would be dangerous with invisible text around.
  18477. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18478. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18479. (when (and org-catch-invisible-edits
  18480. (or (not (boundp 'visible-mode)) (not visible-mode))
  18481. (or (get-char-property (point) 'invisible)
  18482. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18483. ;; OK, we need to take a closer look
  18484. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18485. (invisible-before-point (unless (bobp) (get-char-property
  18486. (1- (point)) 'invisible)))
  18487. (border-and-ok-direction
  18488. (or
  18489. ;; Check if we are acting predictably before invisible text
  18490. (and invisible-at-point (not invisible-before-point)
  18491. (memq kind '(insert delete-backward)))
  18492. ;; Check if we are acting predictably after invisible text
  18493. ;; This works not well, and I have turned it off. It seems
  18494. ;; better to always show and stop after invisible text.
  18495. ;; (and (not invisible-at-point) invisible-before-point
  18496. ;; (memq kind '(insert delete)))
  18497. )))
  18498. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18499. (memq invisible-before-point '(outline org-hide-block t)))
  18500. (when (eq org-catch-invisible-edits 'error)
  18501. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18502. (if (and org-custom-properties-overlays
  18503. (y-or-n-p "Display invisible properties in this buffer? "))
  18504. (org-toggle-custom-properties-visibility)
  18505. ;; Make the area visible
  18506. (save-excursion
  18507. (when invisible-before-point
  18508. (goto-char (previous-single-char-property-change
  18509. (point) 'invisible)))
  18510. (outline-show-subtree))
  18511. (cond
  18512. ((eq org-catch-invisible-edits 'show)
  18513. ;; That's it, we do the edit after showing
  18514. (message
  18515. "Unfolding invisible region around point before editing")
  18516. (sit-for 1))
  18517. ((and (eq org-catch-invisible-edits 'smart)
  18518. border-and-ok-direction)
  18519. (message "Unfolding invisible region around point before editing"))
  18520. (t
  18521. ;; Don't do the edit, make the user repeat it in full visibility
  18522. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18523. (defun org-fix-tags-on-the-fly ()
  18524. (when (and (equal (char-after (point-at-bol)) ?*)
  18525. (org-at-heading-p))
  18526. (org-align-tags-here org-tags-column)))
  18527. (defun org-delete-backward-char (N)
  18528. "Like `delete-backward-char', insert whitespace at field end in tables.
  18529. When deleting backwards, in tables this function will insert whitespace in
  18530. front of the next \"|\" separator, to keep the table aligned. The table will
  18531. still be marked for re-alignment if the field did fill the entire column,
  18532. because, in this case the deletion might narrow the column."
  18533. (interactive "p")
  18534. (save-match-data
  18535. (org-check-before-invisible-edit 'delete-backward)
  18536. (if (and (org-at-table-p)
  18537. (eq N 1)
  18538. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18539. (looking-at ".*?|"))
  18540. (let ((pos (point))
  18541. (noalign (looking-at "[^|\n\r]* |"))
  18542. (c org-table-may-need-update))
  18543. (backward-delete-char N)
  18544. (unless overwrite-mode
  18545. (skip-chars-forward "^|")
  18546. (insert " ")
  18547. (goto-char (1- pos)))
  18548. ;; noalign: if there were two spaces at the end, this field
  18549. ;; does not determine the width of the column.
  18550. (when noalign (setq org-table-may-need-update c)))
  18551. (backward-delete-char N)
  18552. (org-fix-tags-on-the-fly))))
  18553. (defun org-delete-char (N)
  18554. "Like `delete-char', but insert whitespace at field end in tables.
  18555. When deleting characters, in tables this function will insert whitespace in
  18556. front of the next \"|\" separator, to keep the table aligned. The table will
  18557. still be marked for re-alignment if the field did fill the entire column,
  18558. because, in this case the deletion might narrow the column."
  18559. (interactive "p")
  18560. (save-match-data
  18561. (org-check-before-invisible-edit 'delete)
  18562. (if (and (org-at-table-p)
  18563. (not (bolp))
  18564. (not (= (char-after) ?|))
  18565. (eq N 1))
  18566. (if (looking-at ".*?|")
  18567. (let ((pos (point))
  18568. (noalign (looking-at "[^|\n\r]* |"))
  18569. (c org-table-may-need-update))
  18570. (replace-match
  18571. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18572. (goto-char pos)
  18573. ;; noalign: if there were two spaces at the end, this field
  18574. ;; does not determine the width of the column.
  18575. (when noalign (setq org-table-may-need-update c)))
  18576. (delete-char N))
  18577. (delete-char N)
  18578. (org-fix-tags-on-the-fly))))
  18579. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18580. (put 'org-self-insert-command 'delete-selection
  18581. (lambda ()
  18582. (not (run-hook-with-args-until-success
  18583. 'self-insert-uses-region-functions))))
  18584. (put 'orgtbl-self-insert-command 'delete-selection
  18585. (lambda ()
  18586. (not (run-hook-with-args-until-success
  18587. 'self-insert-uses-region-functions))))
  18588. (put 'org-delete-char 'delete-selection 'supersede)
  18589. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18590. (put 'org-yank 'delete-selection 'yank)
  18591. ;; Make `flyspell-mode' delay after some commands
  18592. (put 'org-self-insert-command 'flyspell-delayed t)
  18593. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18594. (put 'org-delete-char 'flyspell-delayed t)
  18595. (put 'org-delete-backward-char 'flyspell-delayed t)
  18596. ;; Make pabbrev-mode expand after Org mode commands
  18597. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18598. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18599. (defun org-remap (map &rest commands)
  18600. "In MAP, remap the functions given in COMMANDS.
  18601. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18602. (let (new old)
  18603. (while commands
  18604. (setq old (pop commands) new (pop commands))
  18605. (org-defkey map (vector 'remap old) new))))
  18606. (defun org-transpose-words ()
  18607. "Transpose words for Org.
  18608. This uses the `org-mode-transpose-word-syntax-table' syntax
  18609. table, which interprets characters in `org-emphasis-alist' as
  18610. word constituents."
  18611. (interactive)
  18612. (with-syntax-table org-mode-transpose-word-syntax-table
  18613. (call-interactively 'transpose-words)))
  18614. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18615. (when (eq org-enable-table-editor 'optimized)
  18616. ;; If the user wants maximum table support, we need to hijack
  18617. ;; some standard editing functions
  18618. (org-remap org-mode-map
  18619. 'self-insert-command 'org-self-insert-command
  18620. 'delete-char 'org-delete-char
  18621. 'delete-backward-char 'org-delete-backward-char)
  18622. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18623. (defvar org-ctrl-c-ctrl-c-hook nil
  18624. "Hook for functions attaching themselves to `C-c C-c'.
  18625. This can be used to add additional functionality to the C-c C-c
  18626. key which executes context-dependent commands. This hook is run
  18627. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18628. run after the last test.
  18629. Each function will be called with no arguments. The function
  18630. must check if the context is appropriate for it to act. If yes,
  18631. it should do its thing and then return a non-nil value. If the
  18632. context is wrong, just do nothing and return nil.")
  18633. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18634. "Hook for functions attaching themselves to `C-c C-c'.
  18635. This can be used to add additional functionality to the C-c C-c
  18636. key which executes context-dependent commands. This hook is run
  18637. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18638. before the first test.
  18639. Each function will be called with no arguments. The function
  18640. must check if the context is appropriate for it to act. If yes,
  18641. it should do its thing and then return a non-nil value. If the
  18642. context is wrong, just do nothing and return nil.")
  18643. (defvar org-tab-first-hook nil
  18644. "Hook for functions to attach themselves to TAB.
  18645. See `org-ctrl-c-ctrl-c-hook' for more information.
  18646. This hook runs as the first action when TAB is pressed, even before
  18647. `org-cycle' messes around with the `outline-regexp' to cater for
  18648. inline tasks and plain list item folding.
  18649. If any function in this hook returns t, any other actions that
  18650. would have been caused by TAB (such as table field motion or visibility
  18651. cycling) will not occur.")
  18652. (defvar org-tab-after-check-for-table-hook nil
  18653. "Hook for functions to attach themselves to TAB.
  18654. See `org-ctrl-c-ctrl-c-hook' for more information.
  18655. This hook runs after it has been established that the cursor is not in a
  18656. table, but before checking if the cursor is in a headline or if global cycling
  18657. should be done.
  18658. If any function in this hook returns t, not other actions like visibility
  18659. cycling will be done.")
  18660. (defvar org-tab-after-check-for-cycling-hook nil
  18661. "Hook for functions to attach themselves to TAB.
  18662. See `org-ctrl-c-ctrl-c-hook' for more information.
  18663. This hook runs after it has been established that not table field motion and
  18664. not visibility should be done because of current context. This is probably
  18665. the place where a package like yasnippets can hook in.")
  18666. (defvar org-tab-before-tab-emulation-hook nil
  18667. "Hook for functions to attach themselves to TAB.
  18668. See `org-ctrl-c-ctrl-c-hook' for more information.
  18669. This hook runs after every other options for TAB have been exhausted, but
  18670. before indentation and \t insertion takes place.")
  18671. (defvar org-metaleft-hook nil
  18672. "Hook for functions attaching themselves to `M-left'.
  18673. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18674. (defvar org-metaright-hook nil
  18675. "Hook for functions attaching themselves to `M-right'.
  18676. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18677. (defvar org-metaup-hook nil
  18678. "Hook for functions attaching themselves to `M-up'.
  18679. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18680. (defvar org-metadown-hook nil
  18681. "Hook for functions attaching themselves to `M-down'.
  18682. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18683. (defvar org-shiftmetaleft-hook nil
  18684. "Hook for functions attaching themselves to `M-S-left'.
  18685. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18686. (defvar org-shiftmetaright-hook nil
  18687. "Hook for functions attaching themselves to `M-S-right'.
  18688. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18689. (defvar org-shiftmetaup-hook nil
  18690. "Hook for functions attaching themselves to `M-S-up'.
  18691. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18692. (defvar org-shiftmetadown-hook nil
  18693. "Hook for functions attaching themselves to `M-S-down'.
  18694. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18695. (defvar org-metareturn-hook nil
  18696. "Hook for functions attaching themselves to `M-RET'.
  18697. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18698. (defvar org-shiftup-hook nil
  18699. "Hook for functions attaching themselves to `S-up'.
  18700. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18701. (defvar org-shiftup-final-hook nil
  18702. "Hook for functions attaching themselves to `S-up'.
  18703. This one runs after all other options except shift-select have been excluded.
  18704. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18705. (defvar org-shiftdown-hook nil
  18706. "Hook for functions attaching themselves to `S-down'.
  18707. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18708. (defvar org-shiftdown-final-hook nil
  18709. "Hook for functions attaching themselves to `S-down'.
  18710. This one runs after all other options except shift-select have been excluded.
  18711. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18712. (defvar org-shiftleft-hook nil
  18713. "Hook for functions attaching themselves to `S-left'.
  18714. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18715. (defvar org-shiftleft-final-hook nil
  18716. "Hook for functions attaching themselves to `S-left'.
  18717. This one runs after all other options except shift-select have been excluded.
  18718. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18719. (defvar org-shiftright-hook nil
  18720. "Hook for functions attaching themselves to `S-right'.
  18721. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18722. (defvar org-shiftright-final-hook nil
  18723. "Hook for functions attaching themselves to `S-right'.
  18724. This one runs after all other options except shift-select have been excluded.
  18725. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18726. (defun org-modifier-cursor-error ()
  18727. "Throw an error, a modified cursor command was applied in wrong context."
  18728. (user-error "This command is active in special context like tables, headlines or items"))
  18729. (defun org-shiftselect-error ()
  18730. "Throw an error because Shift-Cursor command was applied in wrong context."
  18731. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18732. (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
  18733. (user-error "This command works only in special context like headlines or timestamps")))
  18734. (defun org-call-for-shift-select (cmd)
  18735. (let ((this-command-keys-shift-translated t))
  18736. (call-interactively cmd)))
  18737. (defun org-shifttab (&optional arg)
  18738. "Global visibility cycling or move to previous table field.
  18739. Call `org-table-previous-field' within a table.
  18740. When ARG is nil, cycle globally through visibility states.
  18741. When ARG is a numeric prefix, show contents of this level."
  18742. (interactive "P")
  18743. (cond
  18744. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18745. ((integerp arg)
  18746. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18747. (message "Content view to level: %d" arg)
  18748. (org-content (prefix-numeric-value arg2))
  18749. (org-cycle-show-empty-lines t)
  18750. (setq org-cycle-global-status 'overview)))
  18751. (t (call-interactively 'org-global-cycle))))
  18752. (defun org-shiftmetaleft ()
  18753. "Promote subtree or delete table column.
  18754. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18755. `org-table-delete-column', depending on context. See the
  18756. individual commands for more information."
  18757. (interactive)
  18758. (cond
  18759. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18760. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18761. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18762. ((if (not (org-region-active-p)) (org-at-item-p)
  18763. (save-excursion (goto-char (region-beginning))
  18764. (org-at-item-p)))
  18765. (call-interactively 'org-outdent-item-tree))
  18766. (t (org-modifier-cursor-error))))
  18767. (defun org-shiftmetaright ()
  18768. "Demote subtree or insert table column.
  18769. Calls `org-demote-subtree', `org-indent-item-tree', or
  18770. `org-table-insert-column', depending on context. See the
  18771. individual commands for more information."
  18772. (interactive)
  18773. (cond
  18774. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18775. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18776. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18777. ((if (not (org-region-active-p)) (org-at-item-p)
  18778. (save-excursion (goto-char (region-beginning))
  18779. (org-at-item-p)))
  18780. (call-interactively 'org-indent-item-tree))
  18781. (t (org-modifier-cursor-error))))
  18782. (defun org-shiftmetaup (&optional _arg)
  18783. "Drag the line at point up.
  18784. In a table, kill the current row.
  18785. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18786. but also adjust the previous clocked item in the clock history.
  18787. Everywhere else, drag the line at point up."
  18788. (interactive "P")
  18789. (cond
  18790. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18791. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18792. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18793. (call-interactively 'org-timestamp-up)))
  18794. (t (call-interactively 'org-drag-line-backward))))
  18795. (defun org-shiftmetadown (&optional _arg)
  18796. "Drag the line at point down.
  18797. In a table, insert an empty row at the current line.
  18798. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18799. but also adjust the previous clocked item in the clock history.
  18800. Everywhere else, drag the line at point down."
  18801. (interactive "P")
  18802. (cond
  18803. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18804. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18805. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18806. (call-interactively 'org-timestamp-down)))
  18807. (t (call-interactively 'org-drag-line-forward))))
  18808. (defsubst org-hidden-tree-error ()
  18809. (user-error
  18810. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18811. (defun org-metaleft (&optional _arg)
  18812. "Promote heading, list item at point or move table column left.
  18813. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18814. depending on context. With no specific context, calls the Emacs
  18815. default `backward-word'. See the individual commands for more
  18816. information.
  18817. This function runs the hook `org-metaleft-hook' as a first step,
  18818. and returns at first non-nil value."
  18819. (interactive "P")
  18820. (cond
  18821. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18822. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18823. ((org-with-limited-levels
  18824. (or (org-at-heading-p)
  18825. (and (org-region-active-p)
  18826. (save-excursion
  18827. (goto-char (region-beginning))
  18828. (org-at-heading-p)))))
  18829. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18830. (call-interactively 'org-do-promote))
  18831. ;; At an inline task.
  18832. ((org-at-heading-p)
  18833. (call-interactively 'org-inlinetask-promote))
  18834. ((or (org-at-item-p)
  18835. (and (org-region-active-p)
  18836. (save-excursion
  18837. (goto-char (region-beginning))
  18838. (org-at-item-p))))
  18839. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18840. (call-interactively 'org-outdent-item))
  18841. (t (call-interactively 'backward-word))))
  18842. (defun org-metaright (&optional _arg)
  18843. "Demote heading, list item at point or move table column right.
  18844. In front of a drawer or a block keyword, indent it correctly.
  18845. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18846. `org-indent-drawer' or `org-indent-block' depending on context.
  18847. With no specific context, calls the Emacs default `forward-word'.
  18848. See the individual commands for more information.
  18849. This function runs the hook `org-metaright-hook' as a first step,
  18850. and returns at first non-nil value."
  18851. (interactive "P")
  18852. (cond
  18853. ((run-hook-with-args-until-success 'org-metaright-hook))
  18854. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18855. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18856. ((org-at-block-p) (call-interactively 'org-indent-block))
  18857. ((org-with-limited-levels
  18858. (or (org-at-heading-p)
  18859. (and (org-region-active-p)
  18860. (save-excursion
  18861. (goto-char (region-beginning))
  18862. (org-at-heading-p)))))
  18863. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18864. (call-interactively 'org-do-demote))
  18865. ;; At an inline task.
  18866. ((org-at-heading-p)
  18867. (call-interactively 'org-inlinetask-demote))
  18868. ((or (org-at-item-p)
  18869. (and (org-region-active-p)
  18870. (save-excursion
  18871. (goto-char (region-beginning))
  18872. (org-at-item-p))))
  18873. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18874. (call-interactively 'org-indent-item))
  18875. (t (call-interactively 'forward-word))))
  18876. (defun org-check-for-hidden (what)
  18877. "Check if there are hidden headlines/items in the current visual line.
  18878. WHAT can be either `headlines' or `items'. If the current line is
  18879. an outline or item heading and it has a folded subtree below it,
  18880. this function returns t, nil otherwise."
  18881. (let ((re (cond
  18882. ((eq what 'headlines) org-outline-regexp-bol)
  18883. ((eq what 'items) (org-item-beginning-re))
  18884. (t (error "This should not happen"))))
  18885. beg end)
  18886. (save-excursion
  18887. (catch 'exit
  18888. (unless (org-region-active-p)
  18889. (setq beg (point-at-bol))
  18890. (beginning-of-line 2)
  18891. (while (and (not (eobp)) ;; this is like `next-line'
  18892. (get-char-property (1- (point)) 'invisible))
  18893. (beginning-of-line 2))
  18894. (setq end (point))
  18895. (goto-char beg)
  18896. (goto-char (point-at-eol))
  18897. (setq end (max end (point)))
  18898. (while (re-search-forward re end t)
  18899. (when (get-char-property (match-beginning 0) 'invisible)
  18900. (throw 'exit t))))
  18901. nil))))
  18902. (defun org-metaup (&optional _arg)
  18903. "Move subtree up or move table row up.
  18904. Calls `org-move-subtree-up' or `org-table-move-row' or
  18905. `org-move-item-up', depending on context. See the individual commands
  18906. for more information."
  18907. (interactive "P")
  18908. (cond
  18909. ((run-hook-with-args-until-success 'org-metaup-hook))
  18910. ((org-region-active-p)
  18911. (let* ((a (min (region-beginning) (region-end)))
  18912. (b (1- (max (region-beginning) (region-end))))
  18913. (c (save-excursion (goto-char a)
  18914. (move-beginning-of-line 0)))
  18915. (d (save-excursion (goto-char a)
  18916. (move-end-of-line 0) (point))))
  18917. (transpose-regions a b c d)
  18918. (goto-char c)))
  18919. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18920. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18921. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18922. (t (org-drag-element-backward))))
  18923. (defun org-metadown (&optional _arg)
  18924. "Move subtree down or move table row down.
  18925. Calls `org-move-subtree-down' or `org-table-move-row' or
  18926. `org-move-item-down', depending on context. See the individual
  18927. commands for more information."
  18928. (interactive "P")
  18929. (cond
  18930. ((run-hook-with-args-until-success 'org-metadown-hook))
  18931. ((org-region-active-p)
  18932. (let* ((a (min (region-beginning) (region-end)))
  18933. (b (max (region-beginning) (region-end)))
  18934. (c (save-excursion (goto-char b)
  18935. (move-beginning-of-line 1)))
  18936. (d (save-excursion (goto-char b)
  18937. (move-end-of-line 1) (1+ (point)))))
  18938. (transpose-regions a b c d)
  18939. (goto-char d)))
  18940. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18941. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18942. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18943. (t (org-drag-element-forward))))
  18944. (defun org-shiftup (&optional arg)
  18945. "Increase item in timestamp or increase priority of current headline.
  18946. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18947. depending on context. See the individual commands for more information."
  18948. (interactive "P")
  18949. (cond
  18950. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18951. ((and org-support-shift-select (org-region-active-p))
  18952. (org-call-for-shift-select 'previous-line))
  18953. ((org-at-timestamp-p t)
  18954. (call-interactively (if org-edit-timestamp-down-means-later
  18955. 'org-timestamp-down 'org-timestamp-up)))
  18956. ((and (not (eq org-support-shift-select 'always))
  18957. org-enable-priority-commands
  18958. (org-at-heading-p))
  18959. (call-interactively 'org-priority-up))
  18960. ((and (not org-support-shift-select) (org-at-item-p))
  18961. (call-interactively 'org-previous-item))
  18962. ((org-clocktable-try-shift 'up arg))
  18963. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18964. (org-support-shift-select
  18965. (org-call-for-shift-select 'previous-line))
  18966. (t (org-shiftselect-error))))
  18967. (defun org-shiftdown (&optional arg)
  18968. "Decrease item in timestamp or decrease priority of current headline.
  18969. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18970. depending on context. See the individual commands for more information."
  18971. (interactive "P")
  18972. (cond
  18973. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18974. ((and org-support-shift-select (org-region-active-p))
  18975. (org-call-for-shift-select 'next-line))
  18976. ((org-at-timestamp-p t)
  18977. (call-interactively (if org-edit-timestamp-down-means-later
  18978. 'org-timestamp-up 'org-timestamp-down)))
  18979. ((and (not (eq org-support-shift-select 'always))
  18980. org-enable-priority-commands
  18981. (org-at-heading-p))
  18982. (call-interactively 'org-priority-down))
  18983. ((and (not org-support-shift-select) (org-at-item-p))
  18984. (call-interactively 'org-next-item))
  18985. ((org-clocktable-try-shift 'down arg))
  18986. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18987. (org-support-shift-select
  18988. (org-call-for-shift-select 'next-line))
  18989. (t (org-shiftselect-error))))
  18990. (defun org-shiftright (&optional arg)
  18991. "Cycle the thing at point or in the current line, depending on context.
  18992. Depending on context, this does one of the following:
  18993. - switch a timestamp at point one day into the future
  18994. - on a headline, switch to the next TODO keyword.
  18995. - on an item, switch entire list to the next bullet type
  18996. - on a property line, switch to the next allowed value
  18997. - on a clocktable definition line, move time block into the future"
  18998. (interactive "P")
  18999. (cond
  19000. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19001. ((and org-support-shift-select (org-region-active-p))
  19002. (org-call-for-shift-select 'forward-char))
  19003. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19004. ((and (not (eq org-support-shift-select 'always))
  19005. (org-at-heading-p))
  19006. (let ((org-inhibit-logging
  19007. (not org-treat-S-cursor-todo-selection-as-state-change))
  19008. (org-inhibit-blocking
  19009. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19010. (org-call-with-arg 'org-todo 'right)))
  19011. ((or (and org-support-shift-select
  19012. (not (eq org-support-shift-select 'always))
  19013. (org-at-item-bullet-p))
  19014. (and (not org-support-shift-select) (org-at-item-p)))
  19015. (org-call-with-arg 'org-cycle-list-bullet nil))
  19016. ((and (not (eq org-support-shift-select 'always))
  19017. (org-at-property-p))
  19018. (call-interactively 'org-property-next-allowed-value))
  19019. ((org-clocktable-try-shift 'right arg))
  19020. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19021. (org-support-shift-select
  19022. (org-call-for-shift-select 'forward-char))
  19023. (t (org-shiftselect-error))))
  19024. (defun org-shiftleft (&optional arg)
  19025. "Cycle the thing at point or in the current line, depending on context.
  19026. Depending on context, this does one of the following:
  19027. - switch a timestamp at point one day into the past
  19028. - on a headline, switch to the previous TODO keyword.
  19029. - on an item, switch entire list to the previous bullet type
  19030. - on a property line, switch to the previous allowed value
  19031. - on a clocktable definition line, move time block into the past"
  19032. (interactive "P")
  19033. (cond
  19034. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19035. ((and org-support-shift-select (org-region-active-p))
  19036. (org-call-for-shift-select 'backward-char))
  19037. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19038. ((and (not (eq org-support-shift-select 'always))
  19039. (org-at-heading-p))
  19040. (let ((org-inhibit-logging
  19041. (not org-treat-S-cursor-todo-selection-as-state-change))
  19042. (org-inhibit-blocking
  19043. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19044. (org-call-with-arg 'org-todo 'left)))
  19045. ((or (and org-support-shift-select
  19046. (not (eq org-support-shift-select 'always))
  19047. (org-at-item-bullet-p))
  19048. (and (not org-support-shift-select) (org-at-item-p)))
  19049. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19050. ((and (not (eq org-support-shift-select 'always))
  19051. (org-at-property-p))
  19052. (call-interactively 'org-property-previous-allowed-value))
  19053. ((org-clocktable-try-shift 'left arg))
  19054. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19055. (org-support-shift-select
  19056. (org-call-for-shift-select 'backward-char))
  19057. (t (org-shiftselect-error))))
  19058. (defun org-shiftcontrolright ()
  19059. "Switch to next TODO set."
  19060. (interactive)
  19061. (cond
  19062. ((and org-support-shift-select (org-region-active-p))
  19063. (org-call-for-shift-select 'forward-word))
  19064. ((and (not (eq org-support-shift-select 'always))
  19065. (org-at-heading-p))
  19066. (org-call-with-arg 'org-todo 'nextset))
  19067. (org-support-shift-select
  19068. (org-call-for-shift-select 'forward-word))
  19069. (t (org-shiftselect-error))))
  19070. (defun org-shiftcontrolleft ()
  19071. "Switch to previous TODO set."
  19072. (interactive)
  19073. (cond
  19074. ((and org-support-shift-select (org-region-active-p))
  19075. (org-call-for-shift-select 'backward-word))
  19076. ((and (not (eq org-support-shift-select 'always))
  19077. (org-at-heading-p))
  19078. (org-call-with-arg 'org-todo 'previousset))
  19079. (org-support-shift-select
  19080. (org-call-for-shift-select 'backward-word))
  19081. (t (org-shiftselect-error))))
  19082. (defun org-shiftcontrolup (&optional n)
  19083. "Change timestamps synchronously up in CLOCK log lines.
  19084. Optional argument N tells to change by that many units."
  19085. (interactive "P")
  19086. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19087. (let (org-support-shift-select)
  19088. (org-clock-timestamps-up n))
  19089. (user-error "Not at a clock log")))
  19090. (defun org-shiftcontroldown (&optional n)
  19091. "Change timestamps synchronously down in CLOCK log lines.
  19092. Optional argument N tells to change by that many units."
  19093. (interactive "P")
  19094. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19095. (let (org-support-shift-select)
  19096. (org-clock-timestamps-down n))
  19097. (user-error "Not at a clock log")))
  19098. (defun org-increase-number-at-point (&optional inc)
  19099. "Increment the number at point.
  19100. With an optional prefix numeric argument INC, increment using
  19101. this numeric value."
  19102. (interactive "p")
  19103. (if (not (number-at-point))
  19104. (user-error "Not on a number")
  19105. (unless inc (setq inc 1))
  19106. (let ((pos (point))
  19107. (beg (skip-chars-backward "-+^/*0-9eE."))
  19108. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19109. (setq nap (buffer-substring-no-properties
  19110. (+ pos beg) (+ pos beg end)))
  19111. (delete-region (+ pos beg) (+ pos beg end))
  19112. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19113. (when (org-at-table-p)
  19114. (org-table-align)
  19115. (org-table-end-of-field 1))))
  19116. (defun org-decrease-number-at-point (&optional inc)
  19117. "Decrement the number at point.
  19118. With an optional prefix numeric argument INC, decrement using
  19119. this numeric value."
  19120. (interactive "p")
  19121. (org-increase-number-at-point (- (or inc 1))))
  19122. (defun org-ctrl-c-ret ()
  19123. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19124. (interactive)
  19125. (cond
  19126. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19127. (t (call-interactively 'org-insert-heading))))
  19128. (defun org-find-visible ()
  19129. (let ((s (point)))
  19130. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19131. (get-char-property s 'invisible)))
  19132. s))
  19133. (defun org-find-invisible ()
  19134. (let ((s (point)))
  19135. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19136. (not (get-char-property s 'invisible))))
  19137. s))
  19138. (defun org-copy-visible (beg end)
  19139. "Copy the visible parts of the region."
  19140. (interactive "r")
  19141. (let (snippets s)
  19142. (save-excursion
  19143. (save-restriction
  19144. (narrow-to-region beg end)
  19145. (setq s (goto-char (point-min)))
  19146. (while (not (= (point) (point-max)))
  19147. (goto-char (org-find-invisible))
  19148. (push (buffer-substring s (point)) snippets)
  19149. (setq s (goto-char (org-find-visible))))))
  19150. (kill-new (apply 'concat (nreverse snippets)))))
  19151. (defun org-copy-special ()
  19152. "Copy region in table or copy current subtree.
  19153. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19154. context. See the individual commands for more information."
  19155. (interactive)
  19156. (call-interactively
  19157. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19158. (defun org-cut-special ()
  19159. "Cut region in table or cut current subtree.
  19160. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19161. context. See the individual commands for more information."
  19162. (interactive)
  19163. (call-interactively
  19164. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19165. (defun org-paste-special (arg)
  19166. "Paste rectangular region into table, or past subtree relative to level.
  19167. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19168. See the individual commands for more information."
  19169. (interactive "P")
  19170. (if (org-at-table-p)
  19171. (org-table-paste-rectangle)
  19172. (org-paste-subtree arg)))
  19173. (defun org-edit-special (&optional arg)
  19174. "Call a special editor for the element at point.
  19175. When at a table, call the formula editor with `org-table-edit-formulas'.
  19176. When in a source code block, call `org-edit-src-code'.
  19177. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19178. When in an export block, call `org-edit-export-block'.
  19179. When at an #+INCLUDE keyword, visit the included file.
  19180. When at a footnote reference, call `org-edit-footnote-reference'
  19181. On a link, call `ffap' to visit the link at point.
  19182. Otherwise, return a user error."
  19183. (interactive "P")
  19184. (let ((element (org-element-at-point)))
  19185. (barf-if-buffer-read-only)
  19186. (pcase (org-element-type element)
  19187. (`src-block
  19188. (if (not arg) (org-edit-src-code)
  19189. (let* ((info (org-babel-get-src-block-info))
  19190. (lang (nth 0 info))
  19191. (params (nth 2 info))
  19192. (session (cdr (assq :session params))))
  19193. (if (not session) (org-edit-src-code)
  19194. ;; At a src-block with a session and function called with
  19195. ;; an ARG: switch to the buffer related to the inferior
  19196. ;; process.
  19197. (switch-to-buffer
  19198. (funcall (intern (concat "org-babel-prep-session:" lang))
  19199. session params))))))
  19200. (`keyword
  19201. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19202. (org-open-link-from-string
  19203. (format "[[%s]]"
  19204. (expand-file-name
  19205. (let ((value (org-element-property :value element)))
  19206. (cond ((not (org-string-nw-p value))
  19207. (user-error "No file to edit"))
  19208. ((string-match "\\`\"\\(.*?\\)\"" value)
  19209. (match-string 1 value))
  19210. ((string-match "\\`[^ \t\"]\\S-*" value)
  19211. (match-string 0 value))
  19212. (t (user-error "No valid file specified")))))))
  19213. (user-error "No special environment to edit here")))
  19214. (`table
  19215. (if (eq (org-element-property :type element) 'table.el)
  19216. (org-edit-table.el)
  19217. (call-interactively 'org-table-edit-formulas)))
  19218. ;; Only Org tables contain `table-row' type elements.
  19219. (`table-row (call-interactively 'org-table-edit-formulas))
  19220. (`example-block (org-edit-src-code))
  19221. (`export-block (org-edit-export-block))
  19222. (`fixed-width (org-edit-fixed-width-region))
  19223. (_
  19224. ;; No notable element at point. Though, we may be at a link or
  19225. ;; a footnote reference, which are objects. Thus, scan deeper.
  19226. (let ((context (org-element-context element)))
  19227. (pcase (org-element-type context)
  19228. (`footnote-reference (org-edit-footnote-reference))
  19229. (`inline-src-block (org-edit-inline-src-code))
  19230. (`link (call-interactively #'ffap))
  19231. (_ (user-error "No special environment to edit here"))))))))
  19232. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19233. (defun org-ctrl-c-ctrl-c (&optional arg)
  19234. "Set tags in headline, or update according to changed information at point.
  19235. This command does many different things, depending on context:
  19236. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19237. this is what we do.
  19238. - If the cursor is on a statistics cookie, update it.
  19239. - If the cursor is in a headline, prompt for tags and insert them
  19240. into the current line, aligned to `org-tags-column'. When called
  19241. with prefix arg, realign all tags in the current buffer.
  19242. - If the cursor is in one of the special #+KEYWORD lines, this
  19243. triggers scanning the buffer for these lines and updating the
  19244. information.
  19245. - If the cursor is inside a table, realign the table. This command
  19246. works even if the automatic table editor has been turned off.
  19247. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19248. the entire table.
  19249. - If the cursor is at a footnote reference or definition, jump to
  19250. the corresponding definition or references, respectively.
  19251. - If the cursor is a the beginning of a dynamic block, update it.
  19252. - If the current buffer is a capture buffer, close note and file it.
  19253. - If the cursor is on a <<<target>>>, update radio targets and
  19254. corresponding links in this buffer.
  19255. - If the cursor is on a numbered item in a plain list, renumber the
  19256. ordered list.
  19257. - If the cursor is on a checkbox, toggle it.
  19258. - If the cursor is on a code block, evaluate it. The variable
  19259. `org-confirm-babel-evaluate' can be used to control prompting
  19260. before code block evaluation, by default every code block
  19261. evaluation requires confirmation. Code block evaluation can be
  19262. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19263. (interactive "P")
  19264. (cond
  19265. ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
  19266. org-occur-highlights)
  19267. (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19268. (org-remove-occur-highlights)
  19269. (message "Temporary highlights/overlays removed from current buffer"))
  19270. ((and (local-variable-p 'org-finish-function)
  19271. (fboundp org-finish-function))
  19272. (funcall org-finish-function))
  19273. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19274. (t
  19275. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  19276. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19277. (user-error "C-c C-c can do nothing useful at this location"))
  19278. (let* ((context (org-element-context))
  19279. (type (org-element-type context)))
  19280. (cl-case type
  19281. ;; When at a link, act according to the parent instead.
  19282. (link (setq context (org-element-property :parent context))
  19283. (setq type (org-element-type context)))
  19284. ;; Unsupported object types: refer to the first supported
  19285. ;; element or object containing it.
  19286. ((bold code entity export-snippet inline-babel-call inline-src-block
  19287. italic latex-fragment line-break macro strike-through subscript
  19288. superscript underline verbatim)
  19289. (setq context
  19290. (org-element-lineage
  19291. context '(radio-target paragraph verse-block table-cell)))))
  19292. ;; For convenience: at the first line of a paragraph on the
  19293. ;; same line as an item, apply function on that item instead.
  19294. (when (eq type 'paragraph)
  19295. (let ((parent (org-element-property :parent context)))
  19296. (when (and (eq (org-element-type parent) 'item)
  19297. (= (line-beginning-position)
  19298. (org-element-property :begin parent)))
  19299. (setq context parent type 'item))))
  19300. ;; Act according to type of element or object at point.
  19301. (cl-case type
  19302. (clock (org-clock-update-time-maybe))
  19303. (dynamic-block
  19304. (save-excursion
  19305. (goto-char (org-element-property :post-affiliated context))
  19306. (org-update-dblock)))
  19307. (footnote-definition
  19308. (goto-char (org-element-property :post-affiliated context))
  19309. (call-interactively 'org-footnote-action))
  19310. (footnote-reference (call-interactively 'org-footnote-action))
  19311. ((headline inlinetask)
  19312. (save-excursion (goto-char (org-element-property :begin context))
  19313. (call-interactively 'org-set-tags)))
  19314. (item
  19315. ;; At an item: a double C-u set checkbox to "[-]"
  19316. ;; unconditionally, whereas a single one will toggle its
  19317. ;; presence. Without a universal argument, if the item
  19318. ;; has a checkbox, toggle it. Otherwise repair the list.
  19319. (let* ((box (org-element-property :checkbox context))
  19320. (struct (org-element-property :structure context))
  19321. (old-struct (copy-tree struct))
  19322. (parents (org-list-parents-alist struct))
  19323. (prevs (org-list-prevs-alist struct))
  19324. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19325. (org-list-set-checkbox
  19326. (org-element-property :begin context) struct
  19327. (cond ((equal arg '(16)) "[-]")
  19328. ((and (not box) (equal arg '(4))) "[ ]")
  19329. ((or (not box) (equal arg '(4))) nil)
  19330. ((eq box 'on) "[ ]")
  19331. (t "[X]")))
  19332. ;; Mimic `org-list-write-struct' but with grabbing
  19333. ;; a return value from `org-list-struct-fix-box'.
  19334. (org-list-struct-fix-ind struct parents 2)
  19335. (org-list-struct-fix-item-end struct)
  19336. (org-list-struct-fix-bul struct prevs)
  19337. (org-list-struct-fix-ind struct parents)
  19338. (let ((block-item
  19339. (org-list-struct-fix-box struct parents prevs orderedp)))
  19340. (if (and box (equal struct old-struct))
  19341. (if (equal arg '(16))
  19342. (message "Checkboxes already reset")
  19343. (user-error "Cannot toggle this checkbox: %s"
  19344. (if (eq box 'on)
  19345. "all subitems checked"
  19346. "unchecked subitems")))
  19347. (org-list-struct-apply-struct struct old-struct)
  19348. (org-update-checkbox-count-maybe))
  19349. (when block-item
  19350. (message "Checkboxes were removed due to empty box at line %d"
  19351. (org-current-line block-item))))))
  19352. (keyword
  19353. (let ((org-inhibit-startup-visibility-stuff t)
  19354. (org-startup-align-all-tables nil))
  19355. (when (boundp 'org-table-coordinate-overlays)
  19356. (mapc #'delete-overlay org-table-coordinate-overlays)
  19357. (setq org-table-coordinate-overlays nil))
  19358. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19359. (message "Local setup has been refreshed"))
  19360. (plain-list
  19361. ;; At a plain list, with a double C-u argument, set
  19362. ;; checkboxes of each item to "[-]", whereas a single one
  19363. ;; will toggle their presence according to the state of the
  19364. ;; first item in the list. Without an argument, repair the
  19365. ;; list.
  19366. (let* ((begin (org-element-property :contents-begin context))
  19367. (beginm (move-marker (make-marker) begin))
  19368. (struct (org-element-property :structure context))
  19369. (old-struct (copy-tree struct))
  19370. (first-box (save-excursion
  19371. (goto-char begin)
  19372. (looking-at org-list-full-item-re)
  19373. (match-string-no-properties 3)))
  19374. (new-box (cond ((equal arg '(16)) "[-]")
  19375. ((equal arg '(4)) (unless first-box "[ ]"))
  19376. ((equal first-box "[X]") "[ ]")
  19377. (t "[X]"))))
  19378. (cond
  19379. (arg
  19380. (dolist (pos
  19381. (org-list-get-all-items
  19382. begin struct (org-list-prevs-alist struct)))
  19383. (org-list-set-checkbox pos struct new-box)))
  19384. ((and first-box (eq (point) begin))
  19385. ;; For convenience, when point is at bol on the first
  19386. ;; item of the list and no argument is provided, simply
  19387. ;; toggle checkbox of that item, if any.
  19388. (org-list-set-checkbox begin struct new-box)))
  19389. (org-list-write-struct
  19390. struct (org-list-parents-alist struct) old-struct)
  19391. (org-update-checkbox-count-maybe)
  19392. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19393. ((property-drawer node-property)
  19394. (call-interactively 'org-property-action))
  19395. ((radio-target target)
  19396. (call-interactively 'org-update-radio-target-regexp))
  19397. (statistics-cookie
  19398. (call-interactively 'org-update-statistics-cookies))
  19399. ((table table-cell table-row)
  19400. ;; At a table, recalculate every field and align it. Also
  19401. ;; send the table if necessary. If the table has
  19402. ;; a `table.el' type, just give up. At a table row or
  19403. ;; cell, maybe recalculate line but always align table.
  19404. (if (eq (org-element-property :type context) 'table.el)
  19405. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19406. Use \\[org-edit-special] to edit table.el tables"))
  19407. (let ((org-enable-table-editor t))
  19408. (if (or (eq type 'table)
  19409. ;; Check if point is at a TBLFM line.
  19410. (and (eq type 'table-row)
  19411. (= (point) (org-element-property :end context))))
  19412. (save-excursion
  19413. (if (org-at-TBLFM-p)
  19414. (progn (require 'org-table)
  19415. (org-table-calc-current-TBLFM))
  19416. (goto-char (org-element-property :contents-begin context))
  19417. (org-call-with-arg 'org-table-recalculate (or arg t))
  19418. (orgtbl-send-table 'maybe)))
  19419. (org-table-maybe-eval-formula)
  19420. (cond (arg (call-interactively 'org-table-recalculate))
  19421. ((org-table-maybe-recalculate-line))
  19422. (t (org-table-align)))))))
  19423. (timestamp (org-timestamp-change 0 'day))
  19424. (otherwise
  19425. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19426. (user-error
  19427. "C-c C-c can do nothing useful at this location")))))))))
  19428. (defun org-mode-restart ()
  19429. (interactive)
  19430. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19431. (funcall major-mode)
  19432. (hack-local-variables)
  19433. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19434. (org-indent-mode -1)))
  19435. (message "%s restarted" major-mode))
  19436. (defun org-kill-note-or-show-branches ()
  19437. "Abort storing current note, or call `outline-show-branches'."
  19438. (interactive)
  19439. (if (not org-finish-function)
  19440. (progn
  19441. (outline-hide-subtree)
  19442. (call-interactively 'outline-show-branches))
  19443. (let ((org-note-abort t))
  19444. (funcall org-finish-function))))
  19445. (defun org-delete-indentation (&optional ARG)
  19446. "Join current line to previous and fix whitespace at join.
  19447. If previous line is a headline add to headline title. Otherwise
  19448. the function calls `delete-indentation'.
  19449. With argument, join this line to following line."
  19450. (interactive "*P")
  19451. (if (save-excursion
  19452. (if ARG (beginning-of-line)
  19453. (forward-line -1))
  19454. (looking-at org-complex-heading-regexp))
  19455. ;; At headline.
  19456. (let ((tags-column (when (match-beginning 5)
  19457. (save-excursion (goto-char (match-beginning 5))
  19458. (current-column))))
  19459. (string (concat " " (progn (when ARG (forward-line 1))
  19460. (org-trim (delete-and-extract-region
  19461. (line-beginning-position)
  19462. (line-end-position)))))))
  19463. (unless (bobp) (delete-region (point) (1- (point))))
  19464. (goto-char (or (match-end 4)
  19465. (match-beginning 5)
  19466. (match-end 0)))
  19467. (skip-chars-backward " \t")
  19468. (save-excursion (insert string))
  19469. ;; Adjust alignment of tags.
  19470. (when tags-column
  19471. (org-align-tags-here (if org-auto-align-tags
  19472. org-tags-column
  19473. tags-column))))
  19474. (delete-indentation ARG)))
  19475. (defun org-open-line (n)
  19476. "Insert a new row in tables, call `open-line' elsewhere.
  19477. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19478. As a special case, when a document starts with a table, allow to
  19479. call `open-line' on the very first character."
  19480. (interactive "*p")
  19481. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19482. (org-table-insert-row)
  19483. (open-line n)))
  19484. (defun org-return (&optional indent)
  19485. "Goto next table row or insert a newline.
  19486. Calls `org-table-next-row' or `newline', depending on context.
  19487. When optional INDENT argument is non-nil, call
  19488. `newline-and-indent' instead of `newline'.
  19489. When `org-return-follows-link' is non-nil and point is on
  19490. a timestamp or a link, call `org-open-at-point'. However, it
  19491. will not happen if point is in a table or on a \"dead\"
  19492. object (e.g., within a comment). In these case, you need to use
  19493. `org-open-at-point' directly."
  19494. (interactive)
  19495. (let ((context (if org-return-follows-link (org-element-context)
  19496. (org-element-at-point))))
  19497. (cond
  19498. ;; In a table, call `org-table-next-row'.
  19499. ((or (and (eq (org-element-type context) 'table)
  19500. (>= (point) (org-element-property :contents-begin context))
  19501. (< (point) (org-element-property :contents-end context)))
  19502. (org-element-lineage context '(table-row table-cell) t))
  19503. (org-table-justify-field-maybe)
  19504. (call-interactively #'org-table-next-row))
  19505. ;; On a link or a timestamp, call `org-open-at-point' if
  19506. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19507. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19508. ((and org-return-follows-link
  19509. (or (org-in-regexp org-ts-regexp-both nil t)
  19510. (org-in-regexp org-tsr-regexp-both nil t)
  19511. (org-in-regexp org-any-link-re nil t)))
  19512. (call-interactively #'org-open-at-point))
  19513. ;; Insert newline in heading, but preserve tags.
  19514. ((and (not (bolp))
  19515. (save-excursion (beginning-of-line)
  19516. (looking-at org-complex-heading-regexp)))
  19517. ;; At headline. Split line. However, if point is on keyword,
  19518. ;; priority cookie or tags, do not break any of them: add
  19519. ;; a newline after the headline instead.
  19520. (let ((tags-column (and (match-beginning 5)
  19521. (save-excursion (goto-char (match-beginning 5))
  19522. (current-column))))
  19523. (string
  19524. (when (and (match-end 4)
  19525. (>= (point)
  19526. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19527. (<= (point) (match-end 4)))
  19528. (delete-and-extract-region (point) (match-end 4)))))
  19529. (when (and tags-column string) ; Adjust tag alignment.
  19530. (org-align-tags-here
  19531. (if org-auto-align-tags org-tags-column tags-column)))
  19532. (end-of-line)
  19533. (org-show-entry)
  19534. (if indent (newline-and-indent) (newline))
  19535. (when string (save-excursion (insert (org-trim string))))))
  19536. ;; In a list, make sure indenting keeps trailing text within.
  19537. ((and indent
  19538. (not (eolp))
  19539. (org-element-lineage context '(item)))
  19540. (let ((trailing-data
  19541. (delete-and-extract-region (point) (line-end-position))))
  19542. (newline-and-indent)
  19543. (save-excursion (insert trailing-data))))
  19544. (t (if indent (newline-and-indent) (newline))))))
  19545. (defun org-return-indent ()
  19546. "Goto next table row or insert a newline and indent.
  19547. Calls `org-table-next-row' or `newline-and-indent', depending on
  19548. context. See the individual commands for more information."
  19549. (interactive)
  19550. (org-return t))
  19551. (defun org-ctrl-c-star ()
  19552. "Compute table, or change heading status of lines.
  19553. Calls `org-table-recalculate' or `org-toggle-heading',
  19554. depending on context."
  19555. (interactive)
  19556. (cond
  19557. ((org-at-table-p)
  19558. (call-interactively 'org-table-recalculate))
  19559. (t
  19560. ;; Convert all lines in region to list items
  19561. (call-interactively 'org-toggle-heading))))
  19562. (defun org-ctrl-c-minus ()
  19563. "Insert separator line in table or modify bullet status of line.
  19564. Also turns a plain line or a region of lines into list items.
  19565. Calls `org-table-insert-hline', `org-toggle-item', or
  19566. `org-cycle-list-bullet', depending on context."
  19567. (interactive)
  19568. (cond
  19569. ((org-at-table-p)
  19570. (call-interactively 'org-table-insert-hline))
  19571. ((org-region-active-p)
  19572. (call-interactively 'org-toggle-item))
  19573. ((org-in-item-p)
  19574. (call-interactively 'org-cycle-list-bullet))
  19575. (t
  19576. (call-interactively 'org-toggle-item))))
  19577. (defun org-toggle-heading (&optional nstars)
  19578. "Convert headings to normal text, or items or text to headings.
  19579. If there is no active region, only convert the current line.
  19580. With a \\[universal-argument] prefix, convert the whole list at
  19581. point into heading.
  19582. In a region:
  19583. - If the first non blank line is a headline, remove the stars
  19584. from all headlines in the region.
  19585. - If it is a normal line, turn each and every normal line (i.e.,
  19586. not an heading or an item) in the region into headings. If you
  19587. want to convert only the first line of this region, use one
  19588. universal prefix argument.
  19589. - If it is a plain list item, turn all plain list items into headings.
  19590. When converting a line into a heading, the number of stars is chosen
  19591. such that the lines become children of the current entry. However,
  19592. when a numeric prefix argument is given, its value determines the
  19593. number of stars to add."
  19594. (interactive "P")
  19595. (let ((skip-blanks
  19596. (function
  19597. ;; Return beginning of first non-blank line, starting from
  19598. ;; line at POS.
  19599. (lambda (pos)
  19600. (save-excursion
  19601. (goto-char pos)
  19602. (while (org-at-comment-p) (forward-line))
  19603. (skip-chars-forward " \r\t\n")
  19604. (point-at-bol)))))
  19605. beg end toggled)
  19606. ;; Determine boundaries of changes. If a universal prefix has
  19607. ;; been given, put the list in a region. If region ends at a bol,
  19608. ;; do not consider the last line to be in the region.
  19609. (when (and current-prefix-arg (org-at-item-p))
  19610. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19611. (org-mark-element))
  19612. (if (org-region-active-p)
  19613. (setq beg (funcall skip-blanks (region-beginning))
  19614. end (copy-marker (save-excursion
  19615. (goto-char (region-end))
  19616. (if (bolp) (point) (point-at-eol)))))
  19617. (setq beg (funcall skip-blanks (point-at-bol))
  19618. end (copy-marker (point-at-eol))))
  19619. ;; Ensure inline tasks don't count as headings.
  19620. (org-with-limited-levels
  19621. (save-excursion
  19622. (goto-char beg)
  19623. (cond
  19624. ;; Case 1. Started at an heading: de-star headings.
  19625. ((org-at-heading-p)
  19626. (while (< (point) end)
  19627. (when (org-at-heading-p t)
  19628. (looking-at org-outline-regexp) (replace-match "")
  19629. (setq toggled t))
  19630. (forward-line)))
  19631. ;; Case 2. Started at an item: change items into headlines.
  19632. ;; One star will be added by `org-list-to-subtree'.
  19633. ((org-at-item-p)
  19634. (while (< (point) end)
  19635. (when (org-at-item-p)
  19636. ;; Pay attention to cases when region ends before list.
  19637. (let* ((struct (org-list-struct))
  19638. (list-end
  19639. (min (org-list-get-bottom-point struct) (1+ end))))
  19640. (save-restriction
  19641. (narrow-to-region (point) list-end)
  19642. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19643. (setq toggled t))
  19644. (forward-line)))
  19645. ;; Case 3. Started at normal text: make every line an heading,
  19646. ;; skipping headlines and items.
  19647. (t (let* ((stars
  19648. (make-string
  19649. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19650. (add-stars
  19651. (cond (nstars "") ; stars from prefix only
  19652. ((equal stars "") "*") ; before first heading
  19653. (org-odd-levels-only "**") ; inside heading, odd
  19654. (t "*"))) ; inside heading, oddeven
  19655. (rpl (concat stars add-stars " "))
  19656. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19657. (while (< (point) (if (equal nstars '(4)) lend end))
  19658. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19659. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19660. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19661. (forward-line)))))))
  19662. (unless toggled (message "Cannot toggle heading from here"))))
  19663. (defun org-meta-return (&optional _arg)
  19664. "Insert a new heading or wrap a region in a table.
  19665. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19666. on context. See the individual commands for more information."
  19667. (interactive)
  19668. (org-check-before-invisible-edit 'insert)
  19669. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19670. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19671. #'org-insert-heading))))
  19672. ;;; Menu entries
  19673. (defsubst org-in-subtree-not-table-p ()
  19674. "Are we in a subtree and not in a table?"
  19675. (and (not (org-before-first-heading-p))
  19676. (not (org-at-table-p))))
  19677. ;; Define the Org mode menus
  19678. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19679. '("Tbl"
  19680. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19681. ["Next Field" org-cycle (org-at-table-p)]
  19682. ["Previous Field" org-shifttab (org-at-table-p)]
  19683. ["Next Row" org-return (org-at-table-p)]
  19684. "--"
  19685. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19686. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19687. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19688. "--"
  19689. ("Column"
  19690. ["Move Column Left" org-metaleft (org-at-table-p)]
  19691. ["Move Column Right" org-metaright (org-at-table-p)]
  19692. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19693. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19694. ("Row"
  19695. ["Move Row Up" org-metaup (org-at-table-p)]
  19696. ["Move Row Down" org-metadown (org-at-table-p)]
  19697. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19698. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19699. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19700. "--"
  19701. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19702. ("Rectangle"
  19703. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19704. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19705. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19706. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19707. "--"
  19708. ("Calculate"
  19709. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19710. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19711. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19712. "--"
  19713. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19714. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19715. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19716. "--"
  19717. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19718. "--"
  19719. ["Sum Column/Rectangle" org-table-sum
  19720. (or (org-at-table-p) (org-region-active-p))]
  19721. ["Which Column?" org-table-current-column (org-at-table-p)])
  19722. ["Debug Formulas"
  19723. org-table-toggle-formula-debugger
  19724. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19725. ["Show Col/Row Numbers"
  19726. org-table-toggle-coordinate-overlays
  19727. :style toggle
  19728. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19729. "--"
  19730. ["Create" org-table-create (and (not (org-at-table-p))
  19731. org-enable-table-editor)]
  19732. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19733. ["Import from File" org-table-import (not (org-at-table-p))]
  19734. ["Export to File" org-table-export (org-at-table-p)]
  19735. "--"
  19736. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19737. "--"
  19738. ("Plot"
  19739. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19740. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19741. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19742. '("Org"
  19743. ("Show/Hide"
  19744. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19745. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19746. ["Sparse Tree..." org-sparse-tree t]
  19747. ["Reveal Context" org-reveal t]
  19748. ["Show All" outline-show-all t]
  19749. "--"
  19750. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19751. "--"
  19752. ["New Heading" org-insert-heading t]
  19753. ("Navigate Headings"
  19754. ["Up" outline-up-heading t]
  19755. ["Next" outline-next-visible-heading t]
  19756. ["Previous" outline-previous-visible-heading t]
  19757. ["Next Same Level" outline-forward-same-level t]
  19758. ["Previous Same Level" outline-backward-same-level t]
  19759. "--"
  19760. ["Jump" org-goto t])
  19761. ("Edit Structure"
  19762. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19763. "--"
  19764. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19765. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19766. "--"
  19767. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19768. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19769. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19770. "--"
  19771. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19772. "--"
  19773. ["Copy visible text" org-copy-visible t]
  19774. "--"
  19775. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19776. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19777. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19778. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19779. "--"
  19780. ["Sort Region/Children" org-sort t]
  19781. "--"
  19782. ["Convert to odd levels" org-convert-to-odd-levels t]
  19783. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19784. ("Editing"
  19785. ["Emphasis..." org-emphasize t]
  19786. ["Edit Source Example" org-edit-special t]
  19787. "--"
  19788. ["Footnote new/jump" org-footnote-action t]
  19789. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19790. ("Archive"
  19791. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19792. "--"
  19793. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19794. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19795. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19796. )
  19797. "--"
  19798. ("Hyperlinks"
  19799. ["Store Link (Global)" org-store-link t]
  19800. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19801. ["Insert Link" org-insert-link t]
  19802. ["Follow Link" org-open-at-point t]
  19803. "--"
  19804. ["Next link" org-next-link t]
  19805. ["Previous link" org-previous-link t]
  19806. "--"
  19807. ["Descriptive Links"
  19808. org-toggle-link-display
  19809. :style radio
  19810. :selected org-descriptive-links
  19811. ]
  19812. ["Literal Links"
  19813. org-toggle-link-display
  19814. :style radio
  19815. :selected (not org-descriptive-links)])
  19816. "--"
  19817. ("TODO Lists"
  19818. ["TODO/DONE/-" org-todo t]
  19819. ("Select keyword"
  19820. ["Next keyword" org-shiftright (org-at-heading-p)]
  19821. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19822. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19823. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19824. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19825. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19826. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19827. "--"
  19828. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19829. :selected org-enforce-todo-dependencies :style toggle :active t]
  19830. "Settings for tree at point"
  19831. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19832. :selected (org-entry-get nil "ORDERED")
  19833. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19834. ["Do Children parallel" org-toggle-ordered-property :style radio
  19835. :selected (not (org-entry-get nil "ORDERED"))
  19836. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19837. "--"
  19838. ["Set Priority" org-priority t]
  19839. ["Priority Up" org-shiftup t]
  19840. ["Priority Down" org-shiftdown t]
  19841. "--"
  19842. ["Get news from all feeds" org-feed-update-all t]
  19843. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19844. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19845. ("TAGS and Properties"
  19846. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19847. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19848. "--"
  19849. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19850. ["Column view of properties" org-columns t]
  19851. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19852. ("Dates and Scheduling"
  19853. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19854. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19855. ("Change Date"
  19856. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19857. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19858. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19859. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19860. ["Compute Time Range" org-evaluate-time-range t]
  19861. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19862. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19863. "--"
  19864. ["Custom time format" org-toggle-time-stamp-overlays
  19865. :style radio :selected org-display-custom-times]
  19866. "--"
  19867. ["Goto Calendar" org-goto-calendar t]
  19868. ["Date from Calendar" org-date-from-calendar t]
  19869. "--"
  19870. ["Start/Restart Timer" org-timer-start t]
  19871. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19872. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19873. ["Insert Timer String" org-timer t]
  19874. ["Insert Timer Item" org-timer-item t])
  19875. ("Logging work"
  19876. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19877. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19878. ["Clock out" org-clock-out t]
  19879. ["Clock cancel" org-clock-cancel t]
  19880. "--"
  19881. ["Mark as default task" org-clock-mark-default-task t]
  19882. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19883. ["Goto running clock" org-clock-goto t]
  19884. "--"
  19885. ["Display times" org-clock-display t]
  19886. ["Create clock table" org-clock-report t]
  19887. "--"
  19888. ["Record DONE time"
  19889. (progn (setq org-log-done (not org-log-done))
  19890. (message "Switching to %s will %s record a timestamp"
  19891. (car org-done-keywords)
  19892. (if org-log-done "automatically" "not")))
  19893. :style toggle :selected org-log-done])
  19894. "--"
  19895. ["Agenda Command..." org-agenda t]
  19896. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19897. ("File List for Agenda")
  19898. ("Special views current file"
  19899. ["TODO Tree" org-show-todo-tree t]
  19900. ["Check Deadlines" org-check-deadlines t]
  19901. ["Timeline" org-timeline t]
  19902. ["Tags/Property tree" org-match-sparse-tree t])
  19903. "--"
  19904. ["Export/Publish..." org-export-dispatch t]
  19905. ("LaTeX"
  19906. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19907. :selected org-cdlatex-mode]
  19908. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19909. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19910. ["Modify math symbol" org-cdlatex-math-modify
  19911. (org-inside-LaTeX-fragment-p)]
  19912. ["Insert citation" org-reftex-citation t])
  19913. "--"
  19914. ("MobileOrg"
  19915. ["Push Files and Views" org-mobile-push t]
  19916. ["Get Captured and Flagged" org-mobile-pull t]
  19917. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19918. "--"
  19919. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19920. "--"
  19921. ("Documentation"
  19922. ["Show Version" org-version t]
  19923. ["Info Documentation" org-info t])
  19924. ("Customize"
  19925. ["Browse Org Group" org-customize t]
  19926. "--"
  19927. ["Expand This Menu" org-create-customize-menu
  19928. (fboundp 'customize-menu-create)])
  19929. ["Send bug report" org-submit-bug-report t]
  19930. "--"
  19931. ("Refresh/Reload"
  19932. ["Refresh setup current buffer" org-mode-restart t]
  19933. ["Reload Org (after update)" org-reload t]
  19934. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19935. ))
  19936. (defun org-info (&optional node)
  19937. "Read documentation for Org in the info system.
  19938. With optional NODE, go directly to that node."
  19939. (interactive)
  19940. (info (format "(org)%s" (or node ""))))
  19941. ;;;###autoload
  19942. (defun org-submit-bug-report ()
  19943. "Submit a bug report on Org via mail.
  19944. Don't hesitate to report any problems or inaccurate documentation.
  19945. If you don't have setup sending mail from (X)Emacs, please copy the
  19946. output buffer into your mail program, as it gives us important
  19947. information about your Org version and configuration."
  19948. (interactive)
  19949. (require 'reporter)
  19950. (defvar reporter-prompt-for-summary-p)
  19951. (org-load-modules-maybe)
  19952. (org-require-autoloaded-modules)
  19953. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19954. (reporter-submit-bug-report
  19955. "emacs-orgmode@gnu.org"
  19956. (org-version nil 'full)
  19957. (let (list)
  19958. (save-window-excursion
  19959. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19960. (delete-other-windows)
  19961. (erase-buffer)
  19962. (insert "You are about to submit a bug report to the Org mailing list.
  19963. We would like to add your full Org and Outline configuration to the
  19964. bug report. This greatly simplifies the work of the maintainer and
  19965. other experts on the mailing list.
  19966. HOWEVER, some variables you have customized may contain private
  19967. information. The names of customers, colleagues, or friends, might
  19968. appear in the form of file names, tags, todo states, or search strings.
  19969. If you answer yes to the prompt, you might want to check and remove
  19970. such private information before sending the email.")
  19971. (add-text-properties (point-min) (point-max) '(face org-warning))
  19972. (when (yes-or-no-p "Include your Org configuration ")
  19973. (mapatoms
  19974. (lambda (v)
  19975. (and (boundp v)
  19976. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19977. (or (and (symbol-value v)
  19978. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19979. (and
  19980. (get v 'custom-type) (get v 'standard-value)
  19981. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19982. (push v list)))))
  19983. (kill-buffer (get-buffer "*Warn about privacy*"))
  19984. list))
  19985. nil nil
  19986. "Remember to cover the basics, that is, what you expected to happen and
  19987. what in fact did happen. You don't know how to make a good report? See
  19988. http://orgmode.org/manual/Feedback.html#Feedback
  19989. Your bug report will be posted to the Org mailing list.
  19990. ------------------------------------------------------------------------")
  19991. (save-excursion
  19992. (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19993. (replace-match "\\1Bug: \\3 [\\2]")))))
  19994. (defun org-install-agenda-files-menu ()
  19995. (let ((bl (buffer-list)))
  19996. (save-excursion
  19997. (while bl
  19998. (set-buffer (pop bl))
  19999. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20000. (when (derived-mode-p 'org-mode)
  20001. (easy-menu-change
  20002. '("Org") "File List for Agenda"
  20003. (append
  20004. (list
  20005. ["Edit File List" (org-edit-agenda-file-list) t]
  20006. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20007. ["Remove Current File from List" org-remove-file t]
  20008. ["Cycle through agenda files" org-cycle-agenda-files t]
  20009. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20010. "--")
  20011. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20012. ;;;; Documentation
  20013. (defun org-require-autoloaded-modules ()
  20014. (interactive)
  20015. (mapc #'require
  20016. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20017. org-table org-timer)))
  20018. ;;;###autoload
  20019. (defun org-reload (&optional uncompiled)
  20020. "Reload all org lisp files.
  20021. With prefix arg UNCOMPILED, load the uncompiled versions."
  20022. (interactive "P")
  20023. (require 'loadhist)
  20024. (let* ((org-dir (org-find-library-dir "org"))
  20025. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20026. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20027. (remove-re (format "\\`%s\\'"
  20028. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20029. (feats (delete-dups
  20030. (mapcar 'file-name-sans-extension
  20031. (mapcar 'file-name-nondirectory
  20032. (delq nil
  20033. (mapcar 'feature-file
  20034. features))))))
  20035. (lfeat (append
  20036. (sort
  20037. (setq feats
  20038. (delq nil (mapcar
  20039. (lambda (f)
  20040. (if (and (string-match feature-re f)
  20041. (not (string-match remove-re f)))
  20042. f nil))
  20043. feats)))
  20044. 'string-lessp)
  20045. (list "org-version" "org")))
  20046. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20047. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20048. load-uncore load-misses)
  20049. (setq load-misses
  20050. (delq 't
  20051. (mapcar (lambda (f)
  20052. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20053. (and (string= org-dir contrib-dir)
  20054. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20055. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20056. (add-to-list 'load-uncore f 'append)
  20057. 't)
  20058. f))
  20059. lfeat)))
  20060. (when load-uncore
  20061. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20062. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20063. (if load-misses
  20064. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20065. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20066. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20067. ;;;###autoload
  20068. (defun org-customize ()
  20069. "Call the customize function with org as argument."
  20070. (interactive)
  20071. (org-load-modules-maybe)
  20072. (org-require-autoloaded-modules)
  20073. (customize-browse 'org))
  20074. (defun org-create-customize-menu ()
  20075. "Create a full customization menu for Org-mode, insert it into the menu."
  20076. (interactive)
  20077. (org-load-modules-maybe)
  20078. (org-require-autoloaded-modules)
  20079. (if (fboundp 'customize-menu-create)
  20080. (progn
  20081. (easy-menu-change
  20082. '("Org") "Customize"
  20083. `(["Browse Org group" org-customize t]
  20084. "--"
  20085. ,(customize-menu-create 'org)
  20086. ["Set" Custom-set t]
  20087. ["Save" Custom-save t]
  20088. ["Reset to Current" Custom-reset-current t]
  20089. ["Reset to Saved" Custom-reset-saved t]
  20090. ["Reset to Standard Settings" Custom-reset-standard t]))
  20091. (message "\"Org\"-menu now contains full customization menu"))
  20092. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20093. ;;;; Miscellaneous stuff
  20094. ;;; Generally useful functions
  20095. (defun org-get-at-eol (property n)
  20096. "Get text property PROPERTY at the end of line less N characters."
  20097. (get-text-property (- (point-at-eol) n) property))
  20098. (defun org-find-text-property-in-string (prop s)
  20099. "Return the first non-nil value of property PROP in string S."
  20100. (or (get-text-property 0 prop s)
  20101. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20102. prop s)))
  20103. (defun org-display-warning (message)
  20104. "Display the given MESSAGE as a warning."
  20105. (display-warning 'org message :warning))
  20106. (defun org-eval (form)
  20107. "Eval FORM and return result."
  20108. (condition-case error
  20109. (eval form)
  20110. (error (format "%%![Error: %s]" error))))
  20111. (defun org-in-clocktable-p ()
  20112. "Check if the cursor is in a clocktable."
  20113. (let ((pos (point)) start)
  20114. (save-excursion
  20115. (end-of-line 1)
  20116. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20117. (setq start (match-beginning 0))
  20118. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20119. (>= (match-end 0) pos)
  20120. start))))
  20121. (defun org-in-verbatim-emphasis ()
  20122. (save-match-data
  20123. (and (org-in-regexp org-emph-re 2)
  20124. (>= (point) (match-beginning 3))
  20125. (<= (point) (match-end 4))
  20126. (member (match-string 3) '("=" "~")))))
  20127. (defun org-overlay-display (ovl text &optional face evap)
  20128. "Make overlay OVL display TEXT with face FACE."
  20129. (overlay-put ovl 'display text)
  20130. (if face (overlay-put ovl 'face face))
  20131. (if evap (overlay-put ovl 'evaporate t)))
  20132. (defun org-overlay-before-string (ovl text &optional face evap)
  20133. "Make overlay OVL display TEXT with face FACE."
  20134. (if face (org-add-props text nil 'face face))
  20135. (overlay-put ovl 'before-string text)
  20136. (if evap (overlay-put ovl 'evaporate t)))
  20137. (defun org-find-overlays (prop &optional pos delete)
  20138. "Find all overlays specifying PROP at POS or point.
  20139. If DELETE is non-nil, delete all those overlays."
  20140. (let (found)
  20141. (dolist (ov (overlays-at (or pos (point))) found)
  20142. (cond ((not (overlay-get ov prop)))
  20143. (delete (delete-overlay ov))
  20144. (t (push ov found))))))
  20145. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20146. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20147. (if (and marker (marker-buffer marker)
  20148. (buffer-live-p (marker-buffer marker)))
  20149. (progn
  20150. (pop-to-buffer-same-window (marker-buffer marker))
  20151. (when (or (> marker (point-max)) (< marker (point-min)))
  20152. (widen))
  20153. (goto-char marker)
  20154. (org-show-context 'org-goto))
  20155. (if bookmark
  20156. (bookmark-jump bookmark)
  20157. (error "Cannot find location"))))
  20158. (defun org-quote-csv-field (s)
  20159. "Quote field for inclusion in CSV material."
  20160. (if (string-match "[\",]" s)
  20161. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20162. s))
  20163. (defun org-force-self-insert (N)
  20164. "Needed to enforce self-insert under remapping."
  20165. (interactive "p")
  20166. (self-insert-command N))
  20167. (defun org-string-width (s)
  20168. "Compute width of string, ignoring invisible characters.
  20169. This ignores character with invisibility property `org-link', and also
  20170. characters with property `org-cwidth', because these will become invisible
  20171. upon the next fontification round."
  20172. (let (b l)
  20173. (when (or (eq t buffer-invisibility-spec)
  20174. (assq 'org-link buffer-invisibility-spec))
  20175. (while (setq b (text-property-any 0 (length s)
  20176. 'invisible 'org-link s))
  20177. (setq s (concat (substring s 0 b)
  20178. (substring s (or (next-single-property-change
  20179. b 'invisible s)
  20180. (length s)))))))
  20181. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20182. (setq s (concat (substring s 0 b)
  20183. (substring s (or (next-single-property-change
  20184. b 'org-cwidth s)
  20185. (length s))))))
  20186. (setq l (string-width s) b -1)
  20187. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20188. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20189. l))
  20190. (defun org-shorten-string (s maxlength)
  20191. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20192. If the string is shorter or has length MAXLENGTH, just return the
  20193. original string. If it is longer, the functions finds a space in the
  20194. string, breaks this string off at that locations and adds three dots
  20195. as ellipsis. Including the ellipsis, the string will not be longer
  20196. than MAXLENGTH. If finding a good breaking point in the string does
  20197. not work, the string is just chopped off in the middle of a word
  20198. if necessary."
  20199. (if (<= (length s) maxlength)
  20200. s
  20201. (let* ((n (max (- maxlength 4) 1))
  20202. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20203. (if (string-match re s)
  20204. (concat (match-string 1 s) "...")
  20205. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20206. (defun org-get-indentation (&optional line)
  20207. "Get the indentation of the current line, interpreting tabs.
  20208. When LINE is given, assume it represents a line and compute its indentation."
  20209. (if line
  20210. (when (string-match "^ *" (org-remove-tabs line))
  20211. (match-end 0))
  20212. (save-excursion
  20213. (beginning-of-line 1)
  20214. (skip-chars-forward " \t")
  20215. (current-column))))
  20216. (defun org-get-string-indentation (s)
  20217. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20218. (let ((n -1) (i 0) (w tab-width) c)
  20219. (catch 'exit
  20220. (while (< (setq n (1+ n)) (length s))
  20221. (setq c (aref s n))
  20222. (cond ((= c ?\ ) (setq i (1+ i)))
  20223. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20224. (t (throw 'exit t)))))
  20225. i))
  20226. (defun org-remove-tabs (s &optional width)
  20227. "Replace tabulators in S with spaces.
  20228. Assumes that s is a single line, starting in column 0."
  20229. (setq width (or width tab-width))
  20230. (while (string-match "\t" s)
  20231. (setq s (replace-match
  20232. (make-string
  20233. (- (* width (/ (+ (match-beginning 0) width) width))
  20234. (match-beginning 0)) ?\ )
  20235. t t s)))
  20236. s)
  20237. (defun org-fix-indentation (line ind)
  20238. "Fix indentation in LINE.
  20239. IND is a cons cell with target and minimum indentation.
  20240. If the current indentation in LINE is smaller than the minimum,
  20241. leave it alone. If it is larger than ind, set it to the target."
  20242. (let* ((l (org-remove-tabs line))
  20243. (i (org-get-indentation l))
  20244. (i1 (car ind)) (i2 (cdr ind)))
  20245. (when (>= i i2) (setq l (substring line i2)))
  20246. (if (> i1 0)
  20247. (concat (make-string i1 ?\ ) l)
  20248. l)))
  20249. (defun org-remove-indentation (code &optional n)
  20250. "Remove maximum common indentation in string CODE and return it.
  20251. N may optionally be the number of columns to remove. Return CODE
  20252. as-is if removal failed."
  20253. (with-temp-buffer
  20254. (insert code)
  20255. (if (org-do-remove-indentation n) (buffer-string) code)))
  20256. (defun org-do-remove-indentation (&optional n)
  20257. "Remove the maximum common indentation from the buffer.
  20258. When optional argument N is a positive integer, remove exactly
  20259. that much characters from indentation, if possible. Return nil
  20260. if it fails."
  20261. (catch :exit
  20262. (goto-char (point-min))
  20263. ;; Find maximum common indentation, if not specified.
  20264. (let ((n (or n
  20265. (let ((min-ind (point-max)))
  20266. (save-excursion
  20267. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20268. (let ((ind (1- (current-column))))
  20269. (if (zerop ind) (throw :exit nil)
  20270. (setq min-ind (min min-ind ind))))))
  20271. min-ind))))
  20272. (if (zerop n) (throw :exit nil)
  20273. ;; Remove exactly N indentation, but give up if not possible.
  20274. (while (not (eobp))
  20275. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20276. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20277. ((< ind n) (throw :exit nil))
  20278. (t (indent-line-to (- ind n))))
  20279. (forward-line)))
  20280. ;; Signal success.
  20281. t))))
  20282. (defun org-fill-template (template alist)
  20283. "Find each %key of ALIST in TEMPLATE and replace it."
  20284. (let ((case-fold-search nil))
  20285. (dolist (entry (sort (copy-sequence alist)
  20286. (lambda (a b) (< (length (car a)) (length (car b))))))
  20287. (setq template
  20288. (replace-regexp-in-string
  20289. (concat "%" (regexp-quote (car entry)))
  20290. (or (cdr entry) "") template t t)))
  20291. template))
  20292. (defun org-base-buffer (buffer)
  20293. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20294. (if (not buffer)
  20295. buffer
  20296. (or (buffer-base-buffer buffer)
  20297. buffer)))
  20298. (defun org-wrap (string &optional width lines)
  20299. "Wrap string to either a number of lines, or a width in characters.
  20300. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20301. that costs. If there is a word longer than WIDTH, the text is actually
  20302. wrapped to the length of that word.
  20303. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20304. many lines, whatever width that takes.
  20305. The return value is a list of lines, without newlines at the end."
  20306. (let* ((words (org-split-string string "[ \t\n]+"))
  20307. (maxword (apply 'max (mapcar 'org-string-width words)))
  20308. w ll)
  20309. (cond (width
  20310. (org-do-wrap words (max maxword width)))
  20311. (lines
  20312. (setq w maxword)
  20313. (setq ll (org-do-wrap words maxword))
  20314. (if (<= (length ll) lines)
  20315. ll
  20316. (setq ll words)
  20317. (while (> (length ll) lines)
  20318. (setq w (1+ w))
  20319. (setq ll (org-do-wrap words w)))
  20320. ll))
  20321. (t (error "Cannot wrap this")))))
  20322. (defun org-do-wrap (words width)
  20323. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20324. (let (lines line)
  20325. (while words
  20326. (setq line (pop words))
  20327. (while (and words (< (+ (length line) (length (car words))) width))
  20328. (setq line (concat line " " (pop words))))
  20329. (setq lines (push line lines)))
  20330. (nreverse lines)))
  20331. (defun org-split-string (string &optional separators)
  20332. "Splits STRING into substrings at SEPARATORS.
  20333. SEPARATORS is a regular expression.
  20334. No empty strings are returned if there are matches at the beginning
  20335. and end of string."
  20336. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20337. (let ((start 0) notfirst list)
  20338. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20339. (if (and notfirst
  20340. (= start (match-beginning 0))
  20341. (< start (length string)))
  20342. (1+ start) start))
  20343. (< (match-beginning 0) (length string)))
  20344. (setq notfirst t)
  20345. (or (eq (match-beginning 0) 0)
  20346. (and (eq (match-beginning 0) (match-end 0))
  20347. (eq (match-beginning 0) start))
  20348. (push (substring string start (match-beginning 0)) list))
  20349. (setq start (match-end 0)))
  20350. (or (eq start (length string))
  20351. (push (substring string start) list))
  20352. (nreverse list)))
  20353. (defun org-quote-vert (s)
  20354. "Replace \"|\" with \"\\vert\"."
  20355. (while (string-match "|" s)
  20356. (setq s (replace-match "\\vert" t t s)))
  20357. s)
  20358. (defun org-uuidgen-p (s)
  20359. "Is S an ID created by UUIDGEN?"
  20360. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20361. (defun org-in-src-block-p (&optional inside)
  20362. "Whether point is in a code source block.
  20363. When INSIDE is non-nil, don't consider we are within a src block
  20364. when point is at #+BEGIN_SRC or #+END_SRC."
  20365. (let ((case-fold-search t))
  20366. (or (and (eq (get-char-property (point) 'src-block) t))
  20367. (and (not inside)
  20368. (save-match-data
  20369. (save-excursion
  20370. (beginning-of-line)
  20371. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20372. (defun org-context ()
  20373. "Return a list of contexts of the current cursor position.
  20374. If several contexts apply, all are returned.
  20375. Each context entry is a list with a symbol naming the context, and
  20376. two positions indicating start and end of the context. Possible
  20377. contexts are:
  20378. :headline anywhere in a headline
  20379. :headline-stars on the leading stars in a headline
  20380. :todo-keyword on a TODO keyword (including DONE) in a headline
  20381. :tags on the TAGS in a headline
  20382. :priority on the priority cookie in a headline
  20383. :item on the first line of a plain list item
  20384. :item-bullet on the bullet/number of a plain list item
  20385. :checkbox on the checkbox in a plain list item
  20386. :table in an Org table
  20387. :table-special on a special filed in a table
  20388. :table-table in a table.el table
  20389. :clocktable in a clocktable
  20390. :src-block in a source block
  20391. :link on a hyperlink
  20392. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20393. :target on a <<target>>
  20394. :radio-target on a <<<radio-target>>>
  20395. :latex-fragment on a LaTeX fragment
  20396. :latex-preview on a LaTeX fragment with overlaid preview image
  20397. This function expects the position to be visible because it uses font-lock
  20398. faces as a help to recognize the following contexts: :table-special, :link,
  20399. and :keyword."
  20400. (let* ((f (get-text-property (point) 'face))
  20401. (faces (if (listp f) f (list f)))
  20402. (case-fold-search t)
  20403. (p (point)) clist o)
  20404. ;; First the large context
  20405. (cond
  20406. ((org-at-heading-p t)
  20407. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20408. (when (progn
  20409. (beginning-of-line 1)
  20410. (looking-at org-todo-line-tags-regexp))
  20411. (push (org-point-in-group p 1 :headline-stars) clist)
  20412. (push (org-point-in-group p 2 :todo-keyword) clist)
  20413. (push (org-point-in-group p 4 :tags) clist))
  20414. (goto-char p)
  20415. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20416. (when (looking-at "\\[#[A-Z0-9]\\]")
  20417. (push (org-point-in-group p 0 :priority) clist)))
  20418. ((org-at-item-p)
  20419. (push (org-point-in-group p 2 :item-bullet) clist)
  20420. (push (list :item (point-at-bol)
  20421. (save-excursion (org-end-of-item) (point)))
  20422. clist)
  20423. (and (org-at-item-checkbox-p)
  20424. (push (org-point-in-group p 0 :checkbox) clist)))
  20425. ((org-at-table-p)
  20426. (push (list :table (org-table-begin) (org-table-end)) clist)
  20427. (when (memq 'org-formula faces)
  20428. (push (list :table-special
  20429. (previous-single-property-change p 'face)
  20430. (next-single-property-change p 'face)) clist)))
  20431. ((org-at-table-p 'any)
  20432. (push (list :table-table) clist)))
  20433. (goto-char p)
  20434. (let ((case-fold-search t))
  20435. ;; New the "medium" contexts: clocktables, source blocks
  20436. (cond ((org-in-clocktable-p)
  20437. (push (list :clocktable
  20438. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20439. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20440. (match-beginning 1))
  20441. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20442. (match-end 0))) clist))
  20443. ((org-in-src-block-p)
  20444. (push (list :src-block
  20445. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20446. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20447. (match-beginning 1))
  20448. (and (search-forward "#+END_SRC" nil t)
  20449. (match-beginning 0))) clist))))
  20450. (goto-char p)
  20451. ;; Now the small context
  20452. (cond
  20453. ((org-at-timestamp-p)
  20454. (push (org-point-in-group p 0 :timestamp) clist))
  20455. ((memq 'org-link faces)
  20456. (push (list :link
  20457. (previous-single-property-change p 'face)
  20458. (next-single-property-change p 'face)) clist))
  20459. ((memq 'org-special-keyword faces)
  20460. (push (list :keyword
  20461. (previous-single-property-change p 'face)
  20462. (next-single-property-change p 'face)) clist))
  20463. ((org-at-target-p)
  20464. (push (org-point-in-group p 0 :target) clist)
  20465. (goto-char (1- (match-beginning 0)))
  20466. (when (looking-at org-radio-target-regexp)
  20467. (push (org-point-in-group p 0 :radio-target) clist))
  20468. (goto-char p))
  20469. ((setq o (cl-some
  20470. (lambda (o)
  20471. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20472. o))
  20473. (overlays-at (point))))
  20474. (push (list :latex-fragment
  20475. (overlay-start o) (overlay-end o)) clist)
  20476. (push (list :latex-preview
  20477. (overlay-start o) (overlay-end o)) clist))
  20478. ((org-inside-LaTeX-fragment-p)
  20479. ;; FIXME: positions wrong.
  20480. (push (list :latex-fragment (point) (point)) clist)))
  20481. (setq clist (nreverse (delq nil clist)))
  20482. clist))
  20483. (defun org-in-regexp (regexp &optional nlines visually)
  20484. "Check if point is inside a match of REGEXP.
  20485. Normally only the current line is checked, but you can include
  20486. NLINES extra lines around point into the search. If VISUALLY is
  20487. set, require that the cursor is not after the match but really
  20488. on, so that the block visually is on the match.
  20489. Return nil or a cons cell (BEG . END) where BEG and END are,
  20490. respectively, the positions at the beginning and the end of the
  20491. match."
  20492. (catch :exit
  20493. (let ((pos (point))
  20494. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20495. (save-excursion
  20496. (beginning-of-line (- 1 (or nlines 0)))
  20497. (while (and (re-search-forward regexp eol t)
  20498. (<= (match-beginning 0) pos))
  20499. (let ((end (match-end 0)))
  20500. (when (or (> end pos) (and (= end pos) (not visually)))
  20501. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20502. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20503. "Non-nil when point is between matches of START-RE and END-RE.
  20504. Also return a non-nil value when point is on one of the matches.
  20505. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20506. buffer positions. Default values are the positions of headlines
  20507. surrounding the point.
  20508. The functions returns a cons cell whose car (resp. cdr) is the
  20509. position before START-RE (resp. after END-RE)."
  20510. (save-match-data
  20511. (let ((pos (point))
  20512. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20513. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20514. beg end)
  20515. (save-excursion
  20516. ;; Point is on a block when on START-RE or if START-RE can be
  20517. ;; found before it...
  20518. (and (or (org-in-regexp start-re)
  20519. (re-search-backward start-re limit-up t))
  20520. (setq beg (match-beginning 0))
  20521. ;; ... and END-RE after it...
  20522. (goto-char (match-end 0))
  20523. (re-search-forward end-re limit-down t)
  20524. (> (setq end (match-end 0)) pos)
  20525. ;; ... without another START-RE in-between.
  20526. (goto-char (match-beginning 0))
  20527. (not (re-search-backward start-re (1+ beg) t))
  20528. ;; Return value.
  20529. (cons beg end))))))
  20530. (defun org-in-block-p (names)
  20531. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20532. NAMES is a list of strings containing names of blocks.
  20533. Return first block name matched, or nil. Beware that in case of
  20534. nested blocks, the returned name may not belong to the closest
  20535. block from point."
  20536. (save-match-data
  20537. (catch 'exit
  20538. (let ((case-fold-search t)
  20539. (lim-up (save-excursion (outline-previous-heading)))
  20540. (lim-down (save-excursion (outline-next-heading))))
  20541. (dolist (name names)
  20542. (let ((n (regexp-quote name)))
  20543. (when (org-between-regexps-p
  20544. (concat "^[ \t]*#\\+begin_" n)
  20545. (concat "^[ \t]*#\\+end_" n)
  20546. lim-up lim-down)
  20547. (throw 'exit n)))))
  20548. nil)))
  20549. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20550. "Call `multi-occur' with buffers for all agenda files."
  20551. (interactive "sOrg-files matching: ")
  20552. (let* ((files (org-agenda-files))
  20553. (tnames (mapcar #'file-truename files))
  20554. (extra org-agenda-text-search-extra-files))
  20555. (when (eq (car extra) 'agenda-archives)
  20556. (setq extra (cdr extra))
  20557. (setq files (org-add-archive-files files)))
  20558. (dolist (f extra)
  20559. (unless (member (file-truename f) tnames)
  20560. (unless (member f files) (setq files (append files (list f))))
  20561. (setq tnames (append tnames (list (file-truename f))))))
  20562. (multi-occur
  20563. (mapcar (lambda (x)
  20564. (with-current-buffer
  20565. ;; FIXME: Why not just (find-file-noselect x)?
  20566. ;; Is it to avoid the "revert buffer" prompt?
  20567. (or (get-file-buffer x) (find-file-noselect x))
  20568. (widen)
  20569. (current-buffer)))
  20570. files)
  20571. regexp)))
  20572. (add-hook 'occur-mode-find-occurrence-hook
  20573. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20574. (defun org-occur-link-in-agenda-files ()
  20575. "Create a link and search for it in the agendas.
  20576. The link is not stored in `org-stored-links', it is just created
  20577. for the search purpose."
  20578. (interactive)
  20579. (let ((link (condition-case nil
  20580. (org-store-link nil)
  20581. (error "Unable to create a link to here"))))
  20582. (org-occur-in-agenda-files (regexp-quote link))))
  20583. (defun org-reverse-string (string)
  20584. "Return the reverse of STRING."
  20585. (apply 'string (reverse (string-to-list string))))
  20586. ;; defsubst org-uniquify must be defined before first use
  20587. (defun org-uniquify-alist (alist)
  20588. "Merge elements of ALIST with the same key.
  20589. For example, in this alist:
  20590. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20591. => \\='((a 1 3) (b 2))
  20592. merge (a 1) and (a 3) into (a 1 3).
  20593. The function returns the new ALIST."
  20594. (let (rtn)
  20595. (dolist (e alist rtn)
  20596. (let (n)
  20597. (if (not (assoc (car e) rtn))
  20598. (push e rtn)
  20599. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20600. (setq rtn (assq-delete-all (car e) rtn))
  20601. (push n rtn))))))
  20602. (defun org-delete-all (elts list)
  20603. "Remove all elements in ELTS from LIST.
  20604. Comparison is done with `equal'. It is a destructive operation
  20605. that may remove elements by altering the list structure."
  20606. (while elts
  20607. (setq list (delete (pop elts) list)))
  20608. list)
  20609. (defun org-back-over-empty-lines ()
  20610. "Move backwards over whitespace, to the beginning of the first empty line.
  20611. Returns the number of empty lines passed."
  20612. (let ((pos (point)))
  20613. (if (cdr (assq 'heading org-blank-before-new-entry))
  20614. (skip-chars-backward " \t\n\r")
  20615. (unless (eobp)
  20616. (forward-line -1)))
  20617. (beginning-of-line 2)
  20618. (goto-char (min (point) pos))
  20619. (count-lines (point) pos)))
  20620. (defun org-skip-whitespace ()
  20621. (skip-chars-forward " \t\n\r"))
  20622. (defun org-point-in-group (point group &optional context)
  20623. "Check if POINT is in match-group GROUP.
  20624. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20625. match. If the match group does not exist or point is not inside it,
  20626. return nil."
  20627. (and (match-beginning group)
  20628. (>= point (match-beginning group))
  20629. (<= point (match-end group))
  20630. (if context
  20631. (list context (match-beginning group) (match-end group))
  20632. t)))
  20633. (defun org-switch-to-buffer-other-window (&rest args)
  20634. "Switch to buffer in a second window on the current frame.
  20635. In particular, do not allow pop-up frames.
  20636. Returns the newly created buffer."
  20637. (org-no-popups
  20638. (apply 'switch-to-buffer-other-window args)))
  20639. (defun org-combine-plists (&rest plists)
  20640. "Create a single property list from all plists in PLISTS.
  20641. The process starts by copying the first list, and then setting properties
  20642. from the other lists. Settings in the last list are the most significant
  20643. ones and overrule settings in the other lists."
  20644. (let ((rtn (copy-sequence (pop plists)))
  20645. p v ls)
  20646. (while plists
  20647. (setq ls (pop plists))
  20648. (while ls
  20649. (setq p (pop ls) v (pop ls))
  20650. (setq rtn (plist-put rtn p v))))
  20651. rtn))
  20652. (defun org-replace-escapes (string table)
  20653. "Replace %-escapes in STRING with values in TABLE.
  20654. TABLE is an association list with keys like \"%a\" and string values.
  20655. The sequences in STRING may contain normal field width and padding information,
  20656. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20657. so values can contain further %-escapes if they are define later in TABLE."
  20658. (let ((tbl (copy-alist table))
  20659. (case-fold-search nil)
  20660. (pchg 0)
  20661. re rpl)
  20662. (dolist (e tbl)
  20663. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20664. (when (and (cdr e) (string-match re (cdr e)))
  20665. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20666. (safe "SREF"))
  20667. (add-text-properties 0 3 (list 'sref sref) safe)
  20668. (setcdr e (replace-match safe t t (cdr e)))))
  20669. (while (string-match re string)
  20670. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20671. (cdr e)))
  20672. (setq string (replace-match rpl t t string))))
  20673. (while (setq pchg (next-property-change pchg string))
  20674. (let ((sref (get-text-property pchg 'sref string)))
  20675. (when (and sref (string-match "SREF" string pchg))
  20676. (setq string (replace-match sref t t string)))))
  20677. string))
  20678. (defun org-find-base-buffer-visiting (file)
  20679. "Like `find-buffer-visiting' but always return the base buffer and
  20680. not an indirect buffer."
  20681. (let ((buf (or (get-file-buffer file)
  20682. (find-buffer-visiting file))))
  20683. (if buf
  20684. (or (buffer-base-buffer buf) buf)
  20685. nil)))
  20686. ;;; TODO: Only called once, from ox-odt which should probably use
  20687. ;;; org-export-inline-image-p or something.
  20688. (defun org-file-image-p (file)
  20689. "Return non-nil if FILE is an image."
  20690. (save-match-data
  20691. (string-match (image-file-name-regexp) file)))
  20692. (defun org-get-cursor-date (&optional with-time)
  20693. "Return the date at cursor in as a time.
  20694. This works in the calendar and in the agenda, anywhere else it just
  20695. returns the current time.
  20696. If WITH-TIME is non-nil, returns the time of the event at point (in
  20697. the agenda) or the current time of the day."
  20698. (let (date day defd tp hod mod)
  20699. (when with-time
  20700. (setq tp (get-text-property (point) 'time))
  20701. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20702. (setq hod (string-to-number (match-string 1 tp))
  20703. mod (string-to-number (match-string 2 tp))))
  20704. (or tp (let ((now (decode-time)))
  20705. (setq hod (nth 2 now)
  20706. mod (nth 1 now)))))
  20707. (cond
  20708. ((eq major-mode 'calendar-mode)
  20709. (setq date (calendar-cursor-to-date)
  20710. defd (encode-time 0 (or mod 0) (or hod 0)
  20711. (nth 1 date) (nth 0 date) (nth 2 date))))
  20712. ((eq major-mode 'org-agenda-mode)
  20713. (setq day (get-text-property (point) 'day))
  20714. (when day
  20715. (setq date (calendar-gregorian-from-absolute day)
  20716. defd (encode-time 0 (or mod 0) (or hod 0)
  20717. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20718. (or defd (current-time))))
  20719. (defun org-mark-subtree (&optional up)
  20720. "Mark the current subtree.
  20721. This puts point at the start of the current subtree, and mark at
  20722. the end. If a numeric prefix UP is given, move up into the
  20723. hierarchy of headlines by UP levels before marking the subtree."
  20724. (interactive "P")
  20725. (org-with-limited-levels
  20726. (cond ((org-at-heading-p) (beginning-of-line))
  20727. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20728. (t (outline-previous-visible-heading 1))))
  20729. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20730. (if (called-interactively-p 'any)
  20731. (call-interactively 'org-mark-element)
  20732. (org-mark-element)))
  20733. (defun org-file-newer-than-p (file time)
  20734. "Non-nil if FILE is newer than TIME.
  20735. FILE is a filename, as a string, TIME is a list of integers, as
  20736. returned by, e.g., `current-time'."
  20737. (and (file-exists-p file)
  20738. ;; Only compare times up to whole seconds as some file-systems
  20739. ;; (e.g. HFS+) do not retain any finer granularity. As
  20740. ;; a consequence, make sure we return non-nil when the two
  20741. ;; times are equal.
  20742. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20743. (cl-subseq time 0 2)))))
  20744. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20745. "Compile a SOURCE file using PROCESS.
  20746. PROCESS is either a function or a list of shell commands, as
  20747. strings. EXT is a file extension, without the leading dot, as
  20748. a string. It is used to check if the process actually succeeded.
  20749. PROCESS must create a file with the same base name and directory
  20750. as SOURCE, but ending with EXT. The function then returns its
  20751. filename. Otherwise, it raises an error. The error message can
  20752. then be refined by providing string ERR-MSG, which is appended to
  20753. the standard message.
  20754. If PROCESS is a function, it is called with a single argument:
  20755. the SOURCE file.
  20756. If it is a list of commands, each of them is called using
  20757. `shell-command'. By default, in each command, %b, %f, %F and %o
  20758. are replaced with, respectively, SOURCE base name, name, full
  20759. name and directory. It is possible, however, to use more
  20760. place-holders by specifying them in optional argument SPEC, as an
  20761. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20762. When PROCESS is a list of commands, optional argument LOG-BUF can
  20763. be set to a buffer or a buffer name. `shell-command' then uses
  20764. it for output.
  20765. `default-directory' is set to SOURCE directory during the whole
  20766. process."
  20767. (let* ((source-name (file-name-nondirectory source))
  20768. (base-name (file-name-sans-extension source-name))
  20769. (full-name (file-truename source))
  20770. (out-dir (file-name-directory source))
  20771. (time (current-time))
  20772. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20773. (save-window-excursion
  20774. (let ((default-directory (file-name-directory full-name)))
  20775. (pcase process
  20776. ((pred functionp) (funcall process (shell-quote-argument source)))
  20777. ((pred consp)
  20778. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20779. (spec (append spec
  20780. `((?b . ,(shell-quote-argument base-name))
  20781. (?f . ,(shell-quote-argument source-name))
  20782. (?F . ,(shell-quote-argument full-name))
  20783. (?o . ,(shell-quote-argument out-dir))))))
  20784. (dolist (command process)
  20785. (shell-command (format-spec command spec) log-buf))))
  20786. (_ (error "No valid command to process %S%s" source err-msg)))))
  20787. ;; Check for process failure.
  20788. (let ((output (concat out-dir base-name "." ext)))
  20789. (unless (org-file-newer-than-p output time)
  20790. (error (format "File %S wasn't produced%s" output err-msg)))
  20791. output)))
  20792. ;;; Indentation
  20793. (defun org--get-expected-indentation (element contentsp)
  20794. "Expected indentation column for current line, according to ELEMENT.
  20795. ELEMENT is an element containing point. CONTENTSP is non-nil
  20796. when indentation is to be computed according to contents of
  20797. ELEMENT."
  20798. (let ((type (org-element-type element))
  20799. (start (org-element-property :begin element))
  20800. (post-affiliated (org-element-property :post-affiliated element)))
  20801. (org-with-wide-buffer
  20802. (cond
  20803. (contentsp
  20804. (cl-case type
  20805. ((diary-sexp footnote-definition) 0)
  20806. ((headline inlinetask nil)
  20807. (if (not org-adapt-indentation) 0
  20808. (let ((level (org-current-level)))
  20809. (if level (1+ level) 0))))
  20810. ((item plain-list) (org-list-item-body-column post-affiliated))
  20811. (t
  20812. (goto-char start)
  20813. (org-get-indentation))))
  20814. ((memq type '(headline inlinetask nil))
  20815. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20816. (org--get-expected-indentation element t)
  20817. 0))
  20818. ((memq type '(diary-sexp footnote-definition)) 0)
  20819. ;; First paragraph of a footnote definition or an item.
  20820. ;; Indent like parent.
  20821. ((< (line-beginning-position) start)
  20822. (org--get-expected-indentation
  20823. (org-element-property :parent element) t))
  20824. ;; At first line: indent according to previous sibling, if any,
  20825. ;; ignoring footnote definitions and inline tasks, or parent's
  20826. ;; contents.
  20827. ((= (line-beginning-position) start)
  20828. (catch 'exit
  20829. (while t
  20830. (if (= (point-min) start) (throw 'exit 0)
  20831. (goto-char (1- start))
  20832. (let* ((previous (org-element-at-point))
  20833. (parent previous))
  20834. (while (and parent (<= (org-element-property :end parent) start))
  20835. (setq previous parent
  20836. parent (org-element-property :parent parent)))
  20837. (cond
  20838. ((not previous) (throw 'exit 0))
  20839. ((> (org-element-property :end previous) start)
  20840. (throw 'exit (org--get-expected-indentation previous t)))
  20841. ((memq (org-element-type previous)
  20842. '(footnote-definition inlinetask))
  20843. (setq start (org-element-property :begin previous)))
  20844. (t (goto-char (org-element-property :begin previous))
  20845. (throw 'exit
  20846. (if (bolp) (org-get-indentation)
  20847. ;; At first paragraph in an item or
  20848. ;; a footnote definition.
  20849. (org--get-expected-indentation
  20850. (org-element-property :parent previous) t))))))))))
  20851. ;; Otherwise, move to the first non-blank line above.
  20852. (t
  20853. (beginning-of-line)
  20854. (let ((pos (point)))
  20855. (skip-chars-backward " \r\t\n")
  20856. (cond
  20857. ;; Two blank lines end a footnote definition or a plain
  20858. ;; list. When we indent an empty line after them, the
  20859. ;; containing list or footnote definition is over, so it
  20860. ;; qualifies as a previous sibling. Therefore, we indent
  20861. ;; like its first line.
  20862. ((and (memq type '(footnote-definition plain-list))
  20863. (> (count-lines (point) pos) 2))
  20864. (goto-char start)
  20865. (org-get-indentation))
  20866. ;; Line above is the first one of a paragraph at the
  20867. ;; beginning of an item or a footnote definition. Indent
  20868. ;; like parent.
  20869. ((< (line-beginning-position) start)
  20870. (org--get-expected-indentation
  20871. (org-element-property :parent element) t))
  20872. ;; Line above is the beginning of an element, i.e., point
  20873. ;; was originally on the blank lines between element's start
  20874. ;; and contents.
  20875. ((= (line-beginning-position) post-affiliated)
  20876. (org--get-expected-indentation element t))
  20877. ;; POS is after contents in a greater element. Indent like
  20878. ;; the beginning of the element.
  20879. ;;
  20880. ;; As a special case, if point is at the end of a footnote
  20881. ;; definition or an item, indent like the very last element
  20882. ;; within. If that last element is an item, indent like its
  20883. ;; contents.
  20884. ((and (not (eq type 'paragraph))
  20885. (let ((cend (org-element-property :contents-end element)))
  20886. (and cend (<= cend pos))))
  20887. (if (memq type '(footnote-definition item plain-list))
  20888. (let ((last (org-element-at-point)))
  20889. (org--get-expected-indentation
  20890. last (eq (org-element-type last) 'item)))
  20891. (goto-char start)
  20892. (org-get-indentation)))
  20893. ;; In any other case, indent like the current line.
  20894. (t (org-get-indentation)))))))))
  20895. (defun org--align-node-property ()
  20896. "Align node property at point.
  20897. Alignment is done according to `org-property-format', which see."
  20898. (when (save-excursion
  20899. (beginning-of-line)
  20900. (looking-at org-property-re))
  20901. (replace-match
  20902. (concat (match-string 4)
  20903. (org-trim
  20904. (format org-property-format (match-string 1) (match-string 3))))
  20905. t t)))
  20906. (defun org-indent-line ()
  20907. "Indent line depending on context.
  20908. Indentation is done according to the following rules:
  20909. - Footnote definitions, diary sexps, headlines and inline tasks
  20910. have to start at column 0.
  20911. - On the very first line of an element, consider, in order, the
  20912. next rules until one matches:
  20913. 1. If there's a sibling element before, ignoring footnote
  20914. definitions and inline tasks, indent like its first line.
  20915. 2. If element has a parent, indent like its contents. More
  20916. precisely, if parent is an item, indent after the
  20917. description part, if any, or the bullet (see
  20918. `org-list-description-max-indent'). Else, indent like
  20919. parent's first line.
  20920. 3. Otherwise, indent relatively to current level, if
  20921. `org-adapt-indentation' is non-nil, or to left margin.
  20922. - On a blank line at the end of an element, indent according to
  20923. the type of the element. More precisely
  20924. 1. If element is a plain list, an item, or a footnote
  20925. definition, indent like the very last element within.
  20926. 2. If element is a paragraph, indent like its last non blank
  20927. line.
  20928. 3. Otherwise, indent like its very first line.
  20929. - In the code part of a source block, use language major mode
  20930. to indent current line if `org-src-tab-acts-natively' is
  20931. non-nil. If it is nil, do nothing.
  20932. - Otherwise, indent like the first non-blank line above.
  20933. The function doesn't indent an item as it could break the whole
  20934. list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
  20935. \\[org-shiftmetaright].
  20936. Also align node properties according to `org-property-format'."
  20937. (interactive)
  20938. (cond
  20939. (orgstruct-is-++
  20940. (let ((indent-line-function
  20941. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20942. (indent-according-to-mode)))
  20943. ((org-at-heading-p) 'noindent)
  20944. (t
  20945. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20946. (type (org-element-type element)))
  20947. (cond ((and (memq type '(plain-list item))
  20948. (= (line-beginning-position)
  20949. (org-element-property :post-affiliated element)))
  20950. 'noindent)
  20951. ((and (eq type 'src-block)
  20952. org-src-tab-acts-natively
  20953. (> (line-beginning-position)
  20954. (org-element-property :post-affiliated element))
  20955. (< (line-beginning-position)
  20956. (org-with-wide-buffer
  20957. (goto-char (org-element-property :end element))
  20958. (skip-chars-backward " \r\t\n")
  20959. (line-beginning-position))))
  20960. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20961. (t
  20962. (let ((column (org--get-expected-indentation element nil)))
  20963. ;; Preserve current column.
  20964. (if (<= (current-column) (current-indentation))
  20965. (indent-line-to column)
  20966. (save-excursion (indent-line-to column))))
  20967. ;; Align node property. Also preserve current column.
  20968. (when (eq type 'node-property)
  20969. (let ((column (current-column)))
  20970. (org--align-node-property)
  20971. (org-move-to-column column)))))))))
  20972. (defun org-indent-region (start end)
  20973. "Indent each non-blank line in the region.
  20974. Called from a program, START and END specify the region to
  20975. indent. The function will not indent contents of example blocks,
  20976. verse blocks and export blocks as leading white spaces are
  20977. assumed to be significant there."
  20978. (interactive "r")
  20979. (save-excursion
  20980. (goto-char start)
  20981. (skip-chars-forward " \r\t\n")
  20982. (unless (eobp) (beginning-of-line))
  20983. (let ((indent-to
  20984. (lambda (ind pos)
  20985. ;; Set IND as indentation for all lines between point and
  20986. ;; POS. Blank lines are ignored. Leave point after POS
  20987. ;; once done.
  20988. (let ((limit (copy-marker pos)))
  20989. (while (< (point) limit)
  20990. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20991. (forward-line))
  20992. (set-marker limit nil))))
  20993. (end (copy-marker end)))
  20994. (while (< (point) end)
  20995. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20996. (let* ((element (org-element-at-point))
  20997. (type (org-element-type element))
  20998. (element-end (copy-marker (org-element-property :end element)))
  20999. (ind (org--get-expected-indentation element nil)))
  21000. (cond
  21001. ((or (memq type '(paragraph table table-row))
  21002. (not (or (org-element-property :contents-begin element)
  21003. (memq type
  21004. '(example-block export-block src-block)))))
  21005. ;; Elements here are indented as a single block. Also
  21006. ;; align node properties.
  21007. (when (eq type 'node-property)
  21008. (org--align-node-property)
  21009. (beginning-of-line))
  21010. (funcall indent-to ind (min element-end end)))
  21011. (t
  21012. ;; Elements in this category consist of three parts:
  21013. ;; before the contents, the contents, and after the
  21014. ;; contents. The contents are treated specially,
  21015. ;; according to the element type, or not indented at
  21016. ;; all. Other parts are indented as a single block.
  21017. (let* ((post (copy-marker
  21018. (org-element-property :post-affiliated element)))
  21019. (cbeg
  21020. (copy-marker
  21021. (cond
  21022. ((not (org-element-property :contents-begin element))
  21023. ;; Fake contents for source blocks.
  21024. (org-with-wide-buffer
  21025. (goto-char post)
  21026. (forward-line)
  21027. (point)))
  21028. ((memq type '(footnote-definition item plain-list))
  21029. ;; Contents in these elements could start on
  21030. ;; the same line as the beginning of the
  21031. ;; element. Make sure we start indenting
  21032. ;; from the second line.
  21033. (org-with-wide-buffer
  21034. (goto-char post)
  21035. (end-of-line)
  21036. (skip-chars-forward " \r\t\n")
  21037. (if (eobp) (point) (line-beginning-position))))
  21038. (t (org-element-property :contents-begin element)))))
  21039. (cend (copy-marker
  21040. (or (org-element-property :contents-end element)
  21041. ;; Fake contents for source blocks.
  21042. (org-with-wide-buffer
  21043. (goto-char element-end)
  21044. (skip-chars-backward " \r\t\n")
  21045. (line-beginning-position)))
  21046. t)))
  21047. ;; Do not change items indentation individually as it
  21048. ;; might break the list as a whole. On the other
  21049. ;; hand, when at a plain list, indent it as a whole.
  21050. (cond ((eq type 'plain-list)
  21051. (let ((offset (- ind (org-get-indentation))))
  21052. (unless (zerop offset)
  21053. (indent-rigidly (org-element-property :begin element)
  21054. (org-element-property :end element)
  21055. offset))
  21056. (goto-char cbeg)))
  21057. ((eq type 'item) (goto-char cbeg))
  21058. (t (funcall indent-to ind (min cbeg end))))
  21059. (when (< (point) end)
  21060. (cl-case type
  21061. ((example-block export-block verse-block))
  21062. (src-block
  21063. ;; In a source block, indent source code
  21064. ;; according to language major mode, but only if
  21065. ;; `org-src-tab-acts-natively' is non-nil.
  21066. (when (and (< (point) end) org-src-tab-acts-natively)
  21067. (ignore-errors
  21068. (org-babel-do-in-edit-buffer
  21069. (indent-region (point-min) (point-max))))))
  21070. (t (org-indent-region (point) (min cend end))))
  21071. (goto-char (min cend end))
  21072. (when (< (point) end)
  21073. (funcall indent-to ind (min element-end end))))
  21074. (set-marker post nil)
  21075. (set-marker cbeg nil)
  21076. (set-marker cend nil))))
  21077. (set-marker element-end nil))))
  21078. (set-marker end nil))))
  21079. (defun org-indent-drawer ()
  21080. "Indent the drawer at point."
  21081. (interactive)
  21082. (unless (save-excursion
  21083. (beginning-of-line)
  21084. (looking-at-p org-drawer-regexp))
  21085. (user-error "Not at a drawer"))
  21086. (let ((element (org-element-at-point)))
  21087. (unless (memq (org-element-type element) '(drawer property-drawer))
  21088. (user-error "Not at a drawer"))
  21089. (org-with-wide-buffer
  21090. (org-indent-region (org-element-property :begin element)
  21091. (org-element-property :end element))))
  21092. (message "Drawer at point indented"))
  21093. (defun org-indent-block ()
  21094. "Indent the block at point."
  21095. (interactive)
  21096. (unless (save-excursion
  21097. (beginning-of-line)
  21098. (let ((case-fold-search t))
  21099. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21100. (user-error "Not at a block"))
  21101. (let ((element (org-element-at-point)))
  21102. (unless (memq (org-element-type element)
  21103. '(comment-block center-block dynamic-block example-block
  21104. export-block quote-block special-block
  21105. src-block verse-block))
  21106. (user-error "Not at a block"))
  21107. (org-with-wide-buffer
  21108. (org-indent-region (org-element-property :begin element)
  21109. (org-element-property :end element))))
  21110. (message "Block at point indented"))
  21111. ;;; Filling
  21112. ;; We use our own fill-paragraph and auto-fill functions.
  21113. ;; `org-fill-paragraph' relies on adaptive filling and context
  21114. ;; checking. Appropriate `fill-prefix' is computed with
  21115. ;; `org-adaptive-fill-function'.
  21116. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21117. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21118. ;; `org-adaptive-fill-function' value. Internally,
  21119. ;; `org-comment-line-break-function' breaks the line.
  21120. ;; `org-setup-filling' installs filling and auto-filling related
  21121. ;; variables during `org-mode' initialization.
  21122. (defvar org-element-paragraph-separate) ; org-element.el
  21123. (defun org-setup-filling ()
  21124. (require 'org-element)
  21125. ;; Prevent auto-fill from inserting unwanted new items.
  21126. (when (boundp 'fill-nobreak-predicate)
  21127. (setq-local
  21128. fill-nobreak-predicate
  21129. (org-uniquify
  21130. (append fill-nobreak-predicate
  21131. '(org-fill-line-break-nobreak-p
  21132. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21133. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21134. (setq-local paragraph-start paragraph-ending)
  21135. (setq-local paragraph-separate paragraph-ending))
  21136. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21137. (setq-local auto-fill-inhibit-regexp nil)
  21138. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21139. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21140. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21141. (defun org-fill-line-break-nobreak-p ()
  21142. "Non-nil when a new line at point would create an Org line break."
  21143. (save-excursion
  21144. (skip-chars-backward "[ \t]")
  21145. (skip-chars-backward "\\\\")
  21146. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21147. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21148. "Non-nil when a new line at point would split a timestamp."
  21149. (and (org-at-timestamp-p t)
  21150. (not (looking-at org-ts-regexp-both))))
  21151. (declare-function message-in-body-p "message" ())
  21152. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21153. (defun org-adaptive-fill-function ()
  21154. "Compute a fill prefix for the current line.
  21155. Return fill prefix, as a string, or nil if current line isn't
  21156. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21157. matches in paragraphs or comments, use it."
  21158. (catch 'exit
  21159. (when (derived-mode-p 'message-mode)
  21160. (save-excursion
  21161. (beginning-of-line)
  21162. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21163. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21164. ((looking-at message-cite-prefix-regexp)
  21165. (throw 'exit (match-string-no-properties 0)))
  21166. ((looking-at org-outline-regexp)
  21167. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21168. (org-with-wide-buffer
  21169. (unless (org-at-heading-p)
  21170. (let* ((p (line-beginning-position))
  21171. (element (save-excursion
  21172. (beginning-of-line)
  21173. (org-element-at-point)))
  21174. (type (org-element-type element))
  21175. (post-affiliated (org-element-property :post-affiliated element)))
  21176. (unless (< p post-affiliated)
  21177. (cl-case type
  21178. (comment
  21179. (save-excursion
  21180. (beginning-of-line)
  21181. (looking-at "[ \t]*")
  21182. (concat (match-string 0) "# ")))
  21183. (footnote-definition "")
  21184. ((item plain-list)
  21185. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21186. (paragraph
  21187. ;; Fill prefix is usually the same as the current line,
  21188. ;; unless the paragraph is at the beginning of an item.
  21189. (let ((parent (org-element-property :parent element)))
  21190. (save-excursion
  21191. (beginning-of-line)
  21192. (cond ((eq (org-element-type parent) 'item)
  21193. (make-string (org-list-item-body-column
  21194. (org-element-property :begin parent))
  21195. ?\s))
  21196. ((and adaptive-fill-regexp
  21197. ;; Locally disable
  21198. ;; `adaptive-fill-function' to let
  21199. ;; `fill-context-prefix' handle
  21200. ;; `adaptive-fill-regexp' variable.
  21201. (let (adaptive-fill-function)
  21202. (fill-context-prefix
  21203. post-affiliated
  21204. (org-element-property :end element)))))
  21205. ((looking-at "[ \t]+") (match-string 0))
  21206. (t "")))))
  21207. (comment-block
  21208. ;; Only fill contents if P is within block boundaries.
  21209. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21210. (forward-line)
  21211. (point)))
  21212. (cend (save-excursion
  21213. (goto-char (org-element-property :end element))
  21214. (skip-chars-backward " \r\t\n")
  21215. (line-beginning-position))))
  21216. (when (and (>= p cbeg) (< p cend))
  21217. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21218. (match-string 0)
  21219. "")))))))))))
  21220. (declare-function message-goto-body "message" ())
  21221. (defvar message-cite-prefix-regexp) ; From message.el
  21222. (defun org-fill-paragraph (&optional justify)
  21223. "Fill element at point, when applicable.
  21224. This function only applies to comment blocks, comments, example
  21225. blocks and paragraphs. Also, as a special case, re-align table
  21226. when point is at one.
  21227. If JUSTIFY is non-nil (interactively, with prefix argument),
  21228. justify as well. If `sentence-end-double-space' is non-nil, then
  21229. period followed by one space does not end a sentence, so don't
  21230. break a line there. The variable `fill-column' controls the
  21231. width for filling.
  21232. For convenience, when point is at a plain list, an item or
  21233. a footnote definition, try to fill the first paragraph within."
  21234. (interactive)
  21235. (if (and (derived-mode-p 'message-mode)
  21236. (or (not (message-in-body-p))
  21237. (save-excursion (move-beginning-of-line 1)
  21238. (looking-at message-cite-prefix-regexp))))
  21239. ;; First ensure filling is correct in message-mode.
  21240. (let ((fill-paragraph-function
  21241. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21242. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21243. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21244. (paragraph-separate
  21245. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21246. (fill-paragraph nil))
  21247. (with-syntax-table org-mode-transpose-word-syntax-table
  21248. ;; Move to end of line in order to get the first paragraph
  21249. ;; within a plain list or a footnote definition.
  21250. (let ((element (save-excursion
  21251. (end-of-line)
  21252. (or (ignore-errors (org-element-at-point))
  21253. (user-error "An element cannot be parsed line %d"
  21254. (line-number-at-pos (point)))))))
  21255. ;; First check if point is in a blank line at the beginning of
  21256. ;; the buffer. In that case, ignore filling.
  21257. (cl-case (org-element-type element)
  21258. ;; Use major mode filling function is src blocks.
  21259. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21260. ;; Align Org tables, leave table.el tables as-is.
  21261. (table-row (org-table-align) t)
  21262. (table
  21263. (when (eq (org-element-property :type element) 'org)
  21264. (save-excursion
  21265. (goto-char (org-element-property :post-affiliated element))
  21266. (org-table-align)))
  21267. t)
  21268. (paragraph
  21269. ;; Paragraphs may contain `line-break' type objects.
  21270. (let ((beg (max (point-min)
  21271. (org-element-property :contents-begin element)))
  21272. (end (min (point-max)
  21273. (org-element-property :contents-end element))))
  21274. ;; Do nothing if point is at an affiliated keyword.
  21275. (if (< (line-end-position) beg) t
  21276. (when (derived-mode-p 'message-mode)
  21277. ;; In `message-mode', do not fill following citation
  21278. ;; in current paragraph nor text before message body.
  21279. (let ((body-start (save-excursion (message-goto-body))))
  21280. (when body-start (setq beg (max body-start beg))))
  21281. (when (save-excursion
  21282. (re-search-forward
  21283. (concat "^" message-cite-prefix-regexp) end t))
  21284. (setq end (match-beginning 0))))
  21285. ;; Fill paragraph, taking line breaks into account.
  21286. (save-excursion
  21287. (goto-char beg)
  21288. (let ((cuts (list beg)))
  21289. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21290. (when (eq 'line-break
  21291. (org-element-type
  21292. (save-excursion (backward-char)
  21293. (org-element-context))))
  21294. (push (point) cuts)))
  21295. (dolist (c (delq end cuts))
  21296. (fill-region-as-paragraph c end justify)
  21297. (setq end c))))
  21298. t)))
  21299. ;; Contents of `comment-block' type elements should be
  21300. ;; filled as plain text, but only if point is within block
  21301. ;; markers.
  21302. (comment-block
  21303. (let* ((case-fold-search t)
  21304. (beg (save-excursion
  21305. (goto-char (org-element-property :begin element))
  21306. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21307. (forward-line)
  21308. (point)))
  21309. (end (save-excursion
  21310. (goto-char (org-element-property :end element))
  21311. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21312. (line-beginning-position))))
  21313. (if (or (< (point) beg) (> (point) end)) t
  21314. (fill-region-as-paragraph
  21315. (save-excursion (end-of-line)
  21316. (re-search-backward "^[ \t]*$" beg 'move)
  21317. (line-beginning-position))
  21318. (save-excursion (beginning-of-line)
  21319. (re-search-forward "^[ \t]*$" end 'move)
  21320. (line-beginning-position))
  21321. justify))))
  21322. ;; Fill comments.
  21323. (comment
  21324. (let ((begin (org-element-property :post-affiliated element))
  21325. (end (org-element-property :end element)))
  21326. (when (and (>= (point) begin) (<= (point) end))
  21327. (let ((begin (save-excursion
  21328. (end-of-line)
  21329. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21330. (progn (forward-line) (point))
  21331. begin)))
  21332. (end (save-excursion
  21333. (end-of-line)
  21334. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21335. (1- (line-beginning-position))
  21336. (skip-chars-backward " \r\t\n")
  21337. (line-end-position)))))
  21338. ;; Do not fill comments when at a blank line.
  21339. (when (> end begin)
  21340. (let ((fill-prefix
  21341. (save-excursion
  21342. (beginning-of-line)
  21343. (looking-at "[ \t]*#")
  21344. (let ((comment-prefix (match-string 0)))
  21345. (goto-char (match-end 0))
  21346. (if (looking-at adaptive-fill-regexp)
  21347. (concat comment-prefix (match-string 0))
  21348. (concat comment-prefix " "))))))
  21349. (save-excursion
  21350. (fill-region-as-paragraph begin end justify))))))
  21351. t))
  21352. ;; Ignore every other element.
  21353. (otherwise t))))))
  21354. (defun org-auto-fill-function ()
  21355. "Auto-fill function."
  21356. ;; Check if auto-filling is meaningful.
  21357. (let ((fc (current-fill-column)))
  21358. (when (and fc (> (current-column) fc))
  21359. (let* ((fill-prefix (org-adaptive-fill-function))
  21360. ;; Enforce empty fill prefix, if required. Otherwise, it
  21361. ;; will be computed again.
  21362. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21363. (when fill-prefix (do-auto-fill))))))
  21364. (defun org-comment-line-break-function (&optional soft)
  21365. "Break line at point and indent, continuing comment if within one.
  21366. The inserted newline is marked hard if variable
  21367. `use-hard-newlines' is true, unless optional argument SOFT is
  21368. non-nil."
  21369. (if soft (insert-and-inherit ?\n) (newline 1))
  21370. (save-excursion (forward-char -1) (delete-horizontal-space))
  21371. (delete-horizontal-space)
  21372. (indent-to-left-margin)
  21373. (insert-before-markers-and-inherit fill-prefix))
  21374. ;;; Fixed Width Areas
  21375. (defun org-toggle-fixed-width ()
  21376. "Toggle fixed-width markup.
  21377. Add or remove fixed-width markup on current line, whenever it
  21378. makes sense. Return an error otherwise.
  21379. If a region is active and if it contains only fixed-width areas
  21380. or blank lines, remove all fixed-width markup in it. If the
  21381. region contains anything else, convert all non-fixed-width lines
  21382. to fixed-width ones.
  21383. Blank lines at the end of the region are ignored unless the
  21384. region only contains such lines."
  21385. (interactive)
  21386. (if (not (org-region-active-p))
  21387. ;; No region:
  21388. ;;
  21389. ;; Remove fixed width marker only in a fixed-with element.
  21390. ;;
  21391. ;; Add fixed width maker in paragraphs, in blank lines after
  21392. ;; elements or at the beginning of a headline or an inlinetask,
  21393. ;; and before any one-line elements (e.g., a clock).
  21394. (progn
  21395. (beginning-of-line)
  21396. (let* ((element (org-element-at-point))
  21397. (type (org-element-type element)))
  21398. (cond
  21399. ((and (eq type 'fixed-width)
  21400. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21401. (replace-match
  21402. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21403. ((and (memq type '(babel-call clock comment diary-sexp headline
  21404. horizontal-rule keyword paragraph
  21405. planning))
  21406. (<= (org-element-property :post-affiliated element) (point)))
  21407. (skip-chars-forward " \t")
  21408. (insert ": "))
  21409. ((and (looking-at-p "[ \t]*$")
  21410. (or (eq type 'inlinetask)
  21411. (save-excursion
  21412. (skip-chars-forward " \r\t\n")
  21413. (<= (org-element-property :end element) (point)))))
  21414. (delete-region (point) (line-end-position))
  21415. (org-indent-line)
  21416. (insert ": "))
  21417. (t (user-error "Cannot insert a fixed-width line here")))))
  21418. ;; Region active.
  21419. (let* ((begin (save-excursion
  21420. (goto-char (region-beginning))
  21421. (line-beginning-position)))
  21422. (end (copy-marker
  21423. (save-excursion
  21424. (goto-char (region-end))
  21425. (unless (eolp) (beginning-of-line))
  21426. (if (save-excursion (re-search-backward "\\S-" begin t))
  21427. (progn (skip-chars-backward " \r\t\n") (point))
  21428. (point)))))
  21429. (all-fixed-width-p
  21430. (catch 'not-all-p
  21431. (save-excursion
  21432. (goto-char begin)
  21433. (skip-chars-forward " \r\t\n")
  21434. (when (eobp) (throw 'not-all-p nil))
  21435. (while (< (point) end)
  21436. (let ((element (org-element-at-point)))
  21437. (if (eq (org-element-type element) 'fixed-width)
  21438. (goto-char (org-element-property :end element))
  21439. (throw 'not-all-p nil))))
  21440. t))))
  21441. (if all-fixed-width-p
  21442. (save-excursion
  21443. (goto-char begin)
  21444. (while (< (point) end)
  21445. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21446. (replace-match
  21447. "" nil nil nil
  21448. (if (= (line-end-position) (match-end 0)) 0 1)))
  21449. (forward-line)))
  21450. (let ((min-ind (point-max)))
  21451. ;; Find minimum indentation across all lines.
  21452. (save-excursion
  21453. (goto-char begin)
  21454. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21455. (setq min-ind 0)
  21456. (catch 'zerop
  21457. (while (< (point) end)
  21458. (unless (looking-at-p "[ \t]*$")
  21459. (let ((ind (org-get-indentation)))
  21460. (setq min-ind (min min-ind ind))
  21461. (when (zerop ind) (throw 'zerop t))))
  21462. (forward-line)))))
  21463. ;; Loop over all lines and add fixed-width markup everywhere
  21464. ;; but in fixed-width lines.
  21465. (save-excursion
  21466. (goto-char begin)
  21467. (while (< (point) end)
  21468. (cond
  21469. ((org-at-heading-p)
  21470. (insert ": ")
  21471. (forward-line)
  21472. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21473. (insert ":")
  21474. (forward-line)))
  21475. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21476. (let* ((element (org-element-at-point))
  21477. (element-end (org-element-property :end element)))
  21478. (if (eq (org-element-type element) 'fixed-width)
  21479. (progn (goto-char element-end)
  21480. (skip-chars-backward " \r\t\n")
  21481. (forward-line))
  21482. (let ((limit (min end element-end)))
  21483. (while (< (point) limit)
  21484. (org-move-to-column min-ind t)
  21485. (insert ": ")
  21486. (forward-line))))))
  21487. (t
  21488. (org-move-to-column min-ind t)
  21489. (insert ": ")
  21490. (forward-line)))))))
  21491. (set-marker end nil))))
  21492. ;;; Comments
  21493. ;; Org comments syntax is quite complex. It requires the entire line
  21494. ;; to be just a comment. Also, even with the right syntax at the
  21495. ;; beginning of line, some some elements (i.e. verse-block or
  21496. ;; example-block) don't accept comments. Usual Emacs comment commands
  21497. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21498. ;; Org still relies on `comment-dwim', but cannot trust
  21499. ;; `comment-only-p'. So, `comment-region-function' and
  21500. ;; `uncomment-region-function' both point
  21501. ;; to`org-comment-or-uncomment-region'. Eventually,
  21502. ;; `org-insert-comment' takes care of insertion of comments at the
  21503. ;; beginning of line.
  21504. ;; `org-setup-comments-handling' install comments related variables
  21505. ;; during `org-mode' initialization.
  21506. (defun org-setup-comments-handling ()
  21507. (interactive)
  21508. (setq-local comment-use-syntax nil)
  21509. (setq-local comment-start "# ")
  21510. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21511. (setq-local comment-insert-comment-function 'org-insert-comment)
  21512. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21513. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21514. (defun org-insert-comment ()
  21515. "Insert an empty comment above current line.
  21516. If the line is empty, insert comment at its beginning. When
  21517. point is within a source block, comment according to the related
  21518. major mode."
  21519. (if (let ((element (org-element-at-point)))
  21520. (and (eq (org-element-type element) 'src-block)
  21521. (< (save-excursion
  21522. (goto-char (org-element-property :post-affiliated element))
  21523. (line-end-position))
  21524. (point))
  21525. (> (save-excursion
  21526. (goto-char (org-element-property :end element))
  21527. (skip-chars-backward " \r\t\n")
  21528. (line-beginning-position))
  21529. (point))))
  21530. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21531. (beginning-of-line)
  21532. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21533. (open-line 1))
  21534. (org-indent-line)
  21535. (insert "# ")))
  21536. (defvar comment-empty-lines) ; From newcomment.el.
  21537. (defun org-comment-or-uncomment-region (beg end &rest _)
  21538. "Comment or uncomment each non-blank line in the region.
  21539. Uncomment each non-blank line between BEG and END if it only
  21540. contains commented lines. Otherwise, comment them. If region is
  21541. strictly within a source block, use appropriate comment syntax."
  21542. (if (let ((element (org-element-at-point)))
  21543. (and (eq (org-element-type element) 'src-block)
  21544. (< (save-excursion
  21545. (goto-char (org-element-property :post-affiliated element))
  21546. (line-end-position))
  21547. beg)
  21548. (>= (save-excursion
  21549. (goto-char (org-element-property :end element))
  21550. (skip-chars-backward " \r\t\n")
  21551. (line-beginning-position))
  21552. end)))
  21553. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21554. (save-restriction
  21555. ;; Restrict region
  21556. (narrow-to-region (save-excursion (goto-char beg)
  21557. (skip-chars-forward " \r\t\n" end)
  21558. (line-beginning-position))
  21559. (save-excursion (goto-char end)
  21560. (skip-chars-backward " \r\t\n" beg)
  21561. (line-end-position)))
  21562. (let ((uncommentp
  21563. ;; UNCOMMENTP is non-nil when every non blank line between
  21564. ;; BEG and END is a comment.
  21565. (save-excursion
  21566. (goto-char (point-min))
  21567. (while (and (not (eobp))
  21568. (let ((element (org-element-at-point)))
  21569. (and (eq (org-element-type element) 'comment)
  21570. (goto-char (min (point-max)
  21571. (org-element-property
  21572. :end element)))))))
  21573. (eobp))))
  21574. (if uncommentp
  21575. ;; Only blank lines and comments in region: uncomment it.
  21576. (save-excursion
  21577. (goto-char (point-min))
  21578. (while (not (eobp))
  21579. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21580. (replace-match "" nil nil nil 1))
  21581. (forward-line)))
  21582. ;; Comment each line in region.
  21583. (let ((min-indent (point-max)))
  21584. ;; First find the minimum indentation across all lines.
  21585. (save-excursion
  21586. (goto-char (point-min))
  21587. (while (and (not (eobp)) (not (zerop min-indent)))
  21588. (unless (looking-at "[ \t]*$")
  21589. (setq min-indent (min min-indent (current-indentation))))
  21590. (forward-line)))
  21591. ;; Then loop over all lines.
  21592. (save-excursion
  21593. (goto-char (point-min))
  21594. (while (not (eobp))
  21595. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21596. ;; Don't get fooled by invisible text (e.g. link path)
  21597. ;; when moving to column MIN-INDENT.
  21598. (let ((buffer-invisibility-spec nil))
  21599. (org-move-to-column min-indent t))
  21600. (insert comment-start))
  21601. (forward-line)))))))))
  21602. (defun org-comment-dwim (_arg)
  21603. "Call `comment-dwim' within a source edit buffer if needed."
  21604. (interactive "*P")
  21605. (if (org-in-src-block-p)
  21606. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21607. (call-interactively 'comment-dwim)))
  21608. ;;; Timestamps API
  21609. ;; This section contains tools to operate on timestamp objects, as
  21610. ;; returned by, e.g. `org-element-context'.
  21611. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21612. "Encode TIMESTAMP object into Emacs internal time.
  21613. Use end of date range or time range when END is non-nil."
  21614. (apply #'encode-time
  21615. (cons 0
  21616. (mapcar
  21617. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21618. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21619. '(:minute-start :hour-start :day-start :month-start
  21620. :year-start))))))
  21621. (defun org-timestamp-has-time-p (timestamp)
  21622. "Non-nil when TIMESTAMP has a time specified."
  21623. (org-element-property :hour-start timestamp))
  21624. (defun org-timestamp-format (timestamp format &optional end utc)
  21625. "Format a TIMESTAMP object into a string.
  21626. FORMAT is a format specifier to be passed to
  21627. `format-time-string'.
  21628. When optional argument END is non-nil, use end of date-range or
  21629. time-range, if possible.
  21630. When optional argument UTC is non-nil, time will be expressed as
  21631. Universal Time."
  21632. (format-time-string
  21633. format (org-timestamp--to-internal-time timestamp end)
  21634. (and utc t)))
  21635. (defun org-timestamp-split-range (timestamp &optional end)
  21636. "Extract a TIMESTAMP object from a date or time range.
  21637. END, when non-nil, means extract the end of the range.
  21638. Otherwise, extract its start.
  21639. Return a new timestamp object."
  21640. (let ((type (org-element-property :type timestamp)))
  21641. (if (memq type '(active inactive diary)) timestamp
  21642. (let ((split-ts (org-element-copy timestamp)))
  21643. ;; Set new type.
  21644. (org-element-put-property
  21645. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21646. ;; Copy start properties over end properties if END is
  21647. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21648. (let ((p-alist '((:minute-start . :minute-end)
  21649. (:hour-start . :hour-end)
  21650. (:day-start . :day-end)
  21651. (:month-start . :month-end)
  21652. (:year-start . :year-end))))
  21653. (dolist (p-cell p-alist)
  21654. (org-element-put-property
  21655. split-ts
  21656. (funcall (if end #'car #'cdr) p-cell)
  21657. (org-element-property
  21658. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21659. ;; Eventually refresh `:raw-value'.
  21660. (org-element-put-property split-ts :raw-value nil)
  21661. (org-element-put-property
  21662. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21663. (defun org-timestamp-translate (timestamp &optional boundary)
  21664. "Translate TIMESTAMP object to custom format.
  21665. Format string is defined in `org-time-stamp-custom-formats',
  21666. which see.
  21667. When optional argument BOUNDARY is non-nil, it is either the
  21668. symbol `start' or `end'. In this case, only translate the
  21669. starting or ending part of TIMESTAMP if it is a date or time
  21670. range. Otherwise, translate both parts.
  21671. Return timestamp as-is if `org-display-custom-times' is nil or if
  21672. it has a `diary' type."
  21673. (let ((type (org-element-property :type timestamp)))
  21674. (if (or (not org-display-custom-times) (eq type 'diary))
  21675. (org-element-interpret-data timestamp)
  21676. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21677. org-time-stamp-custom-formats)))
  21678. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21679. (concat (org-timestamp-format timestamp fmt)
  21680. "--"
  21681. (org-timestamp-format timestamp fmt t))
  21682. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21683. ;;; Other stuff.
  21684. (defvar reftex-docstruct-symbol)
  21685. (defvar org--rds)
  21686. (defun org-reftex-citation ()
  21687. "Use reftex-citation to insert a citation into the buffer.
  21688. This looks for a line like
  21689. #+BIBLIOGRAPHY: foo plain option:-d
  21690. and derives from it that foo.bib is the bibliography file relevant
  21691. for this document. It then installs the necessary environment for RefTeX
  21692. to work in this buffer and calls `reftex-citation' to insert a citation
  21693. into the buffer.
  21694. Export of such citations to both LaTeX and HTML is handled by the contributed
  21695. package ox-bibtex by Taru Karttunen."
  21696. (interactive)
  21697. (let ((reftex-docstruct-symbol 'org--rds)
  21698. org--rds bib)
  21699. (org-with-wide-buffer
  21700. (let ((case-fold-search t)
  21701. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21702. (if (not (save-excursion
  21703. (or (re-search-forward re nil t)
  21704. (re-search-backward re nil t))))
  21705. (user-error "No bibliography defined in file")
  21706. (setq bib (concat (match-string 1) ".bib")
  21707. org--rds (list (list 'bib bib))))))
  21708. (call-interactively 'reftex-citation)))
  21709. ;;;; Functions extending outline functionality
  21710. (defun org-beginning-of-line (&optional arg)
  21711. "Go to the beginning of the current line. If that is invisible, continue
  21712. to a visible line beginning. This makes the function of C-a more intuitive.
  21713. If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
  21714. first attempt, and only move to after the tags when the cursor is already
  21715. beyond the end of the headline."
  21716. (interactive "P")
  21717. (let ((pos (point))
  21718. (special (if (consp org-special-ctrl-a/e)
  21719. (car org-special-ctrl-a/e)
  21720. org-special-ctrl-a/e))
  21721. deactivate-mark refpos)
  21722. (call-interactively (if (bound-and-true-p visual-line-mode)
  21723. #'beginning-of-visual-line
  21724. #'move-beginning-of-line))
  21725. (cond
  21726. ((or arg (not special)))
  21727. ((and (looking-at org-complex-heading-regexp)
  21728. (eq (char-after (match-end 1)) ?\s))
  21729. (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21730. (point-at-eol)))
  21731. (goto-char
  21732. (if (eq special t)
  21733. (cond ((> pos refpos) refpos)
  21734. ((= pos (point)) refpos)
  21735. (t (point)))
  21736. (cond ((> pos (point)) (point))
  21737. ((not (eq last-command this-command)) (point))
  21738. (t refpos)))))
  21739. ((org-at-item-p)
  21740. ;; Being at an item and not looking at an the item means point
  21741. ;; was previously moved to beginning of a visual line, which
  21742. ;; doesn't contain the item. Therefore, do nothing special,
  21743. ;; just stay here.
  21744. (when (looking-at org-list-full-item-re)
  21745. ;; Set special position at first white space character after
  21746. ;; bullet, and check-box, if any.
  21747. (let ((after-bullet
  21748. (let ((box (match-end 3)))
  21749. (if (not box) (match-end 1)
  21750. (let ((after (char-after box)))
  21751. (if (and after (= after ? )) (1+ box) box))))))
  21752. ;; Special case: Move point to special position when
  21753. ;; currently after it or at beginning of line.
  21754. (if (eq special t)
  21755. (when (or (> pos after-bullet) (= (point) pos))
  21756. (goto-char after-bullet))
  21757. ;; Reversed case: Move point to special position when
  21758. ;; point was already at beginning of line and command is
  21759. ;; repeated.
  21760. (when (and (= (point) pos) (eq last-command this-command))
  21761. (goto-char after-bullet))))))))
  21762. (setq disable-point-adjustment
  21763. (or (not (invisible-p (point)))
  21764. (not (invisible-p (max (point-min) (1- (point))))))))
  21765. (defun org-end-of-line (&optional arg)
  21766. "Go to the end of the line.
  21767. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21768. tags on the first attempt, and only move to after the tags when
  21769. the cursor is already beyond the end of the headline."
  21770. (interactive "P")
  21771. (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
  21772. org-special-ctrl-a/e))
  21773. (move-fun (cond ((bound-and-true-p visual-line-mode)
  21774. 'end-of-visual-line)
  21775. ((fboundp 'move-end-of-line) 'move-end-of-line)
  21776. (t 'end-of-line)))
  21777. deactivate-mark)
  21778. (if (or (not special) arg) (call-interactively move-fun)
  21779. (let* ((element (save-excursion (beginning-of-line)
  21780. (org-element-at-point)))
  21781. (type (org-element-type element)))
  21782. (cond
  21783. ((memq type '(headline inlinetask))
  21784. (let ((pos (point)))
  21785. (beginning-of-line 1)
  21786. (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
  21787. (if (eq special t)
  21788. (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
  21789. (goto-char (match-beginning 1))
  21790. (goto-char (match-end 0)))
  21791. (if (or (< pos (match-end 0))
  21792. (not (eq this-command last-command)))
  21793. (goto-char (match-end 0))
  21794. (goto-char (match-beginning 1))))
  21795. (call-interactively move-fun))))
  21796. ((outline-invisible-p (line-end-position))
  21797. ;; If element is hidden, `move-end-of-line' would put point
  21798. ;; after it. Use `end-of-line' to stay on current line.
  21799. (call-interactively 'end-of-line))
  21800. (t (call-interactively move-fun))))))
  21801. (setq disable-point-adjustment
  21802. (or (not (invisible-p (point)))
  21803. (not (invisible-p (max (point-min) (1- (point))))))))
  21804. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21805. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21806. (defun org-backward-sentence (&optional _arg)
  21807. "Go to beginning of sentence, or beginning of table field.
  21808. This will call `backward-sentence' or `org-table-beginning-of-field',
  21809. depending on context."
  21810. (interactive)
  21811. (let* ((element (org-element-at-point))
  21812. (contents-begin (org-element-property :contents-begin element))
  21813. (table (org-element-lineage element '(table) t)))
  21814. (if (and table
  21815. (> (point) contents-begin)
  21816. (<= (point) (org-element-property :contents-end table)))
  21817. (call-interactively #'org-table-beginning-of-field)
  21818. (save-restriction
  21819. (when (and contents-begin
  21820. (< (point-min) contents-begin)
  21821. (> (point) contents-begin))
  21822. (narrow-to-region contents-begin
  21823. (org-element-property :contents-end element)))
  21824. (call-interactively #'backward-sentence)))))
  21825. (defun org-forward-sentence (&optional _arg)
  21826. "Go to end of sentence, or end of table field.
  21827. This will call `forward-sentence' or `org-table-end-of-field',
  21828. depending on context."
  21829. (interactive)
  21830. (let* ((element (org-element-at-point))
  21831. (contents-end (org-element-property :contents-end element))
  21832. (table (org-element-lineage element '(table) t)))
  21833. (if (and table
  21834. (>= (point) (org-element-property :contents-begin table))
  21835. (< (point) contents-end))
  21836. (call-interactively #'org-table-end-of-field)
  21837. (save-restriction
  21838. (when (and contents-end
  21839. (> (point-max) contents-end)
  21840. ;; Skip blank lines between elements.
  21841. (< (org-element-property :end element)
  21842. (save-excursion (goto-char contents-end)
  21843. (skip-chars-forward " \r\t\n"))))
  21844. (narrow-to-region (org-element-property :contents-begin element)
  21845. contents-end))
  21846. (call-interactively #'forward-sentence)))))
  21847. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21848. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21849. (defun org-kill-line (&optional _arg)
  21850. "Kill line, to tags or end of line."
  21851. (interactive)
  21852. (cond
  21853. ((or (not org-special-ctrl-k)
  21854. (bolp)
  21855. (not (org-at-heading-p)))
  21856. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21857. org-ctrl-k-protect-subtree
  21858. (or (eq org-ctrl-k-protect-subtree 'error)
  21859. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21860. (user-error "C-k aborted as it would kill a hidden subtree"))
  21861. (call-interactively
  21862. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21863. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21864. (kill-region (point) (match-beginning 1))
  21865. (org-set-tags nil t))
  21866. (t (kill-region (point) (point-at-eol)))))
  21867. (define-key org-mode-map "\C-k" 'org-kill-line)
  21868. (defun org-yank (&optional arg)
  21869. "Yank. If the kill is a subtree, treat it specially.
  21870. This command will look at the current kill and check if is a single
  21871. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21872. cursor is at the beginning of a line or after the stars of a currently
  21873. empty headline, then the yank is handled specially. How exactly depends
  21874. on the value of the following variables.
  21875. `org-yank-folded-subtrees'
  21876. By default, this variable is non-nil, which results in
  21877. subtree(s) being folded after insertion, except if doing so
  21878. would swallow text after the yanked text.
  21879. `org-yank-adjusted-subtrees'
  21880. When non-nil (the default value is nil), the subtree will be
  21881. promoted or demoted in order to fit into the local outline tree
  21882. structure, which means that the level will be adjusted so that it
  21883. becomes the smaller one of the two *visible* surrounding headings.
  21884. Any prefix to this command will cause `yank' to be called directly with
  21885. no special treatment. In particular, a simple \\[universal-argument] prefix \
  21886. will just
  21887. plainly yank the text as it is.
  21888. \[1] The test checks if the first non-white line is a heading
  21889. and if there are no other headings with fewer stars."
  21890. (interactive "P")
  21891. (org-yank-generic 'yank arg))
  21892. (defun org-yank-generic (command arg)
  21893. "Perform some yank-like command.
  21894. This function implements the behavior described in the `org-yank'
  21895. documentation. However, it has been generalized to work for any
  21896. interactive command with similar behavior."
  21897. ;; pretend to be command COMMAND
  21898. (setq this-command command)
  21899. (if arg
  21900. (call-interactively command)
  21901. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21902. (and (org-kill-is-subtree-p)
  21903. (or (bolp)
  21904. (and (looking-at "[ \t]*$")
  21905. (string-match
  21906. "\\`\\*+\\'"
  21907. (buffer-substring (point-at-bol) (point)))))))
  21908. swallowp)
  21909. (cond
  21910. ((and subtreep org-yank-folded-subtrees)
  21911. (let ((beg (point))
  21912. end)
  21913. (if (and subtreep org-yank-adjusted-subtrees)
  21914. (org-paste-subtree nil nil 'for-yank)
  21915. (call-interactively command))
  21916. (setq end (point))
  21917. (goto-char beg)
  21918. (when (and (bolp) subtreep
  21919. (not (setq swallowp
  21920. (org-yank-folding-would-swallow-text beg end))))
  21921. (org-with-limited-levels
  21922. (or (looking-at org-outline-regexp)
  21923. (re-search-forward org-outline-regexp-bol end t))
  21924. (while (and (< (point) end) (looking-at org-outline-regexp))
  21925. (outline-hide-subtree)
  21926. (org-cycle-show-empty-lines 'folded)
  21927. (condition-case nil
  21928. (outline-forward-same-level 1)
  21929. (error (goto-char end))))))
  21930. (when swallowp
  21931. (message
  21932. "Inserted text not folded because that would swallow text"))
  21933. (goto-char end)
  21934. (skip-chars-forward " \t\n\r")
  21935. (beginning-of-line 1)
  21936. (push-mark beg 'nomsg)))
  21937. ((and subtreep org-yank-adjusted-subtrees)
  21938. (let ((beg (point-at-bol)))
  21939. (org-paste-subtree nil nil 'for-yank)
  21940. (push-mark beg 'nomsg)))
  21941. (t
  21942. (call-interactively command))))))
  21943. (defun org-yank-folding-would-swallow-text (beg end)
  21944. "Would hide-subtree at BEG swallow any text after END?"
  21945. (let (level)
  21946. (org-with-limited-levels
  21947. (save-excursion
  21948. (goto-char beg)
  21949. (when (or (looking-at org-outline-regexp)
  21950. (re-search-forward org-outline-regexp-bol end t))
  21951. (setq level (org-outline-level)))
  21952. (goto-char end)
  21953. (skip-chars-forward " \t\r\n\v\f")
  21954. (not (or (eobp)
  21955. (and (bolp) (looking-at-p org-outline-regexp)
  21956. (<= (org-outline-level) level))))))))
  21957. (define-key org-mode-map "\C-y" 'org-yank)
  21958. (defun org-truely-invisible-p ()
  21959. "Check if point is at a character currently not visible.
  21960. This version does not only check the character property, but also
  21961. `visible-mode'."
  21962. ;; Early versions of noutline don't have `outline-invisible-p'.
  21963. (unless (bound-and-true-p visible-mode)
  21964. (outline-invisible-p)))
  21965. (defun org-invisible-p2 ()
  21966. "Check if point is at a character currently not visible."
  21967. (save-excursion
  21968. (when (and (eolp) (not (bobp))) (backward-char 1))
  21969. ;; Early versions of noutline don't have `outline-invisible-p'.
  21970. (outline-invisible-p)))
  21971. (defun org-back-to-heading (&optional invisible-ok)
  21972. "Call `outline-back-to-heading', but provide a better error message."
  21973. (condition-case nil
  21974. (outline-back-to-heading invisible-ok)
  21975. (error (error "Before first headline at position %d in buffer %s"
  21976. (point) (current-buffer)))))
  21977. (defun org-before-first-heading-p ()
  21978. "Before first heading?"
  21979. (save-excursion
  21980. (end-of-line)
  21981. (null (re-search-backward org-outline-regexp-bol nil t))))
  21982. (defun org-at-heading-p (&optional ignored)
  21983. (outline-on-heading-p t))
  21984. (defun org-in-commented-heading-p (&optional no-inheritance)
  21985. "Non-nil if point is under a commented heading.
  21986. This function also checks ancestors of the current headline,
  21987. unless optional argument NO-INHERITANCE is non-nil."
  21988. (cond
  21989. ((org-before-first-heading-p) nil)
  21990. ((let ((headline (nth 4 (org-heading-components))))
  21991. (and headline
  21992. (let ((case-fold-search nil))
  21993. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21994. headline)))))
  21995. (no-inheritance nil)
  21996. (t
  21997. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21998. (defun org-at-comment-p nil
  21999. "Is cursor in a commented line?"
  22000. (save-excursion
  22001. (save-match-data
  22002. (beginning-of-line)
  22003. (looking-at "^[ \t]*# "))))
  22004. (defun org-at-drawer-p nil
  22005. "Is cursor at a drawer keyword?"
  22006. (save-excursion
  22007. (move-beginning-of-line 1)
  22008. (looking-at org-drawer-regexp)))
  22009. (defun org-at-block-p nil
  22010. "Is cursor at a block keyword?"
  22011. (save-excursion
  22012. (move-beginning-of-line 1)
  22013. (looking-at org-block-regexp)))
  22014. (defun org-point-at-end-of-empty-headline ()
  22015. "If point is at the end of an empty headline, return t, else nil.
  22016. If the heading only contains a TODO keyword, it is still still considered
  22017. empty."
  22018. (and (looking-at "[ \t]*$")
  22019. (when org-todo-line-regexp
  22020. (save-excursion
  22021. (beginning-of-line 1)
  22022. (let ((case-fold-search nil))
  22023. (looking-at org-todo-line-regexp)
  22024. (string= (match-string 3) ""))))))
  22025. (defun org-at-heading-or-item-p ()
  22026. (or (org-at-heading-p) (org-at-item-p)))
  22027. (defun org-at-target-p ()
  22028. (or (org-in-regexp org-radio-target-regexp)
  22029. (org-in-regexp org-target-regexp)))
  22030. ;; Compatibility alias with Org versions < 7.8.03
  22031. (defalias 'org-on-target-p 'org-at-target-p)
  22032. (defun org-up-heading-all (arg)
  22033. "Move to the heading line of which the present line is a subheading.
  22034. This function considers both visible and invisible heading lines.
  22035. With argument, move up ARG levels."
  22036. (outline-up-heading arg t))
  22037. (defun org-up-heading-safe ()
  22038. "Move to the heading line of which the present line is a subheading.
  22039. This version will not throw an error. It will return the level of the
  22040. headline found, or nil if no higher level is found.
  22041. Also, this function will be a lot faster than `outline-up-heading',
  22042. because it relies on stars being the outline starters. This can really
  22043. make a significant difference in outlines with very many siblings."
  22044. (when (ignore-errors (org-back-to-heading t))
  22045. (let ((level-up (1- (funcall outline-level))))
  22046. (and (> level-up 0)
  22047. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22048. (funcall outline-level)))))
  22049. (defun org-first-sibling-p ()
  22050. "Is this heading the first child of its parents?"
  22051. (interactive)
  22052. (let ((re org-outline-regexp-bol)
  22053. level l)
  22054. (unless (org-at-heading-p t)
  22055. (user-error "Not at a heading"))
  22056. (setq level (funcall outline-level))
  22057. (save-excursion
  22058. (if (not (re-search-backward re nil t))
  22059. t
  22060. (setq l (funcall outline-level))
  22061. (< l level)))))
  22062. (defun org-goto-sibling (&optional previous)
  22063. "Goto the next sibling, even if it is invisible.
  22064. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22065. when a sibling was found. When none is found, return nil and don't
  22066. move point."
  22067. (let ((fun (if previous 're-search-backward 're-search-forward))
  22068. (pos (point))
  22069. (re org-outline-regexp-bol)
  22070. level l)
  22071. (when (ignore-errors (org-back-to-heading t))
  22072. (setq level (funcall outline-level))
  22073. (catch 'exit
  22074. (or previous (forward-char 1))
  22075. (while (funcall fun re nil t)
  22076. (setq l (funcall outline-level))
  22077. (when (< l level) (goto-char pos) (throw 'exit nil))
  22078. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22079. (goto-char pos)
  22080. nil))))
  22081. (defun org-show-siblings ()
  22082. "Show all siblings of the current headline."
  22083. (save-excursion
  22084. (while (org-goto-sibling) (org-flag-heading nil)))
  22085. (save-excursion
  22086. (while (org-goto-sibling 'previous)
  22087. (org-flag-heading nil))))
  22088. (defun org-goto-first-child ()
  22089. "Goto the first child, even if it is invisible.
  22090. Return t when a child was found. Otherwise don't move point and
  22091. return nil."
  22092. (let (level (pos (point)) (re org-outline-regexp-bol))
  22093. (when (ignore-errors (org-back-to-heading t))
  22094. (setq level (outline-level))
  22095. (forward-char 1)
  22096. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22097. (progn (goto-char (match-beginning 0)) t)
  22098. (goto-char pos) nil))))
  22099. (defun org-show-hidden-entry ()
  22100. "Show an entry where even the heading is hidden."
  22101. (save-excursion
  22102. (org-show-entry)))
  22103. (defun org-flag-heading (flag &optional entry)
  22104. "Flag the current heading. FLAG non-nil means make invisible.
  22105. When ENTRY is non-nil, show the entire entry."
  22106. (save-excursion
  22107. (org-back-to-heading t)
  22108. ;; Check if we should show the entire entry
  22109. (if entry
  22110. (progn
  22111. (org-show-entry)
  22112. (save-excursion
  22113. (and (outline-next-heading)
  22114. (org-flag-heading nil))))
  22115. (outline-flag-region (max (point-min) (1- (point)))
  22116. (save-excursion (outline-end-of-heading) (point))
  22117. flag))))
  22118. (defun org-get-next-sibling ()
  22119. "Move to next heading of the same level, and return point.
  22120. If there is no such heading, return nil.
  22121. This is like outline-next-sibling, but invisible headings are ok."
  22122. (let ((level (funcall outline-level)))
  22123. (outline-next-heading)
  22124. (while (and (not (eobp)) (> (funcall outline-level) level))
  22125. (outline-next-heading))
  22126. (unless (or (eobp) (< (funcall outline-level) level))
  22127. (point))))
  22128. (defun org-get-last-sibling ()
  22129. "Move to previous heading of the same level, and return point.
  22130. If there is no such heading, return nil."
  22131. (let ((opoint (point))
  22132. (level (funcall outline-level)))
  22133. (outline-previous-heading)
  22134. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22135. (while (and (> (funcall outline-level) level)
  22136. (not (bobp)))
  22137. (outline-previous-heading))
  22138. (unless (< (funcall outline-level) level)
  22139. (point)))))
  22140. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22141. "Goto to the end of a subtree."
  22142. ;; This contains an exact copy of the original function, but it uses
  22143. ;; `org-back-to-heading', to make it work also in invisible
  22144. ;; trees. And is uses an invisible-ok argument.
  22145. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22146. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22147. ;; with many children and grandchildren etc, this can be much faster
  22148. ;; than the outline version.
  22149. (org-back-to-heading invisible-ok)
  22150. (let ((first t)
  22151. (level (funcall outline-level)))
  22152. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22153. ;; A true heading (not a plain list item), in Org
  22154. ;; This means we can easily find the end by looking
  22155. ;; only for the right number of stars. Using a regexp to do
  22156. ;; this is so much faster than using a Lisp loop.
  22157. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22158. (forward-char 1)
  22159. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22160. ;; something else, do it the slow way
  22161. (while (and (not (eobp))
  22162. (or first (> (funcall outline-level) level)))
  22163. (setq first nil)
  22164. (outline-next-heading)))
  22165. (unless to-heading
  22166. (when (memq (preceding-char) '(?\n ?\^M))
  22167. ;; Go to end of line before heading
  22168. (forward-char -1)
  22169. (when (memq (preceding-char) '(?\n ?\^M))
  22170. ;; leave blank line before heading
  22171. (forward-char -1)))))
  22172. (point))
  22173. (defun org-end-of-meta-data (&optional full)
  22174. "Skip planning line and properties drawer in current entry.
  22175. When optional argument FULL is non-nil, also skip empty lines,
  22176. clocking lines and regular drawers at the beginning of the
  22177. entry."
  22178. (org-back-to-heading t)
  22179. (forward-line)
  22180. (when (looking-at-p org-planning-line-re) (forward-line))
  22181. (when (looking-at org-property-drawer-re)
  22182. (goto-char (match-end 0))
  22183. (forward-line))
  22184. (when (and full (not (org-at-heading-p)))
  22185. (catch 'exit
  22186. (let ((end (save-excursion (outline-next-heading) (point)))
  22187. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22188. (while (not (eobp))
  22189. (cond ((looking-at-p org-drawer-regexp)
  22190. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22191. (forward-line)
  22192. (throw 'exit t)))
  22193. ((looking-at-p re) (forward-line))
  22194. (t (throw 'exit t))))))))
  22195. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22196. "Move forward to the ARG'th subheading at same level as this one.
  22197. Stop at the first and last subheadings of a superior heading.
  22198. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22199. non-nil it will also look at invisible ones."
  22200. (interactive "p")
  22201. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22202. (if (and arg (< arg 0))
  22203. (goto-char (point-min))
  22204. (outline-next-heading))
  22205. (org-at-heading-p)
  22206. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22207. (f (if (and arg (< arg 0))
  22208. 're-search-backward
  22209. 're-search-forward))
  22210. (count (if arg (abs arg) 1))
  22211. (result (point)))
  22212. (while (and (prog1 (> count 0)
  22213. (forward-char (if (and arg (< arg 0)) -1 1)))
  22214. (funcall f org-outline-regexp-bol nil 'move))
  22215. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22216. (cond ((< l level) (setq count 0))
  22217. ((and (= l level)
  22218. (or invisible-ok
  22219. (progn
  22220. (goto-char (line-beginning-position))
  22221. (not (outline-invisible-p)))))
  22222. (setq count (1- count))
  22223. (when (eq l level)
  22224. (setq result (point)))))))
  22225. (goto-char result))
  22226. (beginning-of-line 1)))
  22227. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22228. "Move backward to the ARG'th subheading at same level as this one.
  22229. Stop at the first and last subheadings of a superior heading."
  22230. (interactive "p")
  22231. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22232. (defun org-next-visible-heading (arg)
  22233. "Move to the next visible heading.
  22234. This function wraps `outline-next-visible-heading' with
  22235. `org-with-limited-levels' in order to skip over inline tasks and
  22236. respect customization of `org-odd-levels-only'."
  22237. (interactive "p")
  22238. (org-with-limited-levels
  22239. (outline-next-visible-heading arg)))
  22240. (defun org-previous-visible-heading (arg)
  22241. "Move to the previous visible heading.
  22242. This function wraps `outline-previous-visible-heading' with
  22243. `org-with-limited-levels' in order to skip over inline tasks and
  22244. respect customization of `org-odd-levels-only'."
  22245. (interactive "p")
  22246. (org-with-limited-levels
  22247. (outline-previous-visible-heading arg)))
  22248. (defun org-next-block (arg &optional backward block-regexp)
  22249. "Jump to the next block.
  22250. With a prefix argument ARG, jump forward ARG many blocks.
  22251. When BACKWARD is non-nil, jump to the previous block.
  22252. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22253. Match data is set according to this regexp when the function
  22254. returns.
  22255. Return point at beginning of the opening line of found block.
  22256. Throw an error if no block is found."
  22257. (interactive "p")
  22258. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22259. (case-fold-search t)
  22260. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22261. (count (or arg 1))
  22262. (origin (point))
  22263. last-element)
  22264. (if backward (beginning-of-line) (end-of-line))
  22265. (while (and (> count 0) (funcall search-fn re nil t))
  22266. (let ((element (save-excursion
  22267. (goto-char (match-beginning 0))
  22268. (save-match-data (org-element-at-point)))))
  22269. (when (and (memq (org-element-type element)
  22270. '(center-block comment-block dynamic-block
  22271. example-block export-block quote-block
  22272. special-block src-block verse-block))
  22273. (<= (match-beginning 0)
  22274. (org-element-property :post-affiliated element)))
  22275. (setq last-element element)
  22276. (cl-decf count))))
  22277. (if (= count 0)
  22278. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22279. (save-match-data (org-show-context)))
  22280. (goto-char origin)
  22281. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22282. (defun org-previous-block (arg &optional block-regexp)
  22283. "Jump to the previous block.
  22284. With a prefix argument ARG, jump backward ARG many source blocks.
  22285. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22286. (interactive "p")
  22287. (org-next-block arg t block-regexp))
  22288. (defun org-forward-paragraph ()
  22289. "Move forward to beginning of next paragraph or equivalent.
  22290. The function moves point to the beginning of the next visible
  22291. structural element, which can be a paragraph, a table, a list
  22292. item, etc. It also provides some special moves for convenience:
  22293. - On an affiliated keyword, jump to the beginning of the
  22294. relative element.
  22295. - On an item or a footnote definition, move to the second
  22296. element inside, if any.
  22297. - On a table or a property drawer, jump after it.
  22298. - On a verse or source block, stop after blank lines."
  22299. (interactive)
  22300. (when (eobp) (user-error "Cannot move further down"))
  22301. (let* ((deactivate-mark nil)
  22302. (element (org-element-at-point))
  22303. (type (org-element-type element))
  22304. (post-affiliated (org-element-property :post-affiliated element))
  22305. (contents-begin (org-element-property :contents-begin element))
  22306. (contents-end (org-element-property :contents-end element))
  22307. (end (let ((end (org-element-property :end element)) (parent element))
  22308. (while (and (setq parent (org-element-property :parent parent))
  22309. (= (org-element-property :contents-end parent) end))
  22310. (setq end (org-element-property :end parent)))
  22311. end)))
  22312. (cond ((not element)
  22313. (skip-chars-forward " \r\t\n")
  22314. (or (eobp) (beginning-of-line)))
  22315. ;; On affiliated keywords, move to element's beginning.
  22316. ((< (point) post-affiliated)
  22317. (goto-char post-affiliated))
  22318. ;; At a table row, move to the end of the table. Similarly,
  22319. ;; at a node property, move to the end of the property
  22320. ;; drawer.
  22321. ((memq type '(node-property table-row))
  22322. (goto-char (org-element-property
  22323. :end (org-element-property :parent element))))
  22324. ((memq type '(property-drawer table)) (goto-char end))
  22325. ;; Consider blank lines as separators in verse and source
  22326. ;; blocks to ease editing.
  22327. ((memq type '(src-block verse-block))
  22328. (when (eq type 'src-block)
  22329. (setq contents-end
  22330. (save-excursion (goto-char end)
  22331. (skip-chars-backward " \r\t\n")
  22332. (line-beginning-position))))
  22333. (beginning-of-line)
  22334. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22335. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22336. (goto-char end)
  22337. (skip-chars-forward " \r\t\n")
  22338. (if (= (point) contents-end) (goto-char end)
  22339. (beginning-of-line))))
  22340. ;; With no contents, just skip element.
  22341. ((not contents-begin) (goto-char end))
  22342. ;; If contents are invisible, skip the element altogether.
  22343. ((outline-invisible-p (line-end-position))
  22344. (cl-case type
  22345. (headline
  22346. (org-with-limited-levels (outline-next-visible-heading 1)))
  22347. ;; At a plain list, make sure we move to the next item
  22348. ;; instead of skipping the whole list.
  22349. (plain-list (forward-char)
  22350. (org-forward-paragraph))
  22351. (otherwise (goto-char end))))
  22352. ((>= (point) contents-end) (goto-char end))
  22353. ((>= (point) contents-begin)
  22354. ;; This can only happen on paragraphs and plain lists.
  22355. (cl-case type
  22356. (paragraph (goto-char end))
  22357. ;; At a plain list, try to move to second element in
  22358. ;; first item, if possible.
  22359. (plain-list (end-of-line)
  22360. (org-forward-paragraph))))
  22361. ;; When contents start on the middle of a line (e.g. in
  22362. ;; items and footnote definitions), try to reach first
  22363. ;; element starting after current line.
  22364. ((> (line-end-position) contents-begin)
  22365. (end-of-line)
  22366. (org-forward-paragraph))
  22367. (t (goto-char contents-begin)))))
  22368. (defun org-backward-paragraph ()
  22369. "Move backward to start of previous paragraph or equivalent.
  22370. The function moves point to the beginning of the current
  22371. structural element, which can be a paragraph, a table, a list
  22372. item, etc., or to the beginning of the previous visible one if
  22373. point is already there. It also provides some special moves for
  22374. convenience:
  22375. - On an affiliated keyword, jump to the first one.
  22376. - On a table or a property drawer, move to its beginning.
  22377. - On a verse or source block, stop before blank lines."
  22378. (interactive)
  22379. (when (bobp) (user-error "Cannot move further up"))
  22380. (let* ((deactivate-mark nil)
  22381. (element (org-element-at-point))
  22382. (type (org-element-type element))
  22383. (contents-begin (org-element-property :contents-begin element))
  22384. (contents-end (org-element-property :contents-end element))
  22385. (post-affiliated (org-element-property :post-affiliated element))
  22386. (begin (org-element-property :begin element)))
  22387. (cond
  22388. ((not element) (goto-char (point-min)))
  22389. ((= (point) begin)
  22390. (backward-char)
  22391. (org-backward-paragraph))
  22392. ((<= (point) post-affiliated) (goto-char begin))
  22393. ((memq type '(node-property table-row))
  22394. (goto-char (org-element-property
  22395. :post-affiliated (org-element-property :parent element))))
  22396. ((memq type '(property-drawer table)) (goto-char begin))
  22397. ((memq type '(src-block verse-block))
  22398. (when (eq type 'src-block)
  22399. (setq contents-begin
  22400. (save-excursion (goto-char begin) (forward-line) (point))))
  22401. (if (= (point) contents-begin) (goto-char post-affiliated)
  22402. ;; Inside a verse block, see blank lines as paragraph
  22403. ;; separators.
  22404. (let ((origin (point)))
  22405. (skip-chars-backward " \r\t\n" contents-begin)
  22406. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22407. (skip-chars-forward " \r\t\n" origin)
  22408. (if (= (point) origin) (goto-char contents-begin)
  22409. (beginning-of-line))))))
  22410. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22411. ((eq type 'paragraph)
  22412. (goto-char contents-begin)
  22413. ;; When at first paragraph in an item or a footnote definition,
  22414. ;; move directly to beginning of line.
  22415. (let ((parent-contents
  22416. (org-element-property
  22417. :contents-begin (org-element-property :parent element))))
  22418. (when (and parent-contents (= parent-contents contents-begin))
  22419. (beginning-of-line))))
  22420. ;; At the end of a greater element, move to the beginning of the
  22421. ;; last element within.
  22422. ((>= (point) contents-end)
  22423. (goto-char (1- contents-end))
  22424. (org-backward-paragraph))
  22425. (t (goto-char (or post-affiliated begin))))
  22426. ;; Ensure we never leave point invisible.
  22427. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22428. (defun org-forward-element ()
  22429. "Move forward by one element.
  22430. Move to the next element at the same level, when possible."
  22431. (interactive)
  22432. (cond ((eobp) (user-error "Cannot move further down"))
  22433. ((org-with-limited-levels (org-at-heading-p))
  22434. (let ((origin (point)))
  22435. (goto-char (org-end-of-subtree nil t))
  22436. (unless (org-with-limited-levels (org-at-heading-p))
  22437. (goto-char origin)
  22438. (user-error "Cannot move further down"))))
  22439. (t
  22440. (let* ((elem (org-element-at-point))
  22441. (end (org-element-property :end elem))
  22442. (parent (org-element-property :parent elem)))
  22443. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22444. (goto-char (org-element-property :end parent)))
  22445. ((integer-or-marker-p end) (goto-char end))
  22446. (t (message "No element at point")))))))
  22447. (defun org-backward-element ()
  22448. "Move backward by one element.
  22449. Move to the previous element at the same level, when possible."
  22450. (interactive)
  22451. (cond ((bobp) (user-error "Cannot move further up"))
  22452. ((org-with-limited-levels (org-at-heading-p))
  22453. ;; At a headline, move to the previous one, if any, or stay
  22454. ;; here.
  22455. (let ((origin (point)))
  22456. (org-with-limited-levels (org-backward-heading-same-level 1))
  22457. ;; When current headline has no sibling above, move to its
  22458. ;; parent.
  22459. (when (= (point) origin)
  22460. (or (org-with-limited-levels (org-up-heading-safe))
  22461. (progn (goto-char origin)
  22462. (user-error "Cannot move further up"))))))
  22463. (t
  22464. (let* ((elem (org-element-at-point))
  22465. (beg (org-element-property :begin elem)))
  22466. (cond
  22467. ;; Move to beginning of current element if point isn't
  22468. ;; there already.
  22469. ((null beg) (message "No element at point"))
  22470. ((/= (point) beg) (goto-char beg))
  22471. (t (goto-char beg)
  22472. (skip-chars-backward " \r\t\n")
  22473. (unless (bobp)
  22474. (let ((prev (org-element-at-point)))
  22475. (goto-char (org-element-property :begin prev))
  22476. (while (and (setq prev (org-element-property :parent prev))
  22477. (<= (org-element-property :end prev) beg))
  22478. (goto-char (org-element-property :begin prev)))))))))))
  22479. (defun org-up-element ()
  22480. "Move to upper element."
  22481. (interactive)
  22482. (if (org-with-limited-levels (org-at-heading-p))
  22483. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22484. (let* ((elem (org-element-at-point))
  22485. (parent (org-element-property :parent elem)))
  22486. (if parent (goto-char (org-element-property :begin parent))
  22487. (if (org-with-limited-levels (org-before-first-heading-p))
  22488. (user-error "No surrounding element")
  22489. (org-with-limited-levels (org-back-to-heading)))))))
  22490. (defvar org-element-greater-elements)
  22491. (defun org-down-element ()
  22492. "Move to inner element."
  22493. (interactive)
  22494. (let ((element (org-element-at-point)))
  22495. (cond
  22496. ((memq (org-element-type element) '(plain-list table))
  22497. (goto-char (org-element-property :contents-begin element))
  22498. (forward-char))
  22499. ((memq (org-element-type element) org-element-greater-elements)
  22500. ;; If contents are hidden, first disclose them.
  22501. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22502. (goto-char (or (org-element-property :contents-begin element)
  22503. (user-error "No content for this element"))))
  22504. (t (user-error "No inner element")))))
  22505. (defun org-drag-element-backward ()
  22506. "Move backward element at point."
  22507. (interactive)
  22508. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22509. (let* ((elem (org-element-at-point))
  22510. (prev-elem
  22511. (save-excursion
  22512. (goto-char (org-element-property :begin elem))
  22513. (skip-chars-backward " \r\t\n")
  22514. (unless (bobp)
  22515. (let* ((beg (org-element-property :begin elem))
  22516. (prev (org-element-at-point))
  22517. (up prev))
  22518. (while (and (setq up (org-element-property :parent up))
  22519. (<= (org-element-property :end up) beg))
  22520. (setq prev up))
  22521. prev)))))
  22522. ;; Error out if no previous element or previous element is
  22523. ;; a parent of the current one.
  22524. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22525. (user-error "Cannot drag element backward")
  22526. (let ((pos (point)))
  22527. (org-element-swap-A-B prev-elem elem)
  22528. (goto-char (+ (org-element-property :begin prev-elem)
  22529. (- pos (org-element-property :begin elem)))))))))
  22530. (defun org-drag-element-forward ()
  22531. "Move forward element at point."
  22532. (interactive)
  22533. (let* ((pos (point))
  22534. (elem (org-element-at-point)))
  22535. (when (= (point-max) (org-element-property :end elem))
  22536. (user-error "Cannot drag element forward"))
  22537. (goto-char (org-element-property :end elem))
  22538. (let ((next-elem (org-element-at-point)))
  22539. (when (or (org-element-nested-p elem next-elem)
  22540. (and (eq (org-element-type next-elem) 'headline)
  22541. (not (eq (org-element-type elem) 'headline))))
  22542. (goto-char pos)
  22543. (user-error "Cannot drag element forward"))
  22544. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22545. ;; body's length (without final blanks) and by the length of
  22546. ;; blanks between ELEM and NEXT-ELEM.
  22547. (let ((size-next (- (save-excursion
  22548. (goto-char (org-element-property :end next-elem))
  22549. (skip-chars-backward " \r\t\n")
  22550. (forward-line)
  22551. ;; Small correction if buffer doesn't end
  22552. ;; with a newline character.
  22553. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22554. (org-element-property :begin next-elem)))
  22555. (size-blank (- (org-element-property :end elem)
  22556. (save-excursion
  22557. (goto-char (org-element-property :end elem))
  22558. (skip-chars-backward " \r\t\n")
  22559. (forward-line)
  22560. (point)))))
  22561. (org-element-swap-A-B elem next-elem)
  22562. (goto-char (+ pos size-next size-blank))))))
  22563. (defun org-drag-line-forward (arg)
  22564. "Drag the line at point ARG lines forward."
  22565. (interactive "p")
  22566. (dotimes (_ (abs arg))
  22567. (let ((c (current-column)))
  22568. (if (< 0 arg)
  22569. (progn
  22570. (beginning-of-line 2)
  22571. (transpose-lines 1)
  22572. (beginning-of-line 0))
  22573. (transpose-lines 1)
  22574. (beginning-of-line -1))
  22575. (org-move-to-column c))))
  22576. (defun org-drag-line-backward (arg)
  22577. "Drag the line at point ARG lines backward."
  22578. (interactive "p")
  22579. (org-drag-line-forward (- arg)))
  22580. (defun org-mark-element ()
  22581. "Put point at beginning of this element, mark at end.
  22582. Interactively, if this command is repeated or (in Transient Mark
  22583. mode) if the mark is active, it marks the next element after the
  22584. ones already marked."
  22585. (interactive)
  22586. (let (deactivate-mark)
  22587. (if (and (called-interactively-p 'any)
  22588. (or (and (eq last-command this-command) (mark t))
  22589. (and transient-mark-mode mark-active)))
  22590. (set-mark
  22591. (save-excursion
  22592. (goto-char (mark))
  22593. (goto-char (org-element-property :end (org-element-at-point)))))
  22594. (let ((element (org-element-at-point)))
  22595. (end-of-line)
  22596. (push-mark (org-element-property :end element) t t)
  22597. (goto-char (org-element-property :begin element))))))
  22598. (defun org-narrow-to-element ()
  22599. "Narrow buffer to current element."
  22600. (interactive)
  22601. (let ((elem (org-element-at-point)))
  22602. (cond
  22603. ((eq (car elem) 'headline)
  22604. (narrow-to-region
  22605. (org-element-property :begin elem)
  22606. (org-element-property :end elem)))
  22607. ((memq (car elem) org-element-greater-elements)
  22608. (narrow-to-region
  22609. (org-element-property :contents-begin elem)
  22610. (org-element-property :contents-end elem)))
  22611. (t
  22612. (narrow-to-region
  22613. (org-element-property :begin elem)
  22614. (org-element-property :end elem))))))
  22615. (defun org-transpose-element ()
  22616. "Transpose current and previous elements, keeping blank lines between.
  22617. Point is moved after both elements."
  22618. (interactive)
  22619. (org-skip-whitespace)
  22620. (let ((end (org-element-property :end (org-element-at-point))))
  22621. (org-drag-element-backward)
  22622. (goto-char end)))
  22623. (defun org-unindent-buffer ()
  22624. "Un-indent the visible part of the buffer.
  22625. Relative indentation (between items, inside blocks, etc.) isn't
  22626. modified."
  22627. (interactive)
  22628. (unless (eq major-mode 'org-mode)
  22629. (user-error "Cannot un-indent a buffer not in Org mode"))
  22630. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22631. (unindent-tree
  22632. (lambda (contents)
  22633. (dolist (element (reverse contents))
  22634. (if (memq (org-element-type element) '(headline section))
  22635. (funcall unindent-tree (org-element-contents element))
  22636. (save-excursion
  22637. (save-restriction
  22638. (narrow-to-region
  22639. (org-element-property :begin element)
  22640. (org-element-property :end element))
  22641. (org-do-remove-indentation))))))))
  22642. (funcall unindent-tree (org-element-contents parse-tree))))
  22643. (defun org-show-children (&optional level)
  22644. "Show all direct subheadings of this heading.
  22645. Prefix arg LEVEL is how many levels below the current level
  22646. should be shown. Default is enough to cause the following
  22647. heading to appear."
  22648. (interactive "p")
  22649. ;; If `orgstruct-mode' is active, use the slower version.
  22650. (if orgstruct-mode (call-interactively #'outline-show-children)
  22651. (save-excursion
  22652. (org-back-to-heading t)
  22653. (let* ((current-level (funcall outline-level))
  22654. (max-level (org-get-valid-level
  22655. current-level
  22656. (if level (prefix-numeric-value level) 1)))
  22657. (end (save-excursion (org-end-of-subtree t t)))
  22658. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22659. (past-first-child nil)
  22660. ;; Make sure to skip inlinetasks.
  22661. (re (format regexp-fmt
  22662. current-level
  22663. (cond
  22664. ((not (featurep 'org-inlinetask)) "")
  22665. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22666. 3))
  22667. (t (1- org-inlinetask-min-level))))))
  22668. ;; Display parent heading.
  22669. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22670. (forward-line)
  22671. ;; Display children. First child may be deeper than expected
  22672. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22673. ;; MAX-LEVEL accordingly.
  22674. (while (re-search-forward re end t)
  22675. (unless past-first-child
  22676. (setq re (format regexp-fmt
  22677. current-level
  22678. (max (funcall outline-level) max-level)))
  22679. (setq past-first-child t))
  22680. (outline-flag-region
  22681. (line-end-position 0) (line-end-position) nil))))))
  22682. (defun org-show-subtree ()
  22683. "Show everything after this heading at deeper levels."
  22684. (interactive)
  22685. (outline-flag-region
  22686. (point)
  22687. (save-excursion
  22688. (org-end-of-subtree t t))
  22689. nil))
  22690. (defun org-show-entry ()
  22691. "Show the body directly following this heading.
  22692. Show the heading too, if it is currently invisible."
  22693. (interactive)
  22694. (save-excursion
  22695. (ignore-errors
  22696. (org-back-to-heading t)
  22697. (outline-flag-region
  22698. (max (point-min) (1- (point)))
  22699. (save-excursion
  22700. (if (re-search-forward
  22701. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22702. (match-beginning 1)
  22703. (point-max)))
  22704. nil)
  22705. (org-cycle-hide-drawers 'children))))
  22706. (defun org-make-options-regexp (kwds &optional extra)
  22707. "Make a regular expression for keyword lines.
  22708. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22709. when non-nil, is a regexp matching keywords names."
  22710. (concat "^[ \t]*#\\+\\("
  22711. (regexp-opt kwds)
  22712. (and extra (concat (and kwds "\\|") extra))
  22713. "\\):[ \t]*\\(.*\\)"))
  22714. ;;;; Integration with and fixes for other packages
  22715. ;;; Imenu support
  22716. (defvar-local org-imenu-markers nil
  22717. "All markers currently used by Imenu.")
  22718. (defun org-imenu-new-marker (&optional pos)
  22719. "Return a new marker for use by Imenu, and remember the marker."
  22720. (let ((m (make-marker)))
  22721. (move-marker m (or pos (point)))
  22722. (push m org-imenu-markers)
  22723. m))
  22724. (defun org-imenu-get-tree ()
  22725. "Produce the index for Imenu."
  22726. (dolist (x org-imenu-markers) (move-marker x nil))
  22727. (setq org-imenu-markers nil)
  22728. (let* ((case-fold-search nil)
  22729. (n org-imenu-depth)
  22730. (re (concat "^" (org-get-limited-outline-regexp)))
  22731. (subs (make-vector (1+ n) nil))
  22732. (last-level 0)
  22733. m level head0 head)
  22734. (org-with-wide-buffer
  22735. (goto-char (point-max))
  22736. (while (re-search-backward re nil t)
  22737. (setq level (org-reduced-level (funcall outline-level)))
  22738. (when (and (<= level n)
  22739. (looking-at org-complex-heading-regexp)
  22740. (setq head0 (match-string-no-properties 4)))
  22741. (setq head (org-link-display-format head0)
  22742. m (org-imenu-new-marker))
  22743. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22744. (if (>= level last-level)
  22745. (push (cons head m) (aref subs level))
  22746. (push (cons head (aref subs (1+ level))) (aref subs level))
  22747. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22748. (setq last-level level))))
  22749. (aref subs 1)))
  22750. (eval-after-load "imenu"
  22751. '(progn
  22752. (add-hook 'imenu-after-jump-hook
  22753. (lambda ()
  22754. (when (derived-mode-p 'org-mode)
  22755. (org-show-context 'org-goto))))))
  22756. (defun org-link-display-format (s)
  22757. "Replace links in string S with their description.
  22758. If there is no description, use the link target."
  22759. (save-match-data
  22760. (replace-regexp-in-string
  22761. org-bracket-link-analytic-regexp
  22762. (lambda (m)
  22763. (if (match-end 5) (match-string 5 m)
  22764. (concat (match-string 1 m) (match-string 3 m))))
  22765. s nil t)))
  22766. (defun org-toggle-link-display ()
  22767. "Toggle the literal or descriptive display of links."
  22768. (interactive)
  22769. (if org-descriptive-links
  22770. (progn (org-remove-from-invisibility-spec '(org-link))
  22771. (org-restart-font-lock)
  22772. (setq org-descriptive-links nil))
  22773. (progn (add-to-invisibility-spec '(org-link))
  22774. (org-restart-font-lock)
  22775. (setq org-descriptive-links t))))
  22776. ;; Speedbar support
  22777. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22778. "Overlay marking the agenda restriction line in speedbar.")
  22779. (overlay-put org-speedbar-restriction-lock-overlay
  22780. 'face 'org-agenda-restriction-lock)
  22781. (overlay-put org-speedbar-restriction-lock-overlay
  22782. 'help-echo "Agendas are currently limited to this item.")
  22783. (delete-overlay org-speedbar-restriction-lock-overlay)
  22784. (defun org-speedbar-set-agenda-restriction ()
  22785. "Restrict future agenda commands to the location at point in speedbar.
  22786. To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
  22787. (interactive)
  22788. (require 'org-agenda)
  22789. (let (p m tp np dir txt)
  22790. (cond
  22791. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22792. 'org-imenu t))
  22793. (setq m (get-text-property p 'org-imenu-marker))
  22794. (with-current-buffer (marker-buffer m)
  22795. (goto-char m)
  22796. (org-agenda-set-restriction-lock 'subtree)))
  22797. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22798. 'speedbar-function 'speedbar-find-file))
  22799. (setq tp (previous-single-property-change
  22800. (1+ p) 'speedbar-function)
  22801. np (next-single-property-change
  22802. tp 'speedbar-function)
  22803. dir (speedbar-line-directory)
  22804. txt (buffer-substring-no-properties (or tp (point-min))
  22805. (or np (point-max))))
  22806. (with-current-buffer (find-file-noselect
  22807. (let ((default-directory dir))
  22808. (expand-file-name txt)))
  22809. (unless (derived-mode-p 'org-mode)
  22810. (user-error "Cannot restrict to non-Org-mode file"))
  22811. (org-agenda-set-restriction-lock 'file)))
  22812. (t (user-error "Don't know how to restrict Org-mode's agenda")))
  22813. (move-overlay org-speedbar-restriction-lock-overlay
  22814. (point-at-bol) (point-at-eol))
  22815. (setq current-prefix-arg nil)
  22816. (org-agenda-maybe-redo)))
  22817. (defvar speedbar-file-key-map)
  22818. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22819. (eval-after-load "speedbar"
  22820. '(progn
  22821. (speedbar-add-supported-extension ".org")
  22822. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22823. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22824. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22825. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22826. (add-hook 'speedbar-visiting-tag-hook
  22827. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22828. ;;; Fixes and Hacks for problems with other packages
  22829. (defun org--flyspell-object-check-p (element)
  22830. "Non-nil when Flyspell can check object at point.
  22831. ELEMENT is the element at point."
  22832. (let ((object (save-excursion
  22833. (when (looking-at-p "\\>") (backward-char))
  22834. (org-element-context element))))
  22835. (cl-case (org-element-type object)
  22836. ;; Prevent checks in links due to keybinding conflict with
  22837. ;; Flyspell.
  22838. ((code entity export-snippet inline-babel-call
  22839. inline-src-block line-break latex-fragment link macro
  22840. statistics-cookie target timestamp verbatim)
  22841. nil)
  22842. (footnote-reference
  22843. ;; Only in inline footnotes, within the definition.
  22844. (and (eq (org-element-property :type object) 'inline)
  22845. (< (save-excursion
  22846. (goto-char (org-element-property :begin object))
  22847. (search-forward ":" nil t 2))
  22848. (point))))
  22849. (otherwise t))))
  22850. (defun org-mode-flyspell-verify ()
  22851. "Function used for `flyspell-generic-check-word-predicate'."
  22852. (if (org-at-heading-p)
  22853. ;; At a headline or an inlinetask, check title only. This is
  22854. ;; faster than relying on `org-element-at-point'.
  22855. (and (save-excursion (beginning-of-line)
  22856. (and (let ((case-fold-search t))
  22857. (not (looking-at "\\*+ END[ \t]*$")))
  22858. (looking-at org-complex-heading-regexp)))
  22859. (match-beginning 4)
  22860. (>= (point) (match-beginning 4))
  22861. (or (not (match-beginning 5))
  22862. (< (point) (match-beginning 5))))
  22863. (let* ((element (org-element-at-point))
  22864. (post-affiliated (org-element-property :post-affiliated element)))
  22865. (cond
  22866. ;; Ignore checks in all affiliated keywords but captions.
  22867. ((< (point) post-affiliated)
  22868. (and (save-excursion
  22869. (beginning-of-line)
  22870. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22871. (> (point) (match-end 0))
  22872. (org--flyspell-object-check-p element)))
  22873. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22874. ((let ((log (org-log-into-drawer)))
  22875. (and log
  22876. (let ((drawer (org-element-lineage element '(drawer))))
  22877. (and drawer
  22878. (eq (compare-strings
  22879. log nil nil
  22880. (org-element-property :drawer-name drawer) nil nil t)
  22881. t)))))
  22882. nil)
  22883. (t
  22884. (cl-case (org-element-type element)
  22885. ((comment quote-section) t)
  22886. (comment-block
  22887. ;; Allow checks between block markers, not on them.
  22888. (and (> (line-beginning-position) post-affiliated)
  22889. (save-excursion
  22890. (end-of-line)
  22891. (skip-chars-forward " \r\t\n")
  22892. (< (point) (org-element-property :end element)))))
  22893. ;; Arbitrary list of keywords where checks are meaningful.
  22894. ;; Make sure point is on the value part of the element.
  22895. (keyword
  22896. (and (member (org-element-property :key element)
  22897. '("DESCRIPTION" "TITLE"))
  22898. (save-excursion
  22899. (search-backward ":" (line-beginning-position) t))))
  22900. ;; Check is globally allowed in paragraphs verse blocks and
  22901. ;; table rows (after affiliated keywords) but some objects
  22902. ;; must not be affected.
  22903. ((paragraph table-row verse-block)
  22904. (let ((cbeg (org-element-property :contents-begin element))
  22905. (cend (org-element-property :contents-end element)))
  22906. (and cbeg (>= (point) cbeg) (< (point) cend)
  22907. (org--flyspell-object-check-p element))))))))))
  22908. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22909. (defun org-remove-flyspell-overlays-in (beg end)
  22910. "Remove flyspell overlays in region."
  22911. (and (bound-and-true-p flyspell-mode)
  22912. (fboundp 'flyspell-delete-region-overlays)
  22913. (flyspell-delete-region-overlays beg end)))
  22914. (defvar flyspell-delayed-commands)
  22915. (eval-after-load "flyspell"
  22916. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22917. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22918. (eval-after-load "bookmark"
  22919. '(if (boundp 'bookmark-after-jump-hook)
  22920. ;; We can use the hook
  22921. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22922. ;; Hook not available, use advice
  22923. (defadvice bookmark-jump (after org-make-visible activate)
  22924. "Make the position visible."
  22925. (org-bookmark-jump-unhide))))
  22926. ;; Make sure saveplace shows the location if it was hidden
  22927. (eval-after-load "saveplace"
  22928. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22929. "Make the position visible."
  22930. (org-bookmark-jump-unhide)))
  22931. ;; Make sure ecb shows the location if it was hidden
  22932. (eval-after-load "ecb"
  22933. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22934. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22935. (when (derived-mode-p 'org-mode)
  22936. (org-show-context))))
  22937. (defun org-bookmark-jump-unhide ()
  22938. "Unhide the current position, to show the bookmark location."
  22939. (and (derived-mode-p 'org-mode)
  22940. (or (outline-invisible-p)
  22941. (save-excursion (goto-char (max (point-min) (1- (point))))
  22942. (outline-invisible-p)))
  22943. (org-show-context 'bookmark-jump)))
  22944. (defun org-mark-jump-unhide ()
  22945. "Make the point visible with `org-show-context' after jumping to the mark."
  22946. (when (and (derived-mode-p 'org-mode)
  22947. (outline-invisible-p))
  22948. (org-show-context 'mark-goto)))
  22949. (eval-after-load "simple"
  22950. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22951. "Make the point visible with `org-show-context'."
  22952. (org-mark-jump-unhide)))
  22953. (eval-after-load "simple"
  22954. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22955. "Make the point visible with `org-show-context'."
  22956. (org-mark-jump-unhide)))
  22957. (eval-after-load "simple"
  22958. '(defadvice pop-global-mark (after org-make-visible activate)
  22959. "Make the point visible with `org-show-context'."
  22960. (org-mark-jump-unhide)))
  22961. ;; Make session.el ignore our circular variable
  22962. (defvar session-globals-exclude)
  22963. (eval-after-load "session"
  22964. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22965. ;;;; Finish up
  22966. (provide 'org)
  22967. (run-hooks 'org-load-hook)
  22968. ;;; org.el ends here